blob: 62332b8b4aaac73a20c5af3f507279539dad85a4 [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"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Sebastian Redlab238a72011-04-24 16:28:06 +000021#include "clang/AST/ASTMutationListener.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000023#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000024#include "clang/AST/DeclVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000026#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000028#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000029#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000032#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000033#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000034#include "llvm/ADT/DenseSet.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000035#include "llvm/ADT/SmallString.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000036#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000037#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000038#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000039
40using namespace clang;
41
Chris Lattner58258242008-04-10 02:22:51 +000042//===----------------------------------------------------------------------===//
43// CheckDefaultArgumentVisitor
44//===----------------------------------------------------------------------===//
45
Chris Lattnerb0d38442008-04-12 23:52:44 +000046namespace {
47 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
48 /// the default argument of a parameter to determine whether it
49 /// contains any ill-formed subexpressions. For example, this will
50 /// diagnose the use of local variables or parameters within the
51 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000052 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000053 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 Expr *DefaultArg;
55 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000056
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 public:
Mike Stump11289f42009-09-09 15:08:12 +000058 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000060
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 bool VisitExpr(Expr *Node);
62 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000063 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 };
Chris Lattner58258242008-04-10 02:22:51 +000065
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 /// VisitExpr - Visit all of the children of this expression.
67 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
68 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000069 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000070 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000071 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000072 }
73
Chris Lattnerb0d38442008-04-12 23:52:44 +000074 /// VisitDeclRefExpr - Visit a reference to a declaration, to
75 /// determine whether this declaration can be used in the default
76 /// argument expression.
77 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000078 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000079 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
80 // C++ [dcl.fct.default]p9
81 // Default arguments are evaluated each time the function is
82 // called. The order of evaluation of function arguments is
83 // unspecified. Consequently, parameters of a function shall not
84 // be used in default argument expressions, even if they are not
85 // evaluated. Parameters of a function declared before a default
86 // argument expression are in scope and can hide namespace and
87 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000088 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000089 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000090 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000091 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000092 // C++ [dcl.fct.default]p7
93 // Local variables shall not be used in default argument
94 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000095 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000096 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000097 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000098 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000099 }
Chris Lattner58258242008-04-10 02:22:51 +0000100
Douglas Gregor8e12c382008-11-04 13:41:56 +0000101 return false;
102 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000103
Douglas Gregor97a9c812008-11-04 14:32:21 +0000104 /// VisitCXXThisExpr - Visit a C++ "this" expression.
105 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
106 // C++ [dcl.fct.default]p8:
107 // The keyword this shall not be used in a default argument of a
108 // member function.
109 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000110 diag::err_param_default_argument_references_this)
111 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000112 }
Chris Lattner58258242008-04-10 02:22:51 +0000113}
114
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000115void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000116 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
Richard Smith938f40b2011-06-11 17:19:42 +0000117 // If we have an MSAny or unknown spec already, don't bother.
118 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000119 return;
120
121 const FunctionProtoType *Proto
122 = Method->getType()->getAs<FunctionProtoType>();
123
124 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
125
126 // If this function can throw any exceptions, make a note of that.
Richard Smith938f40b2011-06-11 17:19:42 +0000127 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000128 ClearExceptions();
129 ComputedEST = EST;
130 return;
131 }
132
Richard Smith938f40b2011-06-11 17:19:42 +0000133 // FIXME: If the call to this decl is using any of its default arguments, we
134 // need to search them for potentially-throwing calls.
135
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000136 // If this function has a basic noexcept, it doesn't affect the outcome.
137 if (EST == EST_BasicNoexcept)
138 return;
139
140 // If we have a throw-all spec at this point, ignore the function.
141 if (ComputedEST == EST_None)
142 return;
143
144 // If we're still at noexcept(true) and there's a nothrow() callee,
145 // change to that specification.
146 if (EST == EST_DynamicNone) {
147 if (ComputedEST == EST_BasicNoexcept)
148 ComputedEST = EST_DynamicNone;
149 return;
150 }
151
152 // Check out noexcept specs.
153 if (EST == EST_ComputedNoexcept) {
Alexis Hunt913820d2011-05-13 06:10:58 +0000154 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000155 assert(NR != FunctionProtoType::NR_NoNoexcept &&
156 "Must have noexcept result for EST_ComputedNoexcept.");
157 assert(NR != FunctionProtoType::NR_Dependent &&
158 "Should not generate implicit declarations for dependent cases, "
159 "and don't know how to handle them anyway.");
160
161 // noexcept(false) -> no spec on the new function
162 if (NR == FunctionProtoType::NR_Throw) {
163 ClearExceptions();
164 ComputedEST = EST_None;
165 }
166 // noexcept(true) won't change anything either.
167 return;
168 }
169
170 assert(EST == EST_Dynamic && "EST case not considered earlier.");
171 assert(ComputedEST != EST_None &&
172 "Shouldn't collect exceptions when throw-all is guaranteed.");
173 ComputedEST = EST_Dynamic;
174 // Record the exceptions in this function's exception specification.
175 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
176 EEnd = Proto->exception_end();
177 E != EEnd; ++E)
Alexis Hunt913820d2011-05-13 06:10:58 +0000178 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
Alexis Hunt6d5b96c2011-05-10 00:49:42 +0000179 Exceptions.push_back(*E);
180}
181
Richard Smith938f40b2011-06-11 17:19:42 +0000182void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
183 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
184 return;
185
186 // FIXME:
187 //
188 // C++0x [except.spec]p14:
NAKAMURA Takumi53648472011-06-21 03:19:28 +0000189 // [An] implicit exception-specification specifies the type-id T if and
190 // only if T is allowed by the exception-specification of a function directly
191 // invoked by f's implicit definition; f shall allow all exceptions if any
Richard Smith938f40b2011-06-11 17:19:42 +0000192 // function it directly invokes allows all exceptions, and f shall allow no
193 // exceptions if every function it directly invokes allows no exceptions.
194 //
195 // Note in particular that if an implicit exception-specification is generated
196 // for a function containing a throw-expression, that specification can still
197 // be noexcept(true).
198 //
199 // Note also that 'directly invoked' is not defined in the standard, and there
200 // is no indication that we should only consider potentially-evaluated calls.
201 //
202 // Ultimately we should implement the intent of the standard: the exception
203 // specification should be the set of exceptions which can be thrown by the
204 // implicit definition. For now, we assume that any non-nothrow expression can
205 // throw any exception.
206
207 if (E->CanThrow(*Context))
208 ComputedEST = EST_None;
209}
210
Anders Carlssonc80a1272009-08-25 02:29:20 +0000211bool
John McCallb268a282010-08-23 23:25:46 +0000212Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000213 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000214 if (RequireCompleteType(Param->getLocation(), Param->getType(),
215 diag::err_typecheck_decl_incomplete_type)) {
216 Param->setInvalidDecl();
217 return true;
218 }
219
Anders Carlssonc80a1272009-08-25 02:29:20 +0000220 // C++ [dcl.fct.default]p5
221 // A default argument expression is implicitly converted (clause
222 // 4) to the parameter type. The default argument expression has
223 // the same semantic constraints as the initializer expression in
224 // a declaration of a variable of the parameter type, using the
225 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000226 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
227 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000228 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
229 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000230 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000231 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000232 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000233 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000234 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000235 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000236
John McCallacf0ee52010-10-08 02:01:28 +0000237 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000238 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000239
Anders Carlssonc80a1272009-08-25 02:29:20 +0000240 // Okay: add the default argument to the parameter
241 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000242
Douglas Gregor758cb672010-10-12 18:23:32 +0000243 // We have already instantiated this parameter; provide each of the
244 // instantiations with the uninstantiated default argument.
245 UnparsedDefaultArgInstantiationsMap::iterator InstPos
246 = UnparsedDefaultArgInstantiations.find(Param);
247 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
248 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
249 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
250
251 // We're done tracking this parameter's instantiations.
252 UnparsedDefaultArgInstantiations.erase(InstPos);
253 }
254
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000255 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000256}
257
Chris Lattner58258242008-04-10 02:22:51 +0000258/// ActOnParamDefaultArgument - Check whether the default argument
259/// provided for a function parameter is well-formed. If so, attach it
260/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000261void
John McCall48871652010-08-21 09:40:31 +0000262Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000263 Expr *DefaultArg) {
264 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000265 return;
Mike Stump11289f42009-09-09 15:08:12 +0000266
John McCall48871652010-08-21 09:40:31 +0000267 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000268 UnparsedDefaultArgLocs.erase(Param);
269
Chris Lattner199abbc2008-04-08 05:04:30 +0000270 // Default arguments are only permitted in C++
271 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000272 Diag(EqualLoc, diag::err_param_default_argument)
273 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000274 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000275 return;
276 }
277
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000278 // Check for unexpanded parameter packs.
279 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
280 Param->setInvalidDecl();
281 return;
282 }
283
Anders Carlssonf1c26952009-08-25 01:02:06 +0000284 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000285 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
286 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000287 Param->setInvalidDecl();
288 return;
289 }
Mike Stump11289f42009-09-09 15:08:12 +0000290
John McCallb268a282010-08-23 23:25:46 +0000291 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000292}
293
Douglas Gregor58354032008-12-24 00:01:03 +0000294/// ActOnParamUnparsedDefaultArgument - We've seen a default
295/// argument for a function parameter, but we can't parse it yet
296/// because we're inside a class definition. Note that this default
297/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000298void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000299 SourceLocation EqualLoc,
300 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000301 if (!param)
302 return;
Mike Stump11289f42009-09-09 15:08:12 +0000303
John McCall48871652010-08-21 09:40:31 +0000304 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000305 if (Param)
306 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000307
Anders Carlsson84613c42009-06-12 16:51:40 +0000308 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000309}
310
Douglas Gregor4d87df52008-12-16 21:30:33 +0000311/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
312/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000313void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000314 if (!param)
315 return;
Mike Stump11289f42009-09-09 15:08:12 +0000316
John McCall48871652010-08-21 09:40:31 +0000317 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000318
Anders Carlsson84613c42009-06-12 16:51:40 +0000319 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000320
Anders Carlsson84613c42009-06-12 16:51:40 +0000321 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000322}
323
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000324/// CheckExtraCXXDefaultArguments - Check for any extra default
325/// arguments in the declarator, which is not a function declaration
326/// or definition and therefore is not permitted to have default
327/// arguments. This routine should be invoked for every declarator
328/// that is not a function declaration or definition.
329void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
330 // C++ [dcl.fct.default]p3
331 // A default argument expression shall be specified only in the
332 // parameter-declaration-clause of a function declaration or in a
333 // template-parameter (14.1). It shall not be specified for a
334 // parameter pack. If it is specified in a
335 // parameter-declaration-clause, it shall not occur within a
336 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000337 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000338 DeclaratorChunk &chunk = D.getTypeObject(i);
339 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000340 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
341 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000342 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000343 if (Param->hasUnparsedDefaultArg()) {
344 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000345 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
346 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
347 delete Toks;
348 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000349 } else if (Param->getDefaultArg()) {
350 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
351 << Param->getDefaultArg()->getSourceRange();
352 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000353 }
354 }
355 }
356 }
357}
358
Chris Lattner199abbc2008-04-08 05:04:30 +0000359// MergeCXXFunctionDecl - Merge two declarations of the same C++
360// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000361// type. Subroutine of MergeFunctionDecl. Returns true if there was an
362// error, false otherwise.
363bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
364 bool Invalid = false;
365
Chris Lattner199abbc2008-04-08 05:04:30 +0000366 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000367 // For non-template functions, default arguments can be added in
368 // later declarations of a function in the same
369 // scope. Declarations in different scopes have completely
370 // distinct sets of default arguments. That is, declarations in
371 // inner scopes do not acquire default arguments from
372 // declarations in outer scopes, and vice versa. In a given
373 // function declaration, all parameters subsequent to a
374 // parameter with a default argument shall have default
375 // arguments supplied in this or previous declarations. A
376 // default argument shall not be redefined by a later
377 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000378 //
379 // C++ [dcl.fct.default]p6:
380 // Except for member functions of class templates, the default arguments
381 // in a member function definition that appears outside of the class
382 // definition are added to the set of default arguments provided by the
383 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000384 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
385 ParmVarDecl *OldParam = Old->getParamDecl(p);
386 ParmVarDecl *NewParam = New->getParamDecl(p);
387
Douglas Gregorc732aba2009-09-11 18:44:32 +0000388 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000389
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000390 unsigned DiagDefaultParamID =
391 diag::err_param_default_argument_redefinition;
392
393 // MSVC accepts that default parameters be redefined for member functions
394 // of template class. The new default parameter's value is ignored.
395 Invalid = true;
Francois Pichet0706d202011-09-17 17:15:52 +0000396 if (getLangOptions().MicrosoftExt) {
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000397 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
398 if (MD && MD->getParent()->getDescribedClassTemplate()) {
Francois Pichet8cb243a2011-04-10 04:58:30 +0000399 // Merge the old default argument into the new parameter.
400 NewParam->setHasInheritedDefaultArg();
401 if (OldParam->hasUninstantiatedDefaultArg())
402 NewParam->setUninstantiatedDefaultArg(
403 OldParam->getUninstantiatedDefaultArg());
404 else
405 NewParam->setDefaultArg(OldParam->getInit());
Francois Pichet93921652011-04-22 08:25:24 +0000406 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000407 Invalid = false;
408 }
409 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000410
Francois Pichet8cb243a2011-04-10 04:58:30 +0000411 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
412 // hint here. Alternatively, we could walk the type-source information
413 // for NewParam to find the last source location in the type... but it
414 // isn't worth the effort right now. This is the kind of test case that
415 // is hard to get right:
Douglas Gregor08dc5842010-01-13 00:12:48 +0000416 // int f(int);
417 // void g(int (*fp)(int) = f);
418 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000419 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000420 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000421
422 // Look for the function declaration where the default argument was
423 // actually written, which may be a declaration prior to Old.
Douglas Gregorec9fd132012-01-14 16:38:05 +0000424 for (FunctionDecl *Older = Old->getPreviousDecl();
425 Older; Older = Older->getPreviousDecl()) {
Douglas Gregorc732aba2009-09-11 18:44:32 +0000426 if (!Older->getParamDecl(p)->hasDefaultArg())
427 break;
428
429 OldParam = Older->getParamDecl(p);
430 }
431
432 Diag(OldParam->getLocation(), diag::note_previous_definition)
433 << OldParam->getDefaultArgRange();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000434 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000435 // Merge the old default argument into the new parameter.
436 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000437 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000438 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000439 if (OldParam->hasUninstantiatedDefaultArg())
440 NewParam->setUninstantiatedDefaultArg(
441 OldParam->getUninstantiatedDefaultArg());
442 else
John McCalle61b02b2010-05-04 01:53:42 +0000443 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000444 } else if (NewParam->hasDefaultArg()) {
445 if (New->getDescribedFunctionTemplate()) {
446 // Paragraph 4, quoted above, only applies to non-template functions.
447 Diag(NewParam->getLocation(),
448 diag::err_param_default_argument_template_redecl)
449 << NewParam->getDefaultArgRange();
450 Diag(Old->getLocation(), diag::note_template_prev_declaration)
451 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000452 } else if (New->getTemplateSpecializationKind()
453 != TSK_ImplicitInstantiation &&
454 New->getTemplateSpecializationKind() != TSK_Undeclared) {
455 // C++ [temp.expr.spec]p21:
456 // Default function arguments shall not be specified in a declaration
457 // or a definition for one of the following explicit specializations:
458 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000459 // - the explicit specialization of a member function template;
460 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000461 // template where the class template specialization to which the
462 // member function specialization belongs is implicitly
463 // instantiated.
464 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
465 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
466 << New->getDeclName()
467 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000468 } else if (New->getDeclContext()->isDependentContext()) {
469 // C++ [dcl.fct.default]p6 (DR217):
470 // Default arguments for a member function of a class template shall
471 // be specified on the initial declaration of the member function
472 // within the class template.
473 //
474 // Reading the tea leaves a bit in DR217 and its reference to DR205
475 // leads me to the conclusion that one cannot add default function
476 // arguments for an out-of-line definition of a member function of a
477 // dependent type.
478 int WhichKind = 2;
479 if (CXXRecordDecl *Record
480 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
481 if (Record->getDescribedClassTemplate())
482 WhichKind = 0;
483 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
484 WhichKind = 1;
485 else
486 WhichKind = 2;
487 }
488
489 Diag(NewParam->getLocation(),
490 diag::err_param_default_argument_member_template_redecl)
491 << WhichKind
492 << NewParam->getDefaultArgRange();
Alexis Huntd051b872011-05-26 01:26:05 +0000493 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
494 CXXSpecialMember NewSM = getSpecialMember(Ctor),
495 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
496 if (NewSM != OldSM) {
497 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
498 << NewParam->getDefaultArgRange() << NewSM;
499 Diag(Old->getLocation(), diag::note_previous_declaration_special)
500 << OldSM;
501 }
Douglas Gregorc732aba2009-09-11 18:44:32 +0000502 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000503 }
504 }
505
Richard Smitheb3c10c2011-10-01 02:31:28 +0000506 // C++0x [dcl.constexpr]p1: If any declaration of a function or function
507 // template has a constexpr specifier then all its declarations shall
508 // contain the constexpr specifier. [Note: An explicit specialization can
509 // differ from the template declaration with respect to the constexpr
510 // specifier. -- end note]
511 //
512 // FIXME: Don't reject changes in constexpr in explicit specializations.
513 if (New->isConstexpr() != Old->isConstexpr()) {
514 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
515 << New << New->isConstexpr();
516 Diag(Old->getLocation(), diag::note_previous_declaration);
517 Invalid = true;
518 }
519
Douglas Gregorf40863c2010-02-12 07:32:17 +0000520 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000521 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000522
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000523 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000524}
525
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000526/// \brief Merge the exception specifications of two variable declarations.
527///
528/// This is called when there's a redeclaration of a VarDecl. The function
529/// checks if the redeclaration might have an exception specification and
530/// validates compatibility and merges the specs if necessary.
531void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
532 // Shortcut if exceptions are disabled.
533 if (!getLangOptions().CXXExceptions)
534 return;
535
536 assert(Context.hasSameType(New->getType(), Old->getType()) &&
537 "Should only be called if types are otherwise the same.");
538
539 QualType NewType = New->getType();
540 QualType OldType = Old->getType();
541
542 // We're only interested in pointers and references to functions, as well
543 // as pointers to member functions.
544 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
545 NewType = R->getPointeeType();
546 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
547 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
548 NewType = P->getPointeeType();
549 OldType = OldType->getAs<PointerType>()->getPointeeType();
550 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
551 NewType = M->getPointeeType();
552 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
553 }
554
555 if (!NewType->isFunctionProtoType())
556 return;
557
558 // There's lots of special cases for functions. For function pointers, system
559 // libraries are hopefully not as broken so that we don't need these
560 // workarounds.
561 if (CheckEquivalentExceptionSpec(
562 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
563 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
564 New->setInvalidDecl();
565 }
566}
567
Chris Lattner199abbc2008-04-08 05:04:30 +0000568/// CheckCXXDefaultArguments - Verify that the default arguments for a
569/// function declaration are well-formed according to C++
570/// [dcl.fct.default].
571void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
572 unsigned NumParams = FD->getNumParams();
573 unsigned p;
574
575 // Find first parameter with a default argument
576 for (p = 0; p < NumParams; ++p) {
577 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000578 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000579 break;
580 }
581
582 // C++ [dcl.fct.default]p4:
583 // In a given function declaration, all parameters
584 // subsequent to a parameter with a default argument shall
585 // have default arguments supplied in this or previous
586 // declarations. A default argument shall not be redefined
587 // by a later declaration (not even to the same value).
588 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000589 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000590 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000591 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000592 if (Param->isInvalidDecl())
593 /* We already complained about this parameter. */;
594 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000595 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000596 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000597 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000598 else
Mike Stump11289f42009-09-09 15:08:12 +0000599 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000600 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000601
Chris Lattner199abbc2008-04-08 05:04:30 +0000602 LastMissingDefaultArg = p;
603 }
604 }
605
606 if (LastMissingDefaultArg > 0) {
607 // Some default arguments were missing. Clear out all of the
608 // default arguments up to (and including) the last missing
609 // default argument, so that we leave the function parameters
610 // in a semantically valid state.
611 for (p = 0; p <= LastMissingDefaultArg; ++p) {
612 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000613 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000614 Param->setDefaultArg(0);
615 }
616 }
617 }
618}
Douglas Gregor556877c2008-04-13 21:30:24 +0000619
Richard Smitheb3c10c2011-10-01 02:31:28 +0000620// CheckConstexprParameterTypes - Check whether a function's parameter types
621// are all literal types. If so, return true. If not, produce a suitable
622// diagnostic depending on @p CCK and return false.
623static bool CheckConstexprParameterTypes(Sema &SemaRef, const FunctionDecl *FD,
624 Sema::CheckConstexprKind CCK) {
625 unsigned ArgIndex = 0;
626 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
627 for (FunctionProtoType::arg_type_iterator i = FT->arg_type_begin(),
628 e = FT->arg_type_end(); i != e; ++i, ++ArgIndex) {
629 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
630 SourceLocation ParamLoc = PD->getLocation();
631 if (!(*i)->isDependentType() &&
632 SemaRef.RequireLiteralType(ParamLoc, *i, CCK == Sema::CCK_Declaration ?
633 SemaRef.PDiag(diag::err_constexpr_non_literal_param)
634 << ArgIndex+1 << PD->getSourceRange()
635 << isa<CXXConstructorDecl>(FD) :
636 SemaRef.PDiag(),
637 /*AllowIncompleteType*/ true)) {
638 if (CCK == Sema::CCK_NoteNonConstexprInstantiation)
639 SemaRef.Diag(ParamLoc, diag::note_constexpr_tmpl_non_literal_param)
640 << ArgIndex+1 << PD->getSourceRange()
641 << isa<CXXConstructorDecl>(FD) << *i;
642 return false;
643 }
644 }
645 return true;
646}
647
648// CheckConstexprFunctionDecl - Check whether a function declaration satisfies
649// the requirements of a constexpr function declaration or a constexpr
650// constructor declaration. Return true if it does, false if not.
651//
Richard Smith7971b692012-01-13 04:54:00 +0000652// This implements C++11 [dcl.constexpr]p3,4, as amended by N3308.
Richard Smitheb3c10c2011-10-01 02:31:28 +0000653//
654// \param CCK Specifies whether to produce diagnostics if the function does not
655// satisfy the requirements.
656bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD,
657 CheckConstexprKind CCK) {
658 assert((CCK != CCK_NoteNonConstexprInstantiation ||
659 (NewFD->getTemplateInstantiationPattern() &&
660 NewFD->getTemplateInstantiationPattern()->isConstexpr())) &&
661 "only constexpr templates can be instantiated non-constexpr");
662
Richard Smith7971b692012-01-13 04:54:00 +0000663 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
664 if (MD && MD->isInstance()) {
665 // C++11 [dcl.constexpr]p4: In the definition of a constexpr constructor...
Richard Smitheb3c10c2011-10-01 02:31:28 +0000666 // In addition, either its function-body shall be = delete or = default or
667 // it shall satisfy the following constraints:
668 // - the class shall not have any virtual base classes;
Richard Smith7971b692012-01-13 04:54:00 +0000669 //
670 // We apply this to constexpr member functions too: the class cannot be a
671 // literal type, so the members are not permitted to be constexpr.
672 const CXXRecordDecl *RD = MD->getParent();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000673 if (RD->getNumVBases()) {
674 // Note, this is still illegal if the body is = default, since the
675 // implicit body does not satisfy the requirements of a constexpr
676 // constructor. We also reject cases where the body is = delete, as
677 // required by N3308.
678 if (CCK != CCK_Instantiation) {
679 Diag(NewFD->getLocation(),
680 CCK == CCK_Declaration ? diag::err_constexpr_virtual_base
681 : diag::note_constexpr_tmpl_virtual_base)
Richard Smith7971b692012-01-13 04:54:00 +0000682 << isa<CXXConstructorDecl>(NewFD) << RD->isStruct()
683 << RD->getNumVBases();
Richard Smitheb3c10c2011-10-01 02:31:28 +0000684 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
685 E = RD->vbases_end(); I != E; ++I)
686 Diag(I->getSourceRange().getBegin(),
687 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
688 }
689 return false;
690 }
Richard Smith7971b692012-01-13 04:54:00 +0000691 }
692
693 if (!isa<CXXConstructorDecl>(NewFD)) {
694 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000695 // The definition of a constexpr function shall satisfy the following
696 // constraints:
697 // - it shall not be virtual;
698 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
699 if (Method && Method->isVirtual()) {
700 if (CCK != CCK_Instantiation) {
701 Diag(NewFD->getLocation(),
702 CCK == CCK_Declaration ? diag::err_constexpr_virtual
703 : diag::note_constexpr_tmpl_virtual);
704
705 // If it's not obvious why this function is virtual, find an overridden
706 // function which uses the 'virtual' keyword.
707 const CXXMethodDecl *WrittenVirtual = Method;
708 while (!WrittenVirtual->isVirtualAsWritten())
709 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
710 if (WrittenVirtual != Method)
Richard Smith7971b692012-01-13 04:54:00 +0000711 Diag(WrittenVirtual->getLocation(),
Richard Smitheb3c10c2011-10-01 02:31:28 +0000712 diag::note_overridden_virtual_function);
713 }
714 return false;
715 }
716
717 // - its return type shall be a literal type;
718 QualType RT = NewFD->getResultType();
719 if (!RT->isDependentType() &&
720 RequireLiteralType(NewFD->getLocation(), RT, CCK == CCK_Declaration ?
721 PDiag(diag::err_constexpr_non_literal_return) :
722 PDiag(),
723 /*AllowIncompleteType*/ true)) {
724 if (CCK == CCK_NoteNonConstexprInstantiation)
725 Diag(NewFD->getLocation(),
726 diag::note_constexpr_tmpl_non_literal_return) << RT;
727 return false;
728 }
Richard Smitheb3c10c2011-10-01 02:31:28 +0000729 }
730
Richard Smith7971b692012-01-13 04:54:00 +0000731 // - each of its parameter types shall be a literal type;
732 if (!CheckConstexprParameterTypes(*this, NewFD, CCK))
733 return false;
734
Richard Smitheb3c10c2011-10-01 02:31:28 +0000735 return true;
736}
737
738/// Check the given declaration statement is legal within a constexpr function
739/// body. C++0x [dcl.constexpr]p3,p4.
740///
741/// \return true if the body is OK, false if we have diagnosed a problem.
742static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
743 DeclStmt *DS) {
744 // C++0x [dcl.constexpr]p3 and p4:
745 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
746 // contain only
747 for (DeclStmt::decl_iterator DclIt = DS->decl_begin(),
748 DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt) {
749 switch ((*DclIt)->getKind()) {
750 case Decl::StaticAssert:
751 case Decl::Using:
752 case Decl::UsingShadow:
753 case Decl::UsingDirective:
754 case Decl::UnresolvedUsingTypename:
755 // - static_assert-declarations
756 // - using-declarations,
757 // - using-directives,
758 continue;
759
760 case Decl::Typedef:
761 case Decl::TypeAlias: {
762 // - typedef declarations and alias-declarations that do not define
763 // classes or enumerations,
764 TypedefNameDecl *TN = cast<TypedefNameDecl>(*DclIt);
765 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
766 // Don't allow variably-modified types in constexpr functions.
767 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
768 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
769 << TL.getSourceRange() << TL.getType()
770 << isa<CXXConstructorDecl>(Dcl);
771 return false;
772 }
773 continue;
774 }
775
776 case Decl::Enum:
777 case Decl::CXXRecord:
778 // As an extension, we allow the declaration (but not the definition) of
779 // classes and enumerations in all declarations, not just in typedef and
780 // alias declarations.
781 if (cast<TagDecl>(*DclIt)->isThisDeclarationADefinition()) {
782 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_type_definition)
783 << isa<CXXConstructorDecl>(Dcl);
784 return false;
785 }
786 continue;
787
788 case Decl::Var:
789 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_var_declaration)
790 << isa<CXXConstructorDecl>(Dcl);
791 return false;
792
793 default:
794 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
795 << isa<CXXConstructorDecl>(Dcl);
796 return false;
797 }
798 }
799
800 return true;
801}
802
803/// Check that the given field is initialized within a constexpr constructor.
804///
805/// \param Dcl The constexpr constructor being checked.
806/// \param Field The field being checked. This may be a member of an anonymous
807/// struct or union nested within the class being checked.
808/// \param Inits All declarations, including anonymous struct/union members and
809/// indirect members, for which any initialization was provided.
810/// \param Diagnosed Set to true if an error is produced.
811static void CheckConstexprCtorInitializer(Sema &SemaRef,
812 const FunctionDecl *Dcl,
813 FieldDecl *Field,
814 llvm::SmallSet<Decl*, 16> &Inits,
815 bool &Diagnosed) {
Douglas Gregor556e5862011-10-10 17:22:13 +0000816 if (Field->isUnnamedBitfield())
817 return;
818
Richard Smitheb3c10c2011-10-01 02:31:28 +0000819 if (!Inits.count(Field)) {
820 if (!Diagnosed) {
821 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
822 Diagnosed = true;
823 }
824 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
825 } else if (Field->isAnonymousStructOrUnion()) {
826 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
827 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
828 I != E; ++I)
829 // If an anonymous union contains an anonymous struct of which any member
830 // is initialized, all members must be initialized.
831 if (!RD->isUnion() || Inits.count(*I))
832 CheckConstexprCtorInitializer(SemaRef, Dcl, *I, Inits, Diagnosed);
833 }
834}
835
836/// Check the body for the given constexpr function declaration only contains
837/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
838///
839/// \return true if the body is OK, false if we have diagnosed a problem.
Richard Smith2de5a932012-02-05 02:30:54 +0000840bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body,
841 bool IsInstantiation) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000842 if (isa<CXXTryStmt>(Body)) {
Richard Smith74388b42012-02-04 00:33:54 +0000843 // C++11 [dcl.constexpr]p3:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000844 // The definition of a constexpr function shall satisfy the following
845 // constraints: [...]
846 // - its function-body shall be = delete, = default, or a
847 // compound-statement
848 //
Richard Smith74388b42012-02-04 00:33:54 +0000849 // C++11 [dcl.constexpr]p4:
Richard Smitheb3c10c2011-10-01 02:31:28 +0000850 // In the definition of a constexpr constructor, [...]
851 // - its function-body shall not be a function-try-block;
852 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
853 << isa<CXXConstructorDecl>(Dcl);
854 return false;
855 }
856
857 // - its function-body shall be [...] a compound-statement that contains only
858 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
859
860 llvm::SmallVector<SourceLocation, 4> ReturnStmts;
861 for (CompoundStmt::body_iterator BodyIt = CompBody->body_begin(),
862 BodyEnd = CompBody->body_end(); BodyIt != BodyEnd; ++BodyIt) {
863 switch ((*BodyIt)->getStmtClass()) {
864 case Stmt::NullStmtClass:
865 // - null statements,
866 continue;
867
868 case Stmt::DeclStmtClass:
869 // - static_assert-declarations
870 // - using-declarations,
871 // - using-directives,
872 // - typedef declarations and alias-declarations that do not define
873 // classes or enumerations,
874 if (!CheckConstexprDeclStmt(*this, Dcl, cast<DeclStmt>(*BodyIt)))
875 return false;
876 continue;
877
878 case Stmt::ReturnStmtClass:
879 // - and exactly one return statement;
880 if (isa<CXXConstructorDecl>(Dcl))
881 break;
882
883 ReturnStmts.push_back((*BodyIt)->getLocStart());
884 // FIXME
885 // - every constructor call and implicit conversion used in initializing
886 // the return value shall be one of those allowed in a constant
887 // expression.
888 // Deal with this as part of a general check that the function can produce
889 // a constant expression (for [dcl.constexpr]p5).
890 continue;
891
892 default:
893 break;
894 }
895
896 Diag((*BodyIt)->getLocStart(), diag::err_constexpr_body_invalid_stmt)
897 << isa<CXXConstructorDecl>(Dcl);
898 return false;
899 }
900
901 if (const CXXConstructorDecl *Constructor
902 = dyn_cast<CXXConstructorDecl>(Dcl)) {
903 const CXXRecordDecl *RD = Constructor->getParent();
904 // - every non-static data member and base class sub-object shall be
905 // initialized;
906 if (RD->isUnion()) {
907 // DR1359: Exactly one member of a union shall be initialized.
908 if (Constructor->getNumCtorInitializers() == 0) {
909 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
910 return false;
911 }
Richard Smithf368fb42011-10-10 16:38:04 +0000912 } else if (!Constructor->isDependentContext() &&
913 !Constructor->isDelegatingConstructor()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +0000914 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
915
916 // Skip detailed checking if we have enough initializers, and we would
917 // allow at most one initializer per member.
918 bool AnyAnonStructUnionMembers = false;
919 unsigned Fields = 0;
920 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
921 E = RD->field_end(); I != E; ++I, ++Fields) {
922 if ((*I)->isAnonymousStructOrUnion()) {
923 AnyAnonStructUnionMembers = true;
924 break;
925 }
926 }
927 if (AnyAnonStructUnionMembers ||
928 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
929 // Check initialization of non-static data members. Base classes are
930 // always initialized so do not need to be checked. Dependent bases
931 // might not have initializers in the member initializer list.
932 llvm::SmallSet<Decl*, 16> Inits;
933 for (CXXConstructorDecl::init_const_iterator
934 I = Constructor->init_begin(), E = Constructor->init_end();
935 I != E; ++I) {
936 if (FieldDecl *FD = (*I)->getMember())
937 Inits.insert(FD);
938 else if (IndirectFieldDecl *ID = (*I)->getIndirectMember())
939 Inits.insert(ID->chain_begin(), ID->chain_end());
940 }
941
942 bool Diagnosed = false;
943 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
944 E = RD->field_end(); I != E; ++I)
945 CheckConstexprCtorInitializer(*this, Dcl, *I, Inits, Diagnosed);
946 if (Diagnosed)
947 return false;
948 }
949 }
950
951 // FIXME
952 // - every constructor involved in initializing non-static data members
953 // and base class sub-objects shall be a constexpr constructor;
954 // - every assignment-expression that is an initializer-clause appearing
955 // directly or indirectly within a brace-or-equal-initializer for
956 // a non-static data member that is not named by a mem-initializer-id
957 // shall be a constant expression; and
958 // - every implicit conversion used in converting a constructor argument
959 // to the corresponding parameter type and converting
960 // a full-expression to the corresponding member type shall be one of
961 // those allowed in a constant expression.
962 // Deal with these as part of a general check that the function can produce
963 // a constant expression (for [dcl.constexpr]p5).
964 } else {
965 if (ReturnStmts.empty()) {
966 Diag(Dcl->getLocation(), diag::err_constexpr_body_no_return);
967 return false;
968 }
969 if (ReturnStmts.size() > 1) {
970 Diag(ReturnStmts.back(), diag::err_constexpr_body_multiple_return);
971 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
972 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
973 return false;
974 }
975 }
976
Richard Smith74388b42012-02-04 00:33:54 +0000977 // C++11 [dcl.constexpr]p5:
978 // if no function argument values exist such that the function invocation
979 // substitution would produce a constant expression, the program is
980 // ill-formed; no diagnostic required.
981 // C++11 [dcl.constexpr]p3:
982 // - every constructor call and implicit conversion used in initializing the
983 // return value shall be one of those allowed in a constant expression.
984 // C++11 [dcl.constexpr]p4:
985 // - every constructor involved in initializing non-static data members and
986 // base class sub-objects shall be a constexpr constructor.
Richard Smith253c2a32012-01-27 01:14:48 +0000987 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smithda7c4ba2012-02-08 06:14:53 +0000988 if (!IsInstantiation && !Expr::isPotentialConstantExpr(Dcl, Diags)) {
Richard Smith253c2a32012-01-27 01:14:48 +0000989 Diag(Dcl->getLocation(), diag::err_constexpr_function_never_constant_expr)
990 << isa<CXXConstructorDecl>(Dcl);
991 for (size_t I = 0, N = Diags.size(); I != N; ++I)
992 Diag(Diags[I].first, Diags[I].second);
993 return false;
994 }
995
Richard Smitheb3c10c2011-10-01 02:31:28 +0000996 return true;
997}
998
Douglas Gregor61956c42008-10-31 09:07:45 +0000999/// isCurrentClassName - Determine whether the identifier II is the
1000/// name of the class type currently being defined. In the case of
1001/// nested classes, this will only return true if II is the name of
1002/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00001003bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
1004 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +00001005 assert(getLangOptions().CPlusPlus && "No class names in C!");
1006
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001007 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +00001008 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +00001009 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001010 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
1011 } else
1012 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
1013
Douglas Gregor1aa3edb2010-02-05 06:12:42 +00001014 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +00001015 return &II == CurDecl->getIdentifier();
1016 else
1017 return false;
1018}
1019
Mike Stump11289f42009-09-09 15:08:12 +00001020/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +00001021///
1022/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
1023/// and returns NULL otherwise.
1024CXXBaseSpecifier *
1025Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
1026 SourceRange SpecifierRange,
1027 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001028 TypeSourceInfo *TInfo,
1029 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +00001030 QualType BaseType = TInfo->getType();
1031
Douglas Gregor463421d2009-03-03 04:44:36 +00001032 // C++ [class.union]p1:
1033 // A union shall not have base classes.
1034 if (Class->isUnion()) {
1035 Diag(Class->getLocation(), diag::err_base_clause_on_union)
1036 << SpecifierRange;
1037 return 0;
1038 }
1039
Douglas Gregor752a5952011-01-03 22:36:02 +00001040 if (EllipsisLoc.isValid() &&
1041 !TInfo->getType()->containsUnexpandedParameterPack()) {
1042 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1043 << TInfo->getTypeLoc().getSourceRange();
1044 EllipsisLoc = SourceLocation();
1045 }
1046
Douglas Gregor463421d2009-03-03 04:44:36 +00001047 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +00001048 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001049 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001050 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +00001051
1052 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +00001053
1054 // Base specifiers must be record types.
1055 if (!BaseType->isRecordType()) {
1056 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
1057 return 0;
1058 }
1059
1060 // C++ [class.union]p1:
1061 // A union shall not be used as a base class.
1062 if (BaseType->isUnionType()) {
1063 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
1064 return 0;
1065 }
1066
1067 // C++ [class.derived]p2:
1068 // The class-name in a base-specifier shall not be an incompletely
1069 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +00001070 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +00001071 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +00001072 << SpecifierRange)) {
1073 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001074 return 0;
John McCall3696dcb2010-08-17 07:23:57 +00001075 }
Douglas Gregor463421d2009-03-03 04:44:36 +00001076
Eli Friedmanc96d4962009-08-15 21:55:26 +00001077 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001078 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +00001079 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001080 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +00001081 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +00001082 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
1083 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +00001084
Anders Carlsson65c76d32011-03-25 14:55:14 +00001085 // C++ [class]p3:
1086 // If a class is marked final and it appears as a base-type-specifier in
1087 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +00001088 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +00001089 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
1090 << CXXBaseDecl->getDeclName();
1091 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
1092 << CXXBaseDecl->getDeclName();
1093 return 0;
1094 }
1095
John McCall3696dcb2010-08-17 07:23:57 +00001096 if (BaseDecl->isInvalidDecl())
1097 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001098
1099 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001100 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +00001101 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +00001102 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +00001103}
1104
Douglas Gregor556877c2008-04-13 21:30:24 +00001105/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
1106/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +00001107/// example:
1108/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +00001109/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +00001110BaseResult
John McCall48871652010-08-21 09:40:31 +00001111Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +00001112 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +00001113 ParsedType basetype, SourceLocation BaseLoc,
1114 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001115 if (!classdecl)
1116 return true;
1117
Douglas Gregorc40290e2009-03-09 23:48:35 +00001118 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +00001119 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +00001120 if (!Class)
1121 return true;
1122
Nick Lewycky19b9f952010-07-26 16:56:01 +00001123 TypeSourceInfo *TInfo = 0;
1124 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +00001125
Douglas Gregor752a5952011-01-03 22:36:02 +00001126 if (EllipsisLoc.isInvalid() &&
1127 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +00001128 UPPC_BaseType))
1129 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +00001130
Douglas Gregor463421d2009-03-03 04:44:36 +00001131 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +00001132 Virtual, Access, TInfo,
1133 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001134 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +00001135
Douglas Gregor463421d2009-03-03 04:44:36 +00001136 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001137}
Douglas Gregor556877c2008-04-13 21:30:24 +00001138
Douglas Gregor463421d2009-03-03 04:44:36 +00001139/// \brief Performs the actual work of attaching the given base class
1140/// specifiers to a C++ class.
1141bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
1142 unsigned NumBases) {
1143 if (NumBases == 0)
1144 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +00001145
1146 // Used to keep track of which base types we have already seen, so
1147 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001148 // that the key is always the unqualified canonical type of the base
1149 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +00001150 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
1151
1152 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001153 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +00001154 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001155 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +00001156 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +00001157 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001158 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor29a92472008-10-22 17:49:05 +00001159 if (KnownBaseTypes[NewBaseType]) {
1160 // C++ [class.mi]p3:
1161 // A class shall not be specified as a direct base class of a
1162 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +00001163 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00001164 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001165 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +00001166 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001167
1168 // Delete the duplicate base class specifier; we're going to
1169 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001170 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001171
1172 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +00001173 } else {
1174 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +00001175 KnownBaseTypes[NewBaseType] = Bases[idx];
1176 Bases[NumGoodBases++] = Bases[idx];
Fariborz Jahanian28f5fb92011-10-24 17:30:45 +00001177 if (const RecordType *Record = NewBaseType->getAs<RecordType>())
Fariborz Jahanian47f9a732011-10-21 22:27:12 +00001178 if (const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl()))
1179 if (RD->hasAttr<WeakAttr>())
1180 Class->addAttr(::new (Context) WeakAttr(SourceRange(), Context));
Douglas Gregor29a92472008-10-22 17:49:05 +00001181 }
1182 }
1183
1184 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +00001185 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +00001186
1187 // Delete the remaining (good) base class specifiers, since their
1188 // data has been copied into the CXXRecordDecl.
1189 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +00001190 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +00001191
1192 return Invalid;
1193}
1194
1195/// ActOnBaseSpecifiers - Attach the given base specifiers to the
1196/// class, after checking whether there are any duplicate base
1197/// classes.
Richard Trieu9becef62011-09-09 03:18:59 +00001198void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +00001199 unsigned NumBases) {
1200 if (!ClassDecl || !Bases || !NumBases)
1201 return;
1202
1203 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +00001204 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +00001205 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +00001206}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00001207
John McCalle78aac42010-03-10 03:28:59 +00001208static CXXRecordDecl *GetClassForType(QualType T) {
1209 if (const RecordType *RT = T->getAs<RecordType>())
1210 return cast<CXXRecordDecl>(RT->getDecl());
1211 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
1212 return ICT->getDecl();
1213 else
1214 return 0;
1215}
1216
Douglas Gregor36d1b142009-10-06 17:59:45 +00001217/// \brief Determine whether the type \p Derived is a C++ class that is
1218/// derived from the type \p Base.
1219bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
1220 if (!getLangOptions().CPlusPlus)
1221 return false;
John McCalle78aac42010-03-10 03:28:59 +00001222
1223 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1224 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001225 return false;
1226
John McCalle78aac42010-03-10 03:28:59 +00001227 CXXRecordDecl *BaseRD = GetClassForType(Base);
1228 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001229 return false;
1230
John McCall67da35c2010-02-04 22:26:26 +00001231 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
1232 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001233}
1234
1235/// \brief Determine whether the type \p Derived is a C++ class that is
1236/// derived from the type \p Base.
1237bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
1238 if (!getLangOptions().CPlusPlus)
1239 return false;
1240
John McCalle78aac42010-03-10 03:28:59 +00001241 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
1242 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001243 return false;
1244
John McCalle78aac42010-03-10 03:28:59 +00001245 CXXRecordDecl *BaseRD = GetClassForType(Base);
1246 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +00001247 return false;
1248
Douglas Gregor36d1b142009-10-06 17:59:45 +00001249 return DerivedRD->isDerivedFrom(BaseRD, Paths);
1250}
1251
Anders Carlssona70cff62010-04-24 19:06:50 +00001252void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +00001253 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001254 assert(BasePathArray.empty() && "Base path array must be empty!");
1255 assert(Paths.isRecordingPaths() && "Must record paths!");
1256
1257 const CXXBasePath &Path = Paths.front();
1258
1259 // We first go backward and check if we have a virtual base.
1260 // FIXME: It would be better if CXXBasePath had the base specifier for
1261 // the nearest virtual base.
1262 unsigned Start = 0;
1263 for (unsigned I = Path.size(); I != 0; --I) {
1264 if (Path[I - 1].Base->isVirtual()) {
1265 Start = I - 1;
1266 break;
1267 }
1268 }
1269
1270 // Now add all bases.
1271 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +00001272 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +00001273}
1274
Douglas Gregor88d292c2010-05-13 16:44:06 +00001275/// \brief Determine whether the given base path includes a virtual
1276/// base class.
John McCallcf142162010-08-07 06:22:56 +00001277bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
1278 for (CXXCastPath::const_iterator B = BasePath.begin(),
1279 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +00001280 B != BEnd; ++B)
1281 if ((*B)->isVirtual())
1282 return true;
1283
1284 return false;
1285}
1286
Douglas Gregor36d1b142009-10-06 17:59:45 +00001287/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
1288/// conversion (where Derived and Base are class types) is
1289/// well-formed, meaning that the conversion is unambiguous (and
1290/// that all of the base classes are accessible). Returns true
1291/// and emits a diagnostic if the code is ill-formed, returns false
1292/// otherwise. Loc is the location where this routine should point to
1293/// if there is an error, and Range is the source range to highlight
1294/// if there is an error.
1295bool
1296Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +00001297 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001298 unsigned AmbigiousBaseConvID,
1299 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001300 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +00001301 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001302 // First, determine whether the path from Derived to Base is
1303 // ambiguous. This is slightly more expensive than checking whether
1304 // the Derived to Base conversion exists, because here we need to
1305 // explore multiple paths to determine if there is an ambiguity.
1306 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1307 /*DetectVirtual=*/false);
1308 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
1309 assert(DerivationOkay &&
1310 "Can only be used with a derived-to-base conversion");
1311 (void)DerivationOkay;
1312
1313 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +00001314 if (InaccessibleBaseID) {
1315 // Check that the base class can be accessed.
1316 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
1317 InaccessibleBaseID)) {
1318 case AR_inaccessible:
1319 return true;
1320 case AR_accessible:
1321 case AR_dependent:
1322 case AR_delayed:
1323 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +00001324 }
John McCall5b0829a2010-02-10 09:31:12 +00001325 }
Anders Carlssona70cff62010-04-24 19:06:50 +00001326
1327 // Build a base path if necessary.
1328 if (BasePath)
1329 BuildBasePathArray(Paths, *BasePath);
1330 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +00001331 }
1332
1333 // We know that the derived-to-base conversion is ambiguous, and
1334 // we're going to produce a diagnostic. Perform the derived-to-base
1335 // search just one more time to compute all of the possible paths so
1336 // that we can print them out. This is more expensive than any of
1337 // the previous derived-to-base checks we've done, but at this point
1338 // performance isn't as much of an issue.
1339 Paths.clear();
1340 Paths.setRecordingPaths(true);
1341 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
1342 assert(StillOkay && "Can only be used with a derived-to-base conversion");
1343 (void)StillOkay;
1344
1345 // Build up a textual representation of the ambiguous paths, e.g.,
1346 // D -> B -> A, that will be used to illustrate the ambiguous
1347 // conversions in the diagnostic. We only print one of the paths
1348 // to each base class subobject.
1349 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1350
1351 Diag(Loc, AmbigiousBaseConvID)
1352 << Derived << Base << PathDisplayStr << Range << Name;
1353 return true;
1354}
1355
1356bool
1357Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +00001358 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +00001359 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001360 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +00001361 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +00001362 IgnoreAccess ? 0
1363 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001364 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +00001365 Loc, Range, DeclarationName(),
1366 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +00001367}
1368
1369
1370/// @brief Builds a string representing ambiguous paths from a
1371/// specific derived class to different subobjects of the same base
1372/// class.
1373///
1374/// This function builds a string that can be used in error messages
1375/// to show the different paths that one can take through the
1376/// inheritance hierarchy to go from the derived class to different
1377/// subobjects of a base class. The result looks something like this:
1378/// @code
1379/// struct D -> struct B -> struct A
1380/// struct D -> struct C -> struct A
1381/// @endcode
1382std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
1383 std::string PathDisplayStr;
1384 std::set<unsigned> DisplayedPaths;
1385 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1386 Path != Paths.end(); ++Path) {
1387 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
1388 // We haven't displayed a path to this particular base
1389 // class subobject yet.
1390 PathDisplayStr += "\n ";
1391 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1392 for (CXXBasePath::const_iterator Element = Path->begin();
1393 Element != Path->end(); ++Element)
1394 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1395 }
1396 }
1397
1398 return PathDisplayStr;
1399}
1400
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001401//===----------------------------------------------------------------------===//
1402// C++ class member Handling
1403//===----------------------------------------------------------------------===//
1404
Abramo Bagnarad7340582010-06-05 05:09:32 +00001405/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001406bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1407 SourceLocation ASLoc,
1408 SourceLocation ColonLoc,
1409 AttributeList *Attrs) {
Abramo Bagnarad7340582010-06-05 05:09:32 +00001410 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +00001411 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +00001412 ASLoc, ColonLoc);
1413 CurContext->addHiddenDecl(ASDecl);
Erik Verbruggenca98f2a2011-10-13 09:41:32 +00001414 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
Abramo Bagnarad7340582010-06-05 05:09:32 +00001415}
1416
Anders Carlssonfd835532011-01-20 05:57:14 +00001417/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +00001418void Sema::CheckOverrideControl(const Decl *D) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001419 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
Anders Carlssonfd835532011-01-20 05:57:14 +00001420 if (!MD || !MD->isVirtual())
1421 return;
1422
Anders Carlssonfa8e5d32011-01-20 06:33:26 +00001423 if (MD->isDependentContext())
1424 return;
1425
Anders Carlssonfd835532011-01-20 05:57:14 +00001426 // C++0x [class.virtual]p3:
1427 // If a virtual function is marked with the virt-specifier override and does
1428 // not override a member function of a base class,
1429 // the program is ill-formed.
1430 bool HasOverriddenMethods =
1431 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +00001432 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +00001433 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +00001434 diag::err_function_marked_override_not_overriding)
1435 << MD->getDeclName();
1436 return;
1437 }
1438}
1439
Anders Carlsson3f610c72011-01-20 16:25:36 +00001440/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1441/// function overrides a virtual member function marked 'final', according to
1442/// C++0x [class.virtual]p3.
1443bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1444 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +00001445 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +00001446 return false;
1447
1448 Diag(New->getLocation(), diag::err_final_function_overridden)
1449 << New->getDeclName();
1450 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1451 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +00001452}
1453
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001454/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1455/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
Richard Smith938f40b2011-06-11 17:19:42 +00001456/// bitfield width if there is one, 'InitExpr' specifies the initializer if
1457/// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1458/// present but parsing it has been deferred.
John McCall48871652010-08-21 09:40:31 +00001459Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001460Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +00001461 MultiTemplateParamsArg TemplateParameterLists,
Richard Trieu2bd04012011-09-09 02:00:50 +00001462 Expr *BW, const VirtSpecifiers &VS,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001463 bool HasDeferredInit) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001464 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001465 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1466 DeclarationName Name = NameInfo.getName();
1467 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +00001468
1469 // For anonymous bitfields, the location should point to the type.
1470 if (Loc.isInvalid())
1471 Loc = D.getSourceRange().getBegin();
1472
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001473 Expr *BitWidth = static_cast<Expr*>(BW);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001474
John McCallb1cd7da2010-06-04 08:34:12 +00001475 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +00001476 assert(!DS.isFriendSpecified());
1477
Richard Smithcfcdf3a2011-06-25 02:28:38 +00001478 bool isFunc = D.isDeclarationOfFunction();
John McCallb1cd7da2010-06-04 08:34:12 +00001479
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001480 // C++ 9.2p6: A member shall not be declared to have automatic storage
1481 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001482 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1483 // data members and cannot be applied to names declared const or static,
1484 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001485 switch (DS.getStorageClassSpec()) {
1486 case DeclSpec::SCS_unspecified:
1487 case DeclSpec::SCS_typedef:
1488 case DeclSpec::SCS_static:
1489 // FALL THROUGH.
1490 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001491 case DeclSpec::SCS_mutable:
1492 if (isFunc) {
1493 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +00001494 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001495 else
Chris Lattner3b054132008-11-19 05:08:23 +00001496 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +00001497
Sebastian Redl8071edb2008-11-17 23:24:37 +00001498 // FIXME: It would be nicer if the keyword was ignored only for this
1499 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001500 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001501 }
1502 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001503 default:
1504 if (DS.getStorageClassSpecLoc().isValid())
1505 Diag(DS.getStorageClassSpecLoc(),
1506 diag::err_storageclass_invalid_for_member);
1507 else
1508 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1509 D.getMutableDeclSpec().ClearStorageClassSpecs();
1510 }
1511
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001512 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1513 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001514 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001515
1516 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001517 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001518 CXXScopeSpec &SS = D.getCXXScopeSpec();
Douglas Gregorbb64afc2011-10-09 18:55:59 +00001519
1520 // Data members must have identifiers for names.
1521 if (Name.getNameKind() != DeclarationName::Identifier) {
1522 Diag(Loc, diag::err_bad_variable_name)
1523 << Name;
1524 return 0;
1525 }
Douglas Gregora007d362010-10-13 22:19:53 +00001526
Douglas Gregor7c26c042011-09-21 14:40:46 +00001527 IdentifierInfo *II = Name.getAsIdentifierInfo();
1528
1529 // Member field could not be with "template" keyword.
1530 // So TemplateParameterLists should be empty in this case.
1531 if (TemplateParameterLists.size()) {
1532 TemplateParameterList* TemplateParams = TemplateParameterLists.get()[0];
1533 if (TemplateParams->size()) {
1534 // There is no such thing as a member field template.
1535 Diag(D.getIdentifierLoc(), diag::err_template_member)
1536 << II
1537 << SourceRange(TemplateParams->getTemplateLoc(),
1538 TemplateParams->getRAngleLoc());
1539 } else {
1540 // There is an extraneous 'template<>' for this member.
1541 Diag(TemplateParams->getTemplateLoc(),
1542 diag::err_template_member_noparams)
1543 << II
1544 << SourceRange(TemplateParams->getTemplateLoc(),
1545 TemplateParams->getRAngleLoc());
1546 }
1547 return 0;
1548 }
1549
Douglas Gregora007d362010-10-13 22:19:53 +00001550 if (SS.isSet() && !SS.isInvalid()) {
1551 // The user provided a superfluous scope specifier inside a class
1552 // definition:
1553 //
1554 // class X {
1555 // int X::member;
1556 // };
1557 DeclContext *DC = 0;
1558 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1559 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00001560 << Name << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregora007d362010-10-13 22:19:53 +00001561 else
1562 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1563 << Name << SS.getRange();
Douglas Gregorc3ae7c32011-11-01 22:13:30 +00001564
Douglas Gregora007d362010-10-13 22:19:53 +00001565 SS.clear();
1566 }
Douglas Gregor7c26c042011-09-21 14:40:46 +00001567
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001568 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
Richard Smith938f40b2011-06-11 17:19:42 +00001569 HasDeferredInit, AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001570 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001571 } else {
Richard Smith938f40b2011-06-11 17:19:42 +00001572 assert(!HasDeferredInit);
1573
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001574 Member = HandleDeclarator(S, D, move(TemplateParameterLists));
Chris Lattner97e277e2009-03-05 23:03:49 +00001575 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001576 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001577 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001578
1579 // Non-instance-fields can't have a bitfield.
1580 if (BitWidth) {
1581 if (Member->isInvalidDecl()) {
1582 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001583 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001584 // C++ 9.6p3: A bit-field shall not be a static member.
1585 // "static member 'A' cannot be a bit-field"
1586 Diag(Loc, diag::err_static_not_bitfield)
1587 << Name << BitWidth->getSourceRange();
1588 } else if (isa<TypedefDecl>(Member)) {
1589 // "typedef member 'x' cannot be a bit-field"
1590 Diag(Loc, diag::err_typedef_not_bitfield)
1591 << Name << BitWidth->getSourceRange();
1592 } else {
1593 // A function typedef ("typedef int f(); f a;").
1594 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1595 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001596 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001597 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001598 }
Mike Stump11289f42009-09-09 15:08:12 +00001599
Chris Lattnerd26760a2009-03-05 23:01:03 +00001600 BitWidth = 0;
1601 Member->setInvalidDecl();
1602 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001603
1604 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001605
Douglas Gregor3447e762009-08-20 22:52:58 +00001606 // If we have declared a member function template, set the access of the
1607 // templated declaration as well.
1608 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1609 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001610 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001611
Anders Carlsson13a69102011-01-20 04:34:22 +00001612 if (VS.isOverrideSpecified()) {
1613 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1614 if (!MD || !MD->isVirtual()) {
1615 Diag(Member->getLocStart(),
1616 diag::override_keyword_only_allowed_on_virtual_member_functions)
1617 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001618 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001619 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001620 }
1621 if (VS.isFinalSpecified()) {
1622 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1623 if (!MD || !MD->isVirtual()) {
1624 Diag(Member->getLocStart(),
1625 diag::override_keyword_only_allowed_on_virtual_member_functions)
1626 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001627 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001628 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001629 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001630
Douglas Gregorf2f08062011-03-08 17:10:18 +00001631 if (VS.getLastLocation().isValid()) {
1632 // Update the end location of a method that has a virt-specifiers.
1633 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1634 MD->setRangeEnd(VS.getLastLocation());
1635 }
1636
Anders Carlssonc87f8612011-01-20 06:29:02 +00001637 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001638
Douglas Gregor92751d42008-11-17 22:58:34 +00001639 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001640
John McCall25849ca2011-02-15 07:12:36 +00001641 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001642 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001643 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001644}
1645
Richard Smith938f40b2011-06-11 17:19:42 +00001646/// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
Richard Smithe3daab22011-07-20 00:12:52 +00001647/// in-class initializer for a non-static C++ class member, and after
1648/// instantiating an in-class initializer in a class template. Such actions
1649/// are deferred until the class is complete.
Richard Smith938f40b2011-06-11 17:19:42 +00001650void
1651Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1652 Expr *InitExpr) {
1653 FieldDecl *FD = cast<FieldDecl>(D);
1654
1655 if (!InitExpr) {
1656 FD->setInvalidDecl();
1657 FD->removeInClassInitializer();
1658 return;
1659 }
1660
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00001661 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
1662 FD->setInvalidDecl();
1663 FD->removeInClassInitializer();
1664 return;
1665 }
1666
Richard Smith938f40b2011-06-11 17:19:42 +00001667 ExprResult Init = InitExpr;
1668 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1669 // FIXME: if there is no EqualLoc, this is list-initialization.
1670 Init = PerformCopyInitialization(
1671 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1672 if (Init.isInvalid()) {
1673 FD->setInvalidDecl();
1674 return;
1675 }
1676
1677 CheckImplicitConversions(Init.get(), EqualLoc);
1678 }
1679
1680 // C++0x [class.base.init]p7:
1681 // The initialization of each base and member constitutes a
1682 // full-expression.
1683 Init = MaybeCreateExprWithCleanups(Init);
1684 if (Init.isInvalid()) {
1685 FD->setInvalidDecl();
1686 return;
1687 }
1688
1689 InitExpr = Init.release();
1690
1691 FD->setInClassInitializer(InitExpr);
1692}
1693
Douglas Gregor15e77a22009-12-31 09:10:24 +00001694/// \brief Find the direct and/or virtual base specifiers that
1695/// correspond to the given base type, for use in base initialization
1696/// within a constructor.
1697static bool FindBaseInitializer(Sema &SemaRef,
1698 CXXRecordDecl *ClassDecl,
1699 QualType BaseType,
1700 const CXXBaseSpecifier *&DirectBaseSpec,
1701 const CXXBaseSpecifier *&VirtualBaseSpec) {
1702 // First, check for a direct base class.
1703 DirectBaseSpec = 0;
1704 for (CXXRecordDecl::base_class_const_iterator Base
1705 = ClassDecl->bases_begin();
1706 Base != ClassDecl->bases_end(); ++Base) {
1707 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1708 // We found a direct base of this type. That's what we're
1709 // initializing.
1710 DirectBaseSpec = &*Base;
1711 break;
1712 }
1713 }
1714
1715 // Check for a virtual base class.
1716 // FIXME: We might be able to short-circuit this if we know in advance that
1717 // there are no virtual bases.
1718 VirtualBaseSpec = 0;
1719 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1720 // We haven't found a base yet; search the class hierarchy for a
1721 // virtual base class.
1722 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1723 /*DetectVirtual=*/false);
1724 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1725 BaseType, Paths)) {
1726 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1727 Path != Paths.end(); ++Path) {
1728 if (Path->back().Base->isVirtual()) {
1729 VirtualBaseSpec = Path->back().Base;
1730 break;
1731 }
1732 }
1733 }
1734 }
1735
1736 return DirectBaseSpec || VirtualBaseSpec;
1737}
1738
Sebastian Redla74948d2011-09-24 17:48:25 +00001739/// \brief Handle a C++ member initializer using braced-init-list syntax.
1740MemInitResult
1741Sema::ActOnMemInitializer(Decl *ConstructorD,
1742 Scope *S,
1743 CXXScopeSpec &SS,
1744 IdentifierInfo *MemberOrBase,
1745 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001746 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00001747 SourceLocation IdLoc,
1748 Expr *InitList,
1749 SourceLocation EllipsisLoc) {
1750 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001751 DS, IdLoc, MultiInitializer(InitList),
1752 EllipsisLoc);
Sebastian Redla74948d2011-09-24 17:48:25 +00001753}
1754
1755/// \brief Handle a C++ member initializer using parentheses syntax.
John McCallfaf5fb42010-08-26 23:41:50 +00001756MemInitResult
John McCall48871652010-08-21 09:40:31 +00001757Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001758 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001759 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001760 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001761 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001762 const DeclSpec &DS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001763 SourceLocation IdLoc,
1764 SourceLocation LParenLoc,
Richard Trieu2bd04012011-09-09 02:00:50 +00001765 Expr **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001766 SourceLocation RParenLoc,
1767 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00001768 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001769 DS, IdLoc, MultiInitializer(LParenLoc, Args,
1770 NumArgs, RParenLoc),
Sebastian Redla74948d2011-09-24 17:48:25 +00001771 EllipsisLoc);
1772}
1773
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001774namespace {
1775
Kaelyn Uhrain8811b392012-01-11 21:17:51 +00001776// Callback to only accept typo corrections that can be a valid C++ member
1777// intializer: either a non-static field member or a base class.
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001778class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
1779 public:
1780 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
1781 : ClassDecl(ClassDecl) {}
1782
1783 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1784 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
1785 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
1786 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
1787 else
1788 return isa<TypeDecl>(ND);
1789 }
1790 return false;
1791 }
1792
1793 private:
1794 CXXRecordDecl *ClassDecl;
1795};
1796
1797}
1798
Sebastian Redla74948d2011-09-24 17:48:25 +00001799/// \brief Handle a C++ member initializer.
1800MemInitResult
1801Sema::BuildMemInitializer(Decl *ConstructorD,
1802 Scope *S,
1803 CXXScopeSpec &SS,
1804 IdentifierInfo *MemberOrBase,
1805 ParsedType TemplateTypeTy,
David Blaikie186a8892012-01-24 06:03:59 +00001806 const DeclSpec &DS,
Sebastian Redla74948d2011-09-24 17:48:25 +00001807 SourceLocation IdLoc,
1808 const MultiInitializer &Args,
1809 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001810 if (!ConstructorD)
1811 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001812
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001813 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001814
1815 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001816 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001817 if (!Constructor) {
1818 // The user wrote a constructor initializer on a function that is
1819 // not a C++ constructor. Ignore the error for now, because we may
1820 // have more member initializers coming; we'll diagnose it just
1821 // once in ActOnMemInitializers.
1822 return true;
1823 }
1824
1825 CXXRecordDecl *ClassDecl = Constructor->getParent();
1826
1827 // C++ [class.base.init]p2:
1828 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001829 // constructor's class and, if not found in that scope, are looked
1830 // up in the scope containing the constructor's definition.
1831 // [Note: if the constructor's class contains a member with the
1832 // same name as a direct or virtual base class of the class, a
1833 // mem-initializer-id naming the member or base class and composed
1834 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001835 // mem-initializer-id for the hidden base class may be specified
1836 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001837 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001838 // Look for a member, first.
Mike Stump11289f42009-09-09 15:08:12 +00001839 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001840 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001841 if (Result.first != Result.second) {
Peter Collingbourne05156e32011-10-23 18:59:37 +00001842 ValueDecl *Member;
1843 if ((Member = dyn_cast<FieldDecl>(*Result.first)) ||
1844 (Member = dyn_cast<IndirectFieldDecl>(*Result.first))) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00001845 if (EllipsisLoc.isValid())
1846 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
Sebastian Redla74948d2011-09-24 17:48:25 +00001847 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
1848
1849 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001850 }
Francois Pichetd583da02010-12-04 09:14:42 +00001851 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001852 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001853 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001854 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001855 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001856
1857 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001858 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
David Blaikie186a8892012-01-24 06:03:59 +00001859 } else if (DS.getTypeSpecType() == TST_decltype) {
1860 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
John McCallb5a0d312009-12-21 10:41:20 +00001861 } else {
1862 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1863 LookupParsedName(R, S, &SS);
1864
1865 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1866 if (!TyD) {
1867 if (R.isAmbiguous()) return true;
1868
John McCallda6841b2010-04-09 19:01:14 +00001869 // We don't want access-control diagnostics here.
1870 R.suppressDiagnostics();
1871
Douglas Gregora3b624a2010-01-19 06:46:48 +00001872 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1873 bool NotUnknownSpecialization = false;
1874 DeclContext *DC = computeDeclContext(SS, false);
1875 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1876 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1877
1878 if (!NotUnknownSpecialization) {
1879 // When the scope specifier can refer to a member of an unknown
1880 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001881 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1882 SS.getWithLocInContext(Context),
1883 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001884 if (BaseType.isNull())
1885 return true;
1886
Douglas Gregora3b624a2010-01-19 06:46:48 +00001887 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001888 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001889 }
1890 }
1891
Douglas Gregor15e77a22009-12-31 09:10:24 +00001892 // If no results were found, try to correct typos.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001893 TypoCorrection Corr;
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001894 MemInitializerValidatorCCC Validator(ClassDecl);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001895 if (R.empty() && BaseType.isNull() &&
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001896 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001897 Validator, ClassDecl))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001898 std::string CorrectedStr(Corr.getAsString(getLangOptions()));
1899 std::string CorrectedQuotedStr(Corr.getQuoted(getLangOptions()));
1900 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001901 // We have found a non-static data member with a similar
1902 // name to what was typed; complain and initialize that
1903 // member.
1904 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1905 << MemberOrBase << true << CorrectedQuotedStr
1906 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1907 Diag(Member->getLocation(), diag::note_previous_decl)
1908 << CorrectedQuotedStr;
Douglas Gregor15e77a22009-12-31 09:10:24 +00001909
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00001910 return BuildMemberInitializer(Member, Args, IdLoc);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001911 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001912 const CXXBaseSpecifier *DirectBaseSpec;
1913 const CXXBaseSpecifier *VirtualBaseSpec;
1914 if (FindBaseInitializer(*this, ClassDecl,
1915 Context.getTypeDeclType(Type),
1916 DirectBaseSpec, VirtualBaseSpec)) {
1917 // We have found a direct or virtual base class with a
1918 // similar name to what was typed; complain and initialize
1919 // that base class.
1920 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001921 << MemberOrBase << false << CorrectedQuotedStr
1922 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor43a08572010-01-07 00:26:25 +00001923
1924 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1925 : VirtualBaseSpec;
1926 Diag(BaseSpec->getSourceRange().getBegin(),
1927 diag::note_base_class_specified_here)
1928 << BaseSpec->getType()
1929 << BaseSpec->getSourceRange();
1930
Douglas Gregor15e77a22009-12-31 09:10:24 +00001931 TyD = Type;
1932 }
1933 }
1934 }
1935
Douglas Gregora3b624a2010-01-19 06:46:48 +00001936 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001937 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
Sebastian Redla74948d2011-09-24 17:48:25 +00001938 << MemberOrBase << SourceRange(IdLoc, Args.getEndLoc());
Douglas Gregor15e77a22009-12-31 09:10:24 +00001939 return true;
1940 }
John McCallb5a0d312009-12-21 10:41:20 +00001941 }
1942
Douglas Gregora3b624a2010-01-19 06:46:48 +00001943 if (BaseType.isNull()) {
1944 BaseType = Context.getTypeDeclType(TyD);
1945 if (SS.isSet()) {
1946 NestedNameSpecifier *Qualifier =
1947 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001948
Douglas Gregora3b624a2010-01-19 06:46:48 +00001949 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001950 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001951 }
John McCallb5a0d312009-12-21 10:41:20 +00001952 }
1953 }
Mike Stump11289f42009-09-09 15:08:12 +00001954
John McCallbcd03502009-12-07 02:54:59 +00001955 if (!TInfo)
1956 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001957
Sebastian Redla74948d2011-09-24 17:48:25 +00001958 return BuildBaseInitializer(BaseType, TInfo, Args, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001959}
1960
Chandler Carruth599deef2011-09-03 01:14:15 +00001961/// Checks a member initializer expression for cases where reference (or
1962/// pointer) members are bound to by-value parameters (or their addresses).
Chandler Carruth599deef2011-09-03 01:14:15 +00001963static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
1964 Expr *Init,
1965 SourceLocation IdLoc) {
1966 QualType MemberTy = Member->getType();
1967
1968 // We only handle pointers and references currently.
1969 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
1970 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
1971 return;
1972
1973 const bool IsPointer = MemberTy->isPointerType();
1974 if (IsPointer) {
1975 if (const UnaryOperator *Op
1976 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
1977 // The only case we're worried about with pointers requires taking the
1978 // address.
1979 if (Op->getOpcode() != UO_AddrOf)
1980 return;
1981
1982 Init = Op->getSubExpr();
1983 } else {
1984 // We only handle address-of expression initializers for pointers.
1985 return;
1986 }
1987 }
1988
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001989 if (isa<MaterializeTemporaryExpr>(Init->IgnoreParens())) {
1990 // Taking the address of a temporary will be diagnosed as a hard error.
1991 if (IsPointer)
1992 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00001993
Chandler Carruthd551d4e2011-09-03 02:21:57 +00001994 S.Diag(Init->getExprLoc(), diag::warn_bind_ref_member_to_temporary)
1995 << Member << Init->getSourceRange();
1996 } else if (const DeclRefExpr *DRE
1997 = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
1998 // We only warn when referring to a non-reference parameter declaration.
1999 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
2000 if (!Parameter || Parameter->getType()->isReferenceType())
Chandler Carruth599deef2011-09-03 01:14:15 +00002001 return;
2002
2003 S.Diag(Init->getExprLoc(),
2004 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
2005 : diag::warn_bind_ref_member_to_parameter)
2006 << Member << Parameter << Init->getSourceRange();
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002007 } else {
2008 // Other initializers are fine.
2009 return;
Chandler Carruth599deef2011-09-03 01:14:15 +00002010 }
Chandler Carruthd551d4e2011-09-03 02:21:57 +00002011
2012 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
2013 << (unsigned)IsPointer;
Chandler Carruth599deef2011-09-03 01:14:15 +00002014}
2015
John McCalle22a04a2009-11-04 23:02:40 +00002016/// Checks an initializer expression for use of uninitialized fields, such as
2017/// containing the field that is being initialized. Returns true if there is an
2018/// uninitialized field was used an updates the SourceLocation parameter; false
2019/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002020static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00002021 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002022 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00002023 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
2024
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002025 if (isa<CallExpr>(S)) {
2026 // Do not descend into function calls or constructors, as the use
2027 // of an uninitialized field may be valid. One would have to inspect
2028 // the contents of the function/ctor to determine if it is safe or not.
2029 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
2030 // may be safe, depending on what the function/ctor does.
2031 return false;
2032 }
2033 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
2034 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00002035
2036 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
2037 // The member expression points to a static data member.
2038 assert(VD->isStaticDataMember() &&
2039 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00002040 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00002041 return false;
2042 }
2043
2044 if (isa<EnumConstantDecl>(RhsField)) {
2045 // The member expression points to an enum.
2046 return false;
2047 }
2048
John McCalle22a04a2009-11-04 23:02:40 +00002049 if (RhsField == LhsField) {
2050 // Initializing a field with itself. Throw a warning.
2051 // But wait; there are exceptions!
2052 // Exception #1: The field may not belong to this record.
2053 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002054 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00002055 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
2056 // Even though the field matches, it does not belong to this record.
2057 return false;
2058 }
2059 // None of the exceptions triggered; return true to indicate an
2060 // uninitialized field was used.
2061 *L = ME->getMemberLoc();
2062 return true;
2063 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002064 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00002065 // sizeof/alignof doesn't reference contents, do not warn.
2066 return false;
2067 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
2068 // address-of doesn't reference contents (the pointer may be dereferenced
2069 // in the same expression but it would be rare; and weird).
2070 if (UOE->getOpcode() == UO_AddrOf)
2071 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002072 }
John McCall8322c3a2011-02-13 04:07:26 +00002073 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002074 if (!*it) {
2075 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00002076 continue;
2077 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002078 if (InitExprContainsUninitializedFields(*it, LhsField, L))
2079 return true;
John McCalle22a04a2009-11-04 23:02:40 +00002080 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00002081 return false;
John McCalle22a04a2009-11-04 23:02:40 +00002082}
2083
John McCallfaf5fb42010-08-26 23:41:50 +00002084MemInitResult
Sebastian Redla74948d2011-09-24 17:48:25 +00002085Sema::BuildMemberInitializer(ValueDecl *Member,
2086 const MultiInitializer &Args,
2087 SourceLocation IdLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002088 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
2089 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
2090 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00002091 "Member must be a FieldDecl or IndirectFieldDecl");
2092
Peter Collingbourne9f58d7b2011-10-23 18:59:44 +00002093 if (Args.DiagnoseUnexpandedParameterPack(*this))
2094 return true;
2095
Douglas Gregor266bb5f2010-11-05 22:21:31 +00002096 if (Member->isInvalidDecl())
2097 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00002098
John McCalle22a04a2009-11-04 23:02:40 +00002099 // Diagnose value-uses of fields to initialize themselves, e.g.
2100 // foo(foo)
2101 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00002102 // TODO: implement -Wuninitialized and fold this into that framework.
Sebastian Redla74948d2011-09-24 17:48:25 +00002103 for (MultiInitializer::iterator I = Args.begin(), E = Args.end();
2104 I != E; ++I) {
John McCalle22a04a2009-11-04 23:02:40 +00002105 SourceLocation L;
Sebastian Redla74948d2011-09-24 17:48:25 +00002106 Expr *Arg = *I;
2107 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Arg))
2108 Arg = DIE->getInit();
2109 if (InitExprContainsUninitializedFields(Arg, Member, &L)) {
John McCalle22a04a2009-11-04 23:02:40 +00002110 // FIXME: Return true in the case when other fields are used before being
2111 // uninitialized. For example, let this field be the i'th field. When
2112 // initializing the i'th field, throw a warning if any of the >= i'th
2113 // fields are used, as they are not yet initialized.
2114 // Right now we are only handling the case where the i'th field uses
2115 // itself in its initializer.
2116 Diag(L, diag::warn_field_is_uninit);
2117 }
2118 }
2119
Sebastian Redla74948d2011-09-24 17:48:25 +00002120 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002121
Chandler Carruthd44c3102010-12-06 09:23:57 +00002122 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00002123 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002124 // Can't check initialization for a member of dependent type or when
2125 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002126 Init = Args.CreateInitExpr(Context,Member->getType().getNonReferenceType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002127
John McCall31168b02011-06-15 23:02:42 +00002128 DiscardCleanupsInEvaluationContext();
Chandler Carruthd44c3102010-12-06 09:23:57 +00002129 } else {
2130 // Initialize the member.
2131 InitializedEntity MemberEntity =
2132 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
2133 : InitializedEntity::InitializeMember(IndirectMember, 0);
2134 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002135 InitializationKind::CreateDirect(IdLoc, Args.getStartLoc(),
2136 Args.getEndLoc());
John McCallacf0ee52010-10-08 02:01:28 +00002137
Sebastian Redla74948d2011-09-24 17:48:25 +00002138 ExprResult MemberInit = Args.PerformInit(*this, MemberEntity, Kind);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002139 if (MemberInit.isInvalid())
2140 return true;
2141
Sebastian Redla74948d2011-09-24 17:48:25 +00002142 CheckImplicitConversions(MemberInit.get(), Args.getStartLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002143
2144 // C++0x [class.base.init]p7:
2145 // The initialization of each base and member constitutes a
2146 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002147 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00002148 if (MemberInit.isInvalid())
2149 return true;
2150
2151 // If we are in a dependent context, template instantiation will
2152 // perform this type-checking again. Just save the arguments that we
2153 // received in a ParenListExpr.
2154 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2155 // of the information that we have about the member
2156 // initializer. However, deconstructing the ASTs is a dicey process,
2157 // and this approach is far more likely to get the corner cases right.
Chandler Carruth599deef2011-09-03 01:14:15 +00002158 if (CurContext->isDependentContext()) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002159 Init = Args.CreateInitExpr(Context,
2160 Member->getType().getNonReferenceType());
Chandler Carruth599deef2011-09-03 01:14:15 +00002161 } else {
Chandler Carruthd44c3102010-12-06 09:23:57 +00002162 Init = MemberInit.get();
Chandler Carruth599deef2011-09-03 01:14:15 +00002163 CheckForDanglingReferenceOrPointer(*this, Member, Init, IdLoc);
2164 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002165 }
2166
Chandler Carruthd44c3102010-12-06 09:23:57 +00002167 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002168 return new (Context) CXXCtorInitializer(Context, DirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002169 IdLoc, Args.getStartLoc(),
2170 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002171 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00002172 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Sebastian Redla74948d2011-09-24 17:48:25 +00002173 IdLoc, Args.getStartLoc(),
2174 Init, Args.getEndLoc());
Chandler Carruthd44c3102010-12-06 09:23:57 +00002175 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00002176}
2177
John McCallfaf5fb42010-08-26 23:41:50 +00002178MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002179Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002180 const MultiInitializer &Args,
Alexis Huntc5575cc2011-02-26 19:13:13 +00002181 CXXRecordDecl *ClassDecl) {
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002182 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002183 if (!LangOpts.CPlusPlus0x)
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002184 return Diag(NameLoc, diag::err_delegating_ctor)
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002185 << TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002186 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
Sebastian Redl9cb4be22011-03-12 13:53:51 +00002187
Alexis Huntc5575cc2011-02-26 19:13:13 +00002188 // Initialize the object.
2189 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
2190 QualType(ClassDecl->getTypeForDecl(), 0));
2191 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002192 InitializationKind::CreateDirect(NameLoc, Args.getStartLoc(),
2193 Args.getEndLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002194
Sebastian Redla74948d2011-09-24 17:48:25 +00002195 ExprResult DelegationInit = Args.PerformInit(*this, DelegationEntity, Kind);
Alexis Huntc5575cc2011-02-26 19:13:13 +00002196 if (DelegationInit.isInvalid())
2197 return true;
2198
Matt Beaumont-Gay3e59fac2011-11-01 18:10:22 +00002199 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
2200 "Delegating constructor with no target?");
Alexis Huntc5575cc2011-02-26 19:13:13 +00002201
Sebastian Redla74948d2011-09-24 17:48:25 +00002202 CheckImplicitConversions(DelegationInit.get(), Args.getStartLoc());
Alexis Huntc5575cc2011-02-26 19:13:13 +00002203
2204 // C++0x [class.base.init]p7:
2205 // The initialization of each base and member constitutes a
2206 // full-expression.
2207 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
2208 if (DelegationInit.isInvalid())
2209 return true;
2210
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002211 return new (Context) CXXCtorInitializer(Context, TInfo, Args.getStartLoc(),
Alexis Huntc5575cc2011-02-26 19:13:13 +00002212 DelegationInit.takeAs<Expr>(),
Sebastian Redla74948d2011-09-24 17:48:25 +00002213 Args.getEndLoc());
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002214}
2215
2216MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00002217Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002218 const MultiInitializer &Args,
Douglas Gregor44e7df62011-01-04 00:32:56 +00002219 CXXRecordDecl *ClassDecl,
2220 SourceLocation EllipsisLoc) {
Sebastian Redla74948d2011-09-24 17:48:25 +00002221 bool HasDependentArg = Args.isTypeDependent();
Eli Friedman8e1433b2009-07-29 19:44:27 +00002222
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002223 SourceLocation BaseLoc
2224 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Sebastian Redla74948d2011-09-24 17:48:25 +00002225
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002226 if (!BaseType->isDependentType() && !BaseType->isRecordType())
2227 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
2228 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
2229
2230 // C++ [class.base.init]p2:
2231 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00002232 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002233 // of that class, the mem-initializer is ill-formed. A
2234 // mem-initializer-list can initialize a base class using any
2235 // name that denotes that base class type.
2236 bool Dependent = BaseType->isDependentType() || HasDependentArg;
2237
Douglas Gregor44e7df62011-01-04 00:32:56 +00002238 if (EllipsisLoc.isValid()) {
2239 // This is a pack expansion.
2240 if (!BaseType->containsUnexpandedParameterPack()) {
2241 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
Sebastian Redla74948d2011-09-24 17:48:25 +00002242 << SourceRange(BaseLoc, Args.getEndLoc());
2243
Douglas Gregor44e7df62011-01-04 00:32:56 +00002244 EllipsisLoc = SourceLocation();
2245 }
2246 } else {
2247 // Check for any unexpanded parameter packs.
2248 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
2249 return true;
Sebastian Redla74948d2011-09-24 17:48:25 +00002250
2251 if (Args.DiagnoseUnexpandedParameterPack(*this))
2252 return true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00002253 }
Sebastian Redla74948d2011-09-24 17:48:25 +00002254
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002255 // Check for direct and virtual base classes.
2256 const CXXBaseSpecifier *DirectBaseSpec = 0;
2257 const CXXBaseSpecifier *VirtualBaseSpec = 0;
2258 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002259 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
2260 BaseType))
Douglas Gregord73f3dd2011-11-01 01:16:03 +00002261 return BuildDelegatingInitializer(BaseTInfo, Args, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00002262
Douglas Gregor1c69bf02010-06-16 16:03:14 +00002263 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
2264 VirtualBaseSpec);
2265
2266 // C++ [base.class.init]p2:
2267 // Unless the mem-initializer-id names a nonstatic data member of the
2268 // constructor's class or a direct or virtual base of that class, the
2269 // mem-initializer is ill-formed.
2270 if (!DirectBaseSpec && !VirtualBaseSpec) {
2271 // If the class has any dependent bases, then it's possible that
2272 // one of those types will resolve to the same type as
2273 // BaseType. Therefore, just treat this as a dependent base
2274 // class initialization. FIXME: Should we try to check the
2275 // initialization anyway? It seems odd.
2276 if (ClassDecl->hasAnyDependentBases())
2277 Dependent = true;
2278 else
2279 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
2280 << BaseType << Context.getTypeDeclType(ClassDecl)
2281 << BaseTInfo->getTypeLoc().getLocalSourceRange();
2282 }
2283 }
2284
2285 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002286 // Can't check initialization for a base of dependent type or when
2287 // any of the arguments are type-dependent expressions.
Sebastian Redla74948d2011-09-24 17:48:25 +00002288 Expr *BaseInit = Args.CreateInitExpr(Context, BaseType);
Eli Friedman8e1433b2009-07-29 19:44:27 +00002289
John McCall31168b02011-06-15 23:02:42 +00002290 DiscardCleanupsInEvaluationContext();
Mike Stump11289f42009-09-09 15:08:12 +00002291
Sebastian Redla74948d2011-09-24 17:48:25 +00002292 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
2293 /*IsVirtual=*/false,
2294 Args.getStartLoc(), BaseInit,
2295 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002296 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002297
2298 // C++ [base.class.init]p2:
2299 // If a mem-initializer-id is ambiguous because it designates both
2300 // a direct non-virtual base class and an inherited virtual base
2301 // class, the mem-initializer is ill-formed.
2302 if (DirectBaseSpec && VirtualBaseSpec)
2303 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002304 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002305
2306 CXXBaseSpecifier *BaseSpec
2307 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
2308 if (!BaseSpec)
2309 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
2310
2311 // Initialize the base.
2312 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00002313 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002314 InitializationKind Kind =
Sebastian Redla74948d2011-09-24 17:48:25 +00002315 InitializationKind::CreateDirect(BaseLoc, Args.getStartLoc(),
2316 Args.getEndLoc());
2317
2318 ExprResult BaseInit = Args.PerformInit(*this, BaseEntity, Kind);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002319 if (BaseInit.isInvalid())
2320 return true;
John McCallacf0ee52010-10-08 02:01:28 +00002321
Sebastian Redla74948d2011-09-24 17:48:25 +00002322 CheckImplicitConversions(BaseInit.get(), Args.getStartLoc());
2323
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002324 // C++0x [class.base.init]p7:
2325 // The initialization of each base and member constitutes a
2326 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00002327 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002328 if (BaseInit.isInvalid())
2329 return true;
2330
2331 // If we are in a dependent context, template instantiation will
2332 // perform this type-checking again. Just save the arguments that we
2333 // received in a ParenListExpr.
2334 // FIXME: This isn't quite ideal, since our ASTs don't capture all
2335 // of the information that we have about the base
2336 // initializer. However, deconstructing the ASTs is a dicey process,
2337 // and this approach is far more likely to get the corner cases right.
Sebastian Redla74948d2011-09-24 17:48:25 +00002338 if (CurContext->isDependentContext())
2339 BaseInit = Owned(Args.CreateInitExpr(Context, BaseType));
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002340
Alexis Hunt1d792652011-01-08 20:30:50 +00002341 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Sebastian Redla74948d2011-09-24 17:48:25 +00002342 BaseSpec->isVirtual(),
2343 Args.getStartLoc(),
2344 BaseInit.takeAs<Expr>(),
2345 Args.getEndLoc(), EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00002346}
2347
Sebastian Redl22653ba2011-08-30 19:58:05 +00002348// Create a static_cast\<T&&>(expr).
2349static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
2350 QualType ExprType = E->getType();
2351 QualType TargetType = SemaRef.Context.getRValueReferenceType(ExprType);
2352 SourceLocation ExprLoc = E->getLocStart();
2353 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
2354 TargetType, ExprLoc);
2355
2356 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
2357 SourceRange(ExprLoc, ExprLoc),
2358 E->getSourceRange()).take();
2359}
2360
Anders Carlsson1b00e242010-04-23 03:10:23 +00002361/// ImplicitInitializerKind - How an implicit base or member initializer should
2362/// initialize its base or member.
2363enum ImplicitInitializerKind {
2364 IIK_Default,
2365 IIK_Copy,
2366 IIK_Move
2367};
2368
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002369static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00002370BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002371 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00002372 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002373 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00002374 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002375 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00002376 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
2377 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002378
John McCalldadc5752010-08-24 06:29:42 +00002379 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002380
2381 switch (ImplicitInitKind) {
2382 case IIK_Default: {
2383 InitializationKind InitKind
2384 = InitializationKind::CreateDefault(Constructor->getLocation());
2385 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2386 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002387 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002388 break;
2389 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002390
Sebastian Redl22653ba2011-08-30 19:58:05 +00002391 case IIK_Move:
Anders Carlsson1b00e242010-04-23 03:10:23 +00002392 case IIK_Copy: {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002393 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson1b00e242010-04-23 03:10:23 +00002394 ParmVarDecl *Param = Constructor->getParamDecl(0);
2395 QualType ParamType = Param->getType().getNonReferenceType();
Eli Friedman2dfa7932012-01-16 21:00:51 +00002396
Anders Carlsson1b00e242010-04-23 03:10:23 +00002397 Expr *CopyCtorArg =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002398 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2399 SourceLocation(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002400 Constructor->getLocation(), ParamType,
2401 VK_LValue, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002402
Eli Friedmanfa0df832012-02-02 03:46:19 +00002403 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
2404
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002405 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00002406 QualType ArgTy =
2407 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
2408 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00002409
Sebastian Redl22653ba2011-08-30 19:58:05 +00002410 if (Moving) {
2411 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
2412 }
2413
John McCallcf142162010-08-07 06:22:56 +00002414 CXXCastPath BasePath;
2415 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00002416 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
2417 CK_UncheckedDerivedToBase,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002418 Moving ? VK_XValue : VK_LValue,
Sebastian Redl22653ba2011-08-30 19:58:05 +00002419 &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00002420
Anders Carlsson1b00e242010-04-23 03:10:23 +00002421 InitializationKind InitKind
2422 = InitializationKind::CreateDirect(Constructor->getLocation(),
2423 SourceLocation(), SourceLocation());
2424 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
2425 &CopyCtorArg, 1);
2426 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00002427 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00002428 break;
2429 }
Anders Carlsson1b00e242010-04-23 03:10:23 +00002430 }
John McCallb268a282010-08-23 23:25:46 +00002431
Douglas Gregora40433a2010-12-07 00:41:46 +00002432 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002433 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002434 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002435
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002436 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00002437 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002438 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
2439 SourceLocation()),
2440 BaseSpec->isVirtual(),
2441 SourceLocation(),
2442 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00002443 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002444 SourceLocation());
2445
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002446 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002447}
2448
Sebastian Redl22653ba2011-08-30 19:58:05 +00002449static bool RefersToRValueRef(Expr *MemRef) {
2450 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
2451 return Referenced->getType()->isRValueReferenceType();
2452}
2453
Anders Carlsson3c1db572010-04-23 02:15:47 +00002454static bool
2455BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002456 ImplicitInitializerKind ImplicitInitKind,
Douglas Gregor493627b2011-08-10 15:22:55 +00002457 FieldDecl *Field, IndirectFieldDecl *Indirect,
Alexis Hunt1d792652011-01-08 20:30:50 +00002458 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00002459 if (Field->isInvalidDecl())
2460 return true;
2461
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002462 SourceLocation Loc = Constructor->getLocation();
2463
Sebastian Redl22653ba2011-08-30 19:58:05 +00002464 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
2465 bool Moving = ImplicitInitKind == IIK_Move;
Anders Carlsson423f5d82010-04-23 16:04:08 +00002466 ParmVarDecl *Param = Constructor->getParamDecl(0);
2467 QualType ParamType = Param->getType().getNonReferenceType();
John McCall1b1a1db2011-06-17 00:18:42 +00002468
2469 // Suppress copying zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00002470 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
2471 return false;
Douglas Gregor10f939c2011-11-02 23:04:16 +00002472
Anders Carlsson423f5d82010-04-23 16:04:08 +00002473 Expr *MemberExprBase =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002474 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
2475 SourceLocation(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00002476 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002477
Eli Friedmanfa0df832012-02-02 03:46:19 +00002478 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
2479
Sebastian Redl22653ba2011-08-30 19:58:05 +00002480 if (Moving) {
2481 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
2482 }
2483
Douglas Gregor94f9a482010-05-05 05:51:00 +00002484 // Build a reference to this field within the parameter.
2485 CXXScopeSpec SS;
2486 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2487 Sema::LookupMemberName);
Sebastian Redl22653ba2011-08-30 19:58:05 +00002488 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
2489 : cast<ValueDecl>(Field), AS_public);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002490 MemberLookup.resolveKind();
Sebastian Redle9c4e842011-09-04 18:14:28 +00002491 ExprResult CtorArg
John McCallb268a282010-08-23 23:25:46 +00002492 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002493 ParamType, Loc,
2494 /*IsArrow=*/false,
2495 SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002496 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00002497 /*FirstQualifierInScope=*/0,
2498 MemberLookup,
2499 /*TemplateArgs=*/0);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002500 if (CtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00002501 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002502
2503 // C++11 [class.copy]p15:
2504 // - if a member m has rvalue reference type T&&, it is direct-initialized
2505 // with static_cast<T&&>(x.m);
Sebastian Redle9c4e842011-09-04 18:14:28 +00002506 if (RefersToRValueRef(CtorArg.get())) {
2507 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002508 }
2509
Douglas Gregor94f9a482010-05-05 05:51:00 +00002510 // When the field we are copying is an array, create index variables for
2511 // each dimension of the array. We use these index variables to subscript
2512 // the source array, and other clients (e.g., CodeGen) will perform the
2513 // necessary iteration with these index variables.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002514 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002515 QualType BaseType = Field->getType();
2516 QualType SizeType = SemaRef.Context.getSizeType();
Sebastian Redl22653ba2011-08-30 19:58:05 +00002517 bool InitializingArray = false;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002518 while (const ConstantArrayType *Array
2519 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002520 InitializingArray = true;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002521 // Create the iteration variable for this array index.
2522 IdentifierInfo *IterationVarName = 0;
2523 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002524 SmallString<8> Str;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002525 llvm::raw_svector_ostream OS(Str);
2526 OS << "__i" << IndexVariables.size();
2527 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2528 }
2529 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00002530 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00002531 IterationVarName, SizeType,
2532 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00002533 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002534 IndexVariables.push_back(IterationVar);
2535
2536 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00002537 ExprResult IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00002538 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002539 assert(!IterationVarRef.isInvalid() &&
2540 "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00002541 IterationVarRef = SemaRef.DefaultLvalueConversion(IterationVarRef.take());
2542 assert(!IterationVarRef.isInvalid() &&
2543 "Conversion of invented variable cannot fail!");
Sebastian Redle9c4e842011-09-04 18:14:28 +00002544
Douglas Gregor94f9a482010-05-05 05:51:00 +00002545 // Subscript the array with this iteration variable.
Sebastian Redle9c4e842011-09-04 18:14:28 +00002546 CtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CtorArg.take(), Loc,
John McCallb268a282010-08-23 23:25:46 +00002547 IterationVarRef.take(),
Sebastian Redle9c4e842011-09-04 18:14:28 +00002548 Loc);
2549 if (CtorArg.isInvalid())
Douglas Gregor94f9a482010-05-05 05:51:00 +00002550 return true;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002551
Douglas Gregor94f9a482010-05-05 05:51:00 +00002552 BaseType = Array->getElementType();
2553 }
Sebastian Redl22653ba2011-08-30 19:58:05 +00002554
2555 // The array subscript expression is an lvalue, which is wrong for moving.
2556 if (Moving && InitializingArray)
Sebastian Redle9c4e842011-09-04 18:14:28 +00002557 CtorArg = CastForMoving(SemaRef, CtorArg.take());
Sebastian Redl22653ba2011-08-30 19:58:05 +00002558
Douglas Gregor94f9a482010-05-05 05:51:00 +00002559 // Construct the entity that we will be initializing. For an array, this
2560 // will be first element in the array, which may require several levels
2561 // of array-subscript entities.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002562 SmallVector<InitializedEntity, 4> Entities;
Douglas Gregor94f9a482010-05-05 05:51:00 +00002563 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor493627b2011-08-10 15:22:55 +00002564 if (Indirect)
2565 Entities.push_back(InitializedEntity::InitializeMember(Indirect));
2566 else
2567 Entities.push_back(InitializedEntity::InitializeMember(Field));
Douglas Gregor94f9a482010-05-05 05:51:00 +00002568 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2569 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2570 0,
2571 Entities.back()));
2572
2573 // Direct-initialize to use the copy constructor.
2574 InitializationKind InitKind =
2575 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2576
Sebastian Redle9c4e842011-09-04 18:14:28 +00002577 Expr *CtorArgE = CtorArg.takeAs<Expr>();
Douglas Gregor94f9a482010-05-05 05:51:00 +00002578 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002579 &CtorArgE, 1);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002580
John McCalldadc5752010-08-24 06:29:42 +00002581 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00002582 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
Sebastian Redle9c4e842011-09-04 18:14:28 +00002583 MultiExprArg(&CtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00002584 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00002585 if (MemberInit.isInvalid())
2586 return true;
2587
Douglas Gregor493627b2011-08-10 15:22:55 +00002588 if (Indirect) {
2589 assert(IndexVariables.size() == 0 &&
2590 "Indirect field improperly initialized");
2591 CXXMemberInit
2592 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2593 Loc, Loc,
2594 MemberInit.takeAs<Expr>(),
2595 Loc);
2596 } else
2597 CXXMemberInit = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc,
2598 Loc, MemberInit.takeAs<Expr>(),
2599 Loc,
2600 IndexVariables.data(),
2601 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00002602 return false;
2603 }
2604
Anders Carlsson423f5d82010-04-23 16:04:08 +00002605 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2606
Anders Carlsson3c1db572010-04-23 02:15:47 +00002607 QualType FieldBaseElementType =
2608 SemaRef.Context.getBaseElementType(Field->getType());
2609
Anders Carlsson3c1db572010-04-23 02:15:47 +00002610 if (FieldBaseElementType->isRecordType()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002611 InitializedEntity InitEntity
2612 = Indirect? InitializedEntity::InitializeMember(Indirect)
2613 : InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00002614 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00002615 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002616
2617 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00002618 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00002619 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00002620
Douglas Gregora40433a2010-12-07 00:41:46 +00002621 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002622 if (MemberInit.isInvalid())
2623 return true;
2624
Douglas Gregor493627b2011-08-10 15:22:55 +00002625 if (Indirect)
2626 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2627 Indirect, Loc,
2628 Loc,
2629 MemberInit.get(),
2630 Loc);
2631 else
2632 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2633 Field, Loc, Loc,
2634 MemberInit.get(),
2635 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00002636 return false;
2637 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002638
Alexis Hunt8b455182011-05-17 00:19:05 +00002639 if (!Field->getParent()->isUnion()) {
2640 if (FieldBaseElementType->isReferenceType()) {
2641 SemaRef.Diag(Constructor->getLocation(),
2642 diag::err_uninitialized_member_in_ctor)
2643 << (int)Constructor->isImplicit()
2644 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2645 << 0 << Field->getDeclName();
2646 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2647 return true;
2648 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002649
Alexis Hunt8b455182011-05-17 00:19:05 +00002650 if (FieldBaseElementType.isConstQualified()) {
2651 SemaRef.Diag(Constructor->getLocation(),
2652 diag::err_uninitialized_member_in_ctor)
2653 << (int)Constructor->isImplicit()
2654 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2655 << 1 << Field->getDeclName();
2656 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2657 return true;
2658 }
Anders Carlssondca6be02010-04-23 03:07:47 +00002659 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00002660
John McCall31168b02011-06-15 23:02:42 +00002661 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
2662 FieldBaseElementType->isObjCRetainableType() &&
2663 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_None &&
2664 FieldBaseElementType.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
2665 // Instant objects:
2666 // Default-initialize Objective-C pointers to NULL.
2667 CXXMemberInit
2668 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2669 Loc, Loc,
2670 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
2671 Loc);
2672 return false;
2673 }
2674
Anders Carlsson3c1db572010-04-23 02:15:47 +00002675 // Nothing to initialize.
2676 CXXMemberInit = 0;
2677 return false;
2678}
John McCallbc83b3f2010-05-20 23:23:51 +00002679
2680namespace {
2681struct BaseAndFieldInfo {
2682 Sema &S;
2683 CXXConstructorDecl *Ctor;
2684 bool AnyErrorsInInits;
2685 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00002686 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002687 SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002688
2689 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2690 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00002691 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
2692 if (Generated && Ctor->isCopyConstructor())
John McCallbc83b3f2010-05-20 23:23:51 +00002693 IIK = IIK_Copy;
Sebastian Redl22653ba2011-08-30 19:58:05 +00002694 else if (Generated && Ctor->isMoveConstructor())
2695 IIK = IIK_Move;
John McCallbc83b3f2010-05-20 23:23:51 +00002696 else
2697 IIK = IIK_Default;
2698 }
Douglas Gregor7db3e952011-11-28 20:03:15 +00002699
2700 bool isImplicitCopyOrMove() const {
2701 switch (IIK) {
2702 case IIK_Copy:
2703 case IIK_Move:
2704 return true;
2705
2706 case IIK_Default:
2707 return false;
2708 }
David Blaikiee4d798f2012-01-20 21:50:17 +00002709
2710 llvm_unreachable("Invalid ImplicitInitializerKind!");
Douglas Gregor7db3e952011-11-28 20:03:15 +00002711 }
John McCallbc83b3f2010-05-20 23:23:51 +00002712};
2713}
2714
Richard Smithc94ec842011-09-19 13:34:43 +00002715/// \brief Determine whether the given indirect field declaration is somewhere
2716/// within an anonymous union.
2717static bool isWithinAnonymousUnion(IndirectFieldDecl *F) {
2718 for (IndirectFieldDecl::chain_iterator C = F->chain_begin(),
2719 CEnd = F->chain_end();
2720 C != CEnd; ++C)
2721 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>((*C)->getDeclContext()))
2722 if (Record->isUnion())
2723 return true;
2724
2725 return false;
2726}
2727
Douglas Gregor10f939c2011-11-02 23:04:16 +00002728/// \brief Determine whether the given type is an incomplete or zero-lenfgth
2729/// array type.
2730static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
2731 if (T->isIncompleteArrayType())
2732 return true;
2733
2734 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
2735 if (!ArrayT->getSize())
2736 return true;
2737
2738 T = ArrayT->getElementType();
2739 }
2740
2741 return false;
2742}
2743
Richard Smith938f40b2011-06-11 17:19:42 +00002744static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
Douglas Gregor493627b2011-08-10 15:22:55 +00002745 FieldDecl *Field,
2746 IndirectFieldDecl *Indirect = 0) {
John McCallbc83b3f2010-05-20 23:23:51 +00002747
Chandler Carruth139e9622010-06-30 02:59:29 +00002748 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00002749 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002750 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002751 return false;
2752 }
2753
Richard Smith938f40b2011-06-11 17:19:42 +00002754 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2755 // has a brace-or-equal-initializer, the entity is initialized as specified
2756 // in [dcl.init].
Douglas Gregor7db3e952011-11-28 20:03:15 +00002757 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
Douglas Gregor493627b2011-08-10 15:22:55 +00002758 CXXCtorInitializer *Init;
2759 if (Indirect)
2760 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Indirect,
2761 SourceLocation(),
2762 SourceLocation(), 0,
2763 SourceLocation());
2764 else
2765 Init = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2766 SourceLocation(),
2767 SourceLocation(), 0,
2768 SourceLocation());
2769 Info.AllToInit.push_back(Init);
Richard Smith938f40b2011-06-11 17:19:42 +00002770 return false;
2771 }
2772
Richard Smith12d5ed82011-09-18 11:14:50 +00002773 // Don't build an implicit initializer for union members if none was
2774 // explicitly specified.
Richard Smithc94ec842011-09-19 13:34:43 +00002775 if (Field->getParent()->isUnion() ||
2776 (Indirect && isWithinAnonymousUnion(Indirect)))
Richard Smith12d5ed82011-09-18 11:14:50 +00002777 return false;
2778
Douglas Gregor10f939c2011-11-02 23:04:16 +00002779 // Don't initialize incomplete or zero-length arrays.
2780 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
2781 return false;
2782
John McCallbc83b3f2010-05-20 23:23:51 +00002783 // Don't try to build an implicit initializer if there were semantic
2784 // errors in any of the initializers (and therefore we might be
2785 // missing some that the user actually wrote).
Richard Smith938f40b2011-06-11 17:19:42 +00002786 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
John McCallbc83b3f2010-05-20 23:23:51 +00002787 return false;
2788
Alexis Hunt1d792652011-01-08 20:30:50 +00002789 CXXCtorInitializer *Init = 0;
Douglas Gregor493627b2011-08-10 15:22:55 +00002790 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
2791 Indirect, Init))
John McCallbc83b3f2010-05-20 23:23:51 +00002792 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002793
Francois Pichetd583da02010-12-04 09:14:42 +00002794 if (Init)
2795 Info.AllToInit.push_back(Init);
2796
John McCallbc83b3f2010-05-20 23:23:51 +00002797 return false;
2798}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002799
2800bool
2801Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2802 CXXCtorInitializer *Initializer) {
Alexis Hunt6118d662011-05-04 05:57:24 +00002803 assert(Initializer->isDelegatingInitializer());
Alexis Hunt5583d562011-05-03 20:43:02 +00002804 Constructor->setNumCtorInitializers(1);
2805 CXXCtorInitializer **initializer =
2806 new (Context) CXXCtorInitializer*[1];
2807 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2808 Constructor->setCtorInitializers(initializer);
2809
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002810 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002811 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002812 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2813 }
2814
Alexis Hunte2622992011-05-05 00:05:47 +00002815 DelegatingCtorDecls.push_back(Constructor);
Alexis Hunt6118d662011-05-04 05:57:24 +00002816
Alexis Hunt61bc1732011-05-01 07:04:31 +00002817 return false;
2818}
Douglas Gregor493627b2011-08-10 15:22:55 +00002819
John McCall1b1a1db2011-06-17 00:18:42 +00002820bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2821 CXXCtorInitializer **Initializers,
2822 unsigned NumInitializers,
2823 bool AnyErrors) {
Douglas Gregor52235292011-09-22 23:04:35 +00002824 if (Constructor->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002825 // Just store the initializers as written, they will be checked during
2826 // instantiation.
2827 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002828 Constructor->setNumCtorInitializers(NumInitializers);
2829 CXXCtorInitializer **baseOrMemberInitializers =
2830 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002831 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002832 NumInitializers * sizeof(CXXCtorInitializer*));
2833 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002834 }
2835
2836 return false;
2837 }
2838
John McCallbc83b3f2010-05-20 23:23:51 +00002839 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002840
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002841 // We need to build the initializer AST according to order of construction
2842 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002843 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002844 if (!ClassDecl)
2845 return true;
2846
Eli Friedman9cf6b592009-11-09 19:20:36 +00002847 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002848
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002849 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002850 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002851
2852 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002853 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002854 else
Francois Pichetd583da02010-12-04 09:14:42 +00002855 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002856 }
2857
Anders Carlsson43c64af2010-04-21 19:52:01 +00002858 // Keep track of the direct virtual bases.
2859 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2860 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2861 E = ClassDecl->bases_end(); I != E; ++I) {
2862 if (I->isVirtual())
2863 DirectVBases.insert(I);
2864 }
2865
Anders Carlssondb0a9652010-04-02 06:26:44 +00002866 // Push virtual bases before others.
2867 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2868 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2869
Alexis Hunt1d792652011-01-08 20:30:50 +00002870 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002871 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2872 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002873 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002874 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002875 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002876 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002877 VBase, IsInheritedVirtualBase,
2878 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002879 HadError = true;
2880 continue;
2881 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002882
John McCallbc83b3f2010-05-20 23:23:51 +00002883 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002884 }
2885 }
Mike Stump11289f42009-09-09 15:08:12 +00002886
John McCallbc83b3f2010-05-20 23:23:51 +00002887 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002888 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2889 E = ClassDecl->bases_end(); Base != E; ++Base) {
2890 // Virtuals are in the virtual base list and already constructed.
2891 if (Base->isVirtual())
2892 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002893
Alexis Hunt1d792652011-01-08 20:30:50 +00002894 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002895 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2896 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002897 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002898 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002899 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002900 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002901 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002902 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002903 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002904 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002905
John McCallbc83b3f2010-05-20 23:23:51 +00002906 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002907 }
2908 }
Mike Stump11289f42009-09-09 15:08:12 +00002909
John McCallbc83b3f2010-05-20 23:23:51 +00002910 // Fields.
Douglas Gregor493627b2011-08-10 15:22:55 +00002911 for (DeclContext::decl_iterator Mem = ClassDecl->decls_begin(),
2912 MemEnd = ClassDecl->decls_end();
2913 Mem != MemEnd; ++Mem) {
2914 if (FieldDecl *F = dyn_cast<FieldDecl>(*Mem)) {
Douglas Gregor556e5862011-10-10 17:22:13 +00002915 // C++ [class.bit]p2:
2916 // A declaration for a bit-field that omits the identifier declares an
2917 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
2918 // initialized.
2919 if (F->isUnnamedBitfield())
2920 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00002921
Sebastian Redl22653ba2011-08-30 19:58:05 +00002922 // If we're not generating the implicit copy/move constructor, then we'll
Douglas Gregor493627b2011-08-10 15:22:55 +00002923 // handle anonymous struct/union fields based on their individual
2924 // indirect fields.
2925 if (F->isAnonymousStructOrUnion() && Info.IIK == IIK_Default)
2926 continue;
2927
2928 if (CollectFieldInitializer(*this, Info, F))
2929 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002930 continue;
2931 }
Douglas Gregor493627b2011-08-10 15:22:55 +00002932
2933 // Beyond this point, we only consider default initialization.
2934 if (Info.IIK != IIK_Default)
2935 continue;
2936
2937 if (IndirectFieldDecl *F = dyn_cast<IndirectFieldDecl>(*Mem)) {
2938 if (F->getType()->isIncompleteArrayType()) {
2939 assert(ClassDecl->hasFlexibleArrayMember() &&
2940 "Incomplete array type is not valid");
2941 continue;
2942 }
2943
Douglas Gregor493627b2011-08-10 15:22:55 +00002944 // Initialize each field of an anonymous struct individually.
2945 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
2946 HadError = true;
2947
2948 continue;
2949 }
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002950 }
Mike Stump11289f42009-09-09 15:08:12 +00002951
John McCallbc83b3f2010-05-20 23:23:51 +00002952 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002953 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002954 Constructor->setNumCtorInitializers(NumInitializers);
2955 CXXCtorInitializer **baseOrMemberInitializers =
2956 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002957 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002958 NumInitializers * sizeof(CXXCtorInitializer*));
2959 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002960
John McCalla6309952010-03-16 21:39:52 +00002961 // Constructors implicitly reference the base and member
2962 // destructors.
2963 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2964 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002965 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002966
2967 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002968}
2969
Eli Friedman952c15d2009-07-21 19:28:10 +00002970static void *GetKeyForTopLevelField(FieldDecl *Field) {
2971 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002972 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002973 if (RT->getDecl()->isAnonymousStructOrUnion())
2974 return static_cast<void *>(RT->getDecl());
2975 }
2976 return static_cast<void *>(Field);
2977}
2978
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002979static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002980 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002981}
2982
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002983static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002984 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002985 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002986 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002987
Eli Friedman952c15d2009-07-21 19:28:10 +00002988 // For fields injected into the class via declaration of an anonymous union,
2989 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002990 FieldDecl *Field = Member->getAnyMember();
2991
John McCall23eebd92010-04-10 09:28:51 +00002992 // If the field is a member of an anonymous struct or union, our key
2993 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002994 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002995 if (RD->isAnonymousStructOrUnion()) {
2996 while (true) {
2997 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2998 if (Parent->isAnonymousStructOrUnion())
2999 RD = Parent;
3000 else
3001 break;
3002 }
3003
Anders Carlsson83ac3122010-03-30 16:19:37 +00003004 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00003005 }
Mike Stump11289f42009-09-09 15:08:12 +00003006
Anders Carlssona942dcd2010-03-30 15:39:27 +00003007 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00003008}
3009
Anders Carlssone857b292010-04-02 03:37:03 +00003010static void
3011DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003012 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00003013 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00003014 unsigned NumInits) {
3015 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00003016 return;
Mike Stump11289f42009-09-09 15:08:12 +00003017
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003018 // Don't check initializers order unless the warning is enabled at the
3019 // location of at least one initializer.
3020 bool ShouldCheckOrder = false;
3021 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003022 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003023 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
3024 Init->getSourceLocation())
David Blaikie9c902b52011-09-25 23:23:43 +00003025 != DiagnosticsEngine::Ignored) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003026 ShouldCheckOrder = true;
3027 break;
3028 }
3029 }
3030 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00003031 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003032
John McCallbb7b6582010-04-10 07:37:23 +00003033 // Build the list of bases and members in the order that they'll
3034 // actually be initialized. The explicit initializers should be in
3035 // this same order but may be missing things.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003036 SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00003037
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003038 const CXXRecordDecl *ClassDecl = Constructor->getParent();
3039
John McCallbb7b6582010-04-10 07:37:23 +00003040 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003041 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00003042 ClassDecl->vbases_begin(),
3043 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00003044 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00003045
John McCallbb7b6582010-04-10 07:37:23 +00003046 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00003047 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00003048 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00003049 if (Base->isVirtual())
3050 continue;
John McCallbb7b6582010-04-10 07:37:23 +00003051 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00003052 }
Mike Stump11289f42009-09-09 15:08:12 +00003053
John McCallbb7b6582010-04-10 07:37:23 +00003054 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00003055 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Douglas Gregor556e5862011-10-10 17:22:13 +00003056 E = ClassDecl->field_end(); Field != E; ++Field) {
3057 if (Field->isUnnamedBitfield())
3058 continue;
3059
John McCallbb7b6582010-04-10 07:37:23 +00003060 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Douglas Gregor556e5862011-10-10 17:22:13 +00003061 }
3062
John McCallbb7b6582010-04-10 07:37:23 +00003063 unsigned NumIdealInits = IdealInitKeys.size();
3064 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00003065
Alexis Hunt1d792652011-01-08 20:30:50 +00003066 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00003067 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003068 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00003069 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00003070
3071 // Scan forward to try to find this initializer in the idealized
3072 // initializers list.
3073 for (; IdealIndex != NumIdealInits; ++IdealIndex)
3074 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003075 break;
John McCallbb7b6582010-04-10 07:37:23 +00003076
3077 // If we didn't find this initializer, it must be because we
3078 // scanned past it on a previous iteration. That can only
3079 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00003080 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00003081 Sema::SemaDiagnosticBuilder D =
3082 SemaRef.Diag(PrevInit->getSourceLocation(),
3083 diag::warn_initializer_out_of_order);
3084
Francois Pichetd583da02010-12-04 09:14:42 +00003085 if (PrevInit->isAnyMemberInitializer())
3086 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003087 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003088 D << 1 << PrevInit->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003089
Francois Pichetd583da02010-12-04 09:14:42 +00003090 if (Init->isAnyMemberInitializer())
3091 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00003092 else
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003093 D << 1 << Init->getTypeSourceInfo()->getType();
John McCallbb7b6582010-04-10 07:37:23 +00003094
3095 // Move back to the initializer's location in the ideal list.
3096 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
3097 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00003098 break;
John McCallbb7b6582010-04-10 07:37:23 +00003099
3100 assert(IdealIndex != NumIdealInits &&
3101 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003102 }
John McCallbb7b6582010-04-10 07:37:23 +00003103
3104 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00003105 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00003106}
3107
John McCall23eebd92010-04-10 09:28:51 +00003108namespace {
3109bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003110 CXXCtorInitializer *Init,
3111 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00003112 if (!PrevInit) {
3113 PrevInit = Init;
3114 return false;
3115 }
3116
3117 if (FieldDecl *Field = Init->getMember())
3118 S.Diag(Init->getSourceLocation(),
3119 diag::err_multiple_mem_initialization)
3120 << Field->getDeclName()
3121 << Init->getSourceRange();
3122 else {
John McCall424cec92011-01-19 06:33:43 +00003123 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00003124 assert(BaseClass && "neither field nor base");
3125 S.Diag(Init->getSourceLocation(),
3126 diag::err_multiple_base_initialization)
3127 << QualType(BaseClass, 0)
3128 << Init->getSourceRange();
3129 }
3130 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
3131 << 0 << PrevInit->getSourceRange();
3132
3133 return true;
3134}
3135
Alexis Hunt1d792652011-01-08 20:30:50 +00003136typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00003137typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
3138
3139bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00003140 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00003141 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00003142 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003143 RecordDecl *Parent = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00003144 NamedDecl *Child = Field;
David Blaikie0f65d592011-11-17 06:01:57 +00003145
3146 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
John McCall23eebd92010-04-10 09:28:51 +00003147 if (Parent->isUnion()) {
3148 UnionEntry &En = Unions[Parent];
3149 if (En.first && En.first != Child) {
3150 S.Diag(Init->getSourceLocation(),
3151 diag::err_multiple_mem_union_initialization)
3152 << Field->getDeclName()
3153 << Init->getSourceRange();
3154 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
3155 << 0 << En.second->getSourceRange();
3156 return true;
David Blaikie256ee192011-11-12 20:54:14 +00003157 }
3158 if (!En.first) {
John McCall23eebd92010-04-10 09:28:51 +00003159 En.first = Child;
3160 En.second = Init;
3161 }
David Blaikie0f65d592011-11-17 06:01:57 +00003162 if (!Parent->isAnonymousStructOrUnion())
3163 return false;
John McCall23eebd92010-04-10 09:28:51 +00003164 }
3165
3166 Child = Parent;
3167 Parent = cast<RecordDecl>(Parent->getDeclContext());
David Blaikie0f65d592011-11-17 06:01:57 +00003168 }
John McCall23eebd92010-04-10 09:28:51 +00003169
3170 return false;
3171}
3172}
3173
Anders Carlssone857b292010-04-02 03:37:03 +00003174/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00003175void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00003176 SourceLocation ColonLoc,
Richard Trieu9becef62011-09-09 03:18:59 +00003177 CXXCtorInitializer **meminits,
3178 unsigned NumMemInits,
Anders Carlssone857b292010-04-02 03:37:03 +00003179 bool AnyErrors) {
3180 if (!ConstructorDecl)
3181 return;
3182
3183 AdjustDeclIfTemplate(ConstructorDecl);
3184
3185 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003186 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00003187
3188 if (!Constructor) {
3189 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
3190 return;
3191 }
3192
Alexis Hunt1d792652011-01-08 20:30:50 +00003193 CXXCtorInitializer **MemInits =
3194 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00003195
3196 // Mapping for the duplicate initializers check.
3197 // For member initializers, this is keyed with a FieldDecl*.
3198 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00003199 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00003200
3201 // Mapping for the inconsistent anonymous-union initializers check.
3202 RedundantUnionMap MemberUnions;
3203
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003204 bool HadError = false;
3205 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003206 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00003207
Abramo Bagnara341d7832010-05-26 18:09:23 +00003208 // Set the source order index.
3209 Init->setSourceOrder(i);
3210
Francois Pichetd583da02010-12-04 09:14:42 +00003211 if (Init->isAnyMemberInitializer()) {
3212 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00003213 if (CheckRedundantInit(*this, Init, Members[Field]) ||
3214 CheckRedundantUnionInit(*this, Init, MemberUnions))
3215 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003216 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00003217 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
3218 if (CheckRedundantInit(*this, Init, Members[Key]))
3219 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00003220 } else {
3221 assert(Init->isDelegatingInitializer());
3222 // This must be the only initializer
3223 if (i != 0 || NumMemInits > 1) {
3224 Diag(MemInits[0]->getSourceLocation(),
3225 diag::err_delegating_initializer_alone)
3226 << MemInits[0]->getSourceRange();
3227 HadError = true;
Alexis Hunt61bc1732011-05-01 07:04:31 +00003228 // We will treat this as being the only initializer.
Alexis Huntc5575cc2011-02-26 19:13:13 +00003229 }
Alexis Hunt6118d662011-05-04 05:57:24 +00003230 SetDelegatingInitializer(Constructor, MemInits[i]);
Alexis Hunt61bc1732011-05-01 07:04:31 +00003231 // Return immediately as the initializer is set.
3232 return;
Anders Carlssone857b292010-04-02 03:37:03 +00003233 }
Anders Carlssone857b292010-04-02 03:37:03 +00003234 }
3235
Anders Carlsson7b3f2782010-04-02 05:42:15 +00003236 if (HadError)
3237 return;
3238
Anders Carlssone857b292010-04-02 03:37:03 +00003239 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00003240
Alexis Hunt1d792652011-01-08 20:30:50 +00003241 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00003242}
3243
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003244void
John McCalla6309952010-03-16 21:39:52 +00003245Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
3246 CXXRecordDecl *ClassDecl) {
Richard Smith20104042011-09-18 12:11:43 +00003247 // Ignore dependent contexts. Also ignore unions, since their members never
3248 // have destructors implicitly called.
3249 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
Anders Carlssondee9a302009-11-17 04:44:12 +00003250 return;
John McCall1064d7e2010-03-16 05:22:47 +00003251
3252 // FIXME: all the access-control diagnostics are positioned on the
3253 // field/base declaration. That's probably good; that said, the
3254 // user might reasonably want to know why the destructor is being
3255 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00003256
Anders Carlssondee9a302009-11-17 04:44:12 +00003257 // Non-static data members.
3258 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
3259 E = ClassDecl->field_end(); I != E; ++I) {
3260 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00003261 if (Field->isInvalidDecl())
3262 continue;
Douglas Gregor10f939c2011-11-02 23:04:16 +00003263
3264 // Don't destroy incomplete or zero-length arrays.
3265 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
3266 continue;
3267
Anders Carlssondee9a302009-11-17 04:44:12 +00003268 QualType FieldType = Context.getBaseElementType(Field->getType());
3269
3270 const RecordType* RT = FieldType->getAs<RecordType>();
3271 if (!RT)
3272 continue;
3273
3274 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003275 if (FieldClassDecl->isInvalidDecl())
3276 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00003277 if (FieldClassDecl->hasTrivialDestructor())
3278 continue;
3279
Douglas Gregore71edda2010-07-01 22:47:18 +00003280 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003281 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003282 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003283 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00003284 << Field->getDeclName()
3285 << FieldType);
3286
Eli Friedmanfa0df832012-02-02 03:46:19 +00003287 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003288 }
3289
John McCall1064d7e2010-03-16 05:22:47 +00003290 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
3291
Anders Carlssondee9a302009-11-17 04:44:12 +00003292 // Bases.
3293 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
3294 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00003295 // Bases are always records in a well-formed non-dependent class.
3296 const RecordType *RT = Base->getType()->getAs<RecordType>();
3297
3298 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00003299 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00003300 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00003301
John McCall1064d7e2010-03-16 05:22:47 +00003302 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003303 // If our base class is invalid, we probably can't get its dtor anyway.
3304 if (BaseClassDecl->isInvalidDecl())
3305 continue;
3306 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00003307 if (BaseClassDecl->hasTrivialDestructor())
3308 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003309
Douglas Gregore71edda2010-07-01 22:47:18 +00003310 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003311 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003312
3313 // FIXME: caret should be on the start of the class name
3314 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003315 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00003316 << Base->getType()
3317 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00003318
Eli Friedmanfa0df832012-02-02 03:46:19 +00003319 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00003320 }
3321
3322 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003323 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
3324 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00003325
3326 // Bases are always records in a well-formed non-dependent class.
3327 const RecordType *RT = VBase->getType()->getAs<RecordType>();
3328
3329 // Ignore direct virtual bases.
3330 if (DirectVirtualBases.count(RT))
3331 continue;
3332
John McCall1064d7e2010-03-16 05:22:47 +00003333 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003334 // If our base class is invalid, we probably can't get its dtor anyway.
3335 if (BaseClassDecl->isInvalidDecl())
3336 continue;
3337 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003338 if (BaseClassDecl->hasTrivialDestructor())
3339 continue;
John McCall1064d7e2010-03-16 05:22:47 +00003340
Douglas Gregore71edda2010-07-01 22:47:18 +00003341 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00003342 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00003343 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00003344 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00003345 << VBase->getType());
3346
Eli Friedmanfa0df832012-02-02 03:46:19 +00003347 MarkFunctionReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003348 }
3349}
3350
John McCall48871652010-08-21 09:40:31 +00003351void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00003352 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003353 return;
Mike Stump11289f42009-09-09 15:08:12 +00003354
Mike Stump11289f42009-09-09 15:08:12 +00003355 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00003356 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00003357 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00003358}
3359
Mike Stump11289f42009-09-09 15:08:12 +00003360bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003361 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00003362 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00003363 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00003364 else
John McCall02db245d2010-08-18 09:41:07 +00003365 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00003366}
3367
Anders Carlssoneabf7702009-08-27 00:13:57 +00003368bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00003369 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003370 if (!getLangOptions().CPlusPlus)
3371 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003372
Anders Carlssoneb0c5322009-03-23 19:10:31 +00003373 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00003374 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00003375
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003376 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003377 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003378 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003379 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00003380
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003381 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00003382 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00003383 }
Mike Stump11289f42009-09-09 15:08:12 +00003384
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003385 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003386 if (!RT)
3387 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003388
John McCall67da35c2010-02-04 22:26:26 +00003389 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003390
John McCall02db245d2010-08-18 09:41:07 +00003391 // We can't answer whether something is abstract until it has a
3392 // definition. If it's currently being defined, we'll walk back
3393 // over all the declarations when we have a full definition.
3394 const CXXRecordDecl *Def = RD->getDefinition();
3395 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00003396 return false;
3397
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003398 if (!RD->isAbstract())
3399 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003400
Anders Carlssoneabf7702009-08-27 00:13:57 +00003401 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00003402 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00003403
John McCall02db245d2010-08-18 09:41:07 +00003404 return true;
3405}
3406
3407void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
3408 // Check if we've already emitted the list of pure virtual functions
3409 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003410 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00003411 return;
Mike Stump11289f42009-09-09 15:08:12 +00003412
Douglas Gregor4165bd62010-03-23 23:47:56 +00003413 CXXFinalOverriderMap FinalOverriders;
3414 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00003415
Anders Carlssona2f74f32010-06-03 01:00:02 +00003416 // Keep a set of seen pure methods so we won't diagnose the same method
3417 // more than once.
3418 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
3419
Douglas Gregor4165bd62010-03-23 23:47:56 +00003420 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
3421 MEnd = FinalOverriders.end();
3422 M != MEnd;
3423 ++M) {
3424 for (OverridingMethods::iterator SO = M->second.begin(),
3425 SOEnd = M->second.end();
3426 SO != SOEnd; ++SO) {
3427 // C++ [class.abstract]p4:
3428 // A class is abstract if it contains or inherits at least one
3429 // pure virtual function for which the final overrider is pure
3430 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00003431
Douglas Gregor4165bd62010-03-23 23:47:56 +00003432 //
3433 if (SO->second.size() != 1)
3434 continue;
3435
3436 if (!SO->second.front().Method->isPure())
3437 continue;
3438
Anders Carlssona2f74f32010-06-03 01:00:02 +00003439 if (!SeenPureMethods.insert(SO->second.front().Method))
3440 continue;
3441
Douglas Gregor4165bd62010-03-23 23:47:56 +00003442 Diag(SO->second.front().Method->getLocation(),
3443 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00003444 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00003445 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003446 }
3447
3448 if (!PureVirtualClassDiagSet)
3449 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
3450 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00003451}
3452
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003453namespace {
John McCall02db245d2010-08-18 09:41:07 +00003454struct AbstractUsageInfo {
3455 Sema &S;
3456 CXXRecordDecl *Record;
3457 CanQualType AbstractType;
3458 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00003459
John McCall02db245d2010-08-18 09:41:07 +00003460 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
3461 : S(S), Record(Record),
3462 AbstractType(S.Context.getCanonicalType(
3463 S.Context.getTypeDeclType(Record))),
3464 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003465
John McCall02db245d2010-08-18 09:41:07 +00003466 void DiagnoseAbstractType() {
3467 if (Invalid) return;
3468 S.DiagnoseAbstractType(Record);
3469 Invalid = true;
3470 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00003471
John McCall02db245d2010-08-18 09:41:07 +00003472 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
3473};
3474
3475struct CheckAbstractUsage {
3476 AbstractUsageInfo &Info;
3477 const NamedDecl *Ctx;
3478
3479 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
3480 : Info(Info), Ctx(Ctx) {}
3481
3482 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3483 switch (TL.getTypeLocClass()) {
3484#define ABSTRACT_TYPELOC(CLASS, PARENT)
3485#define TYPELOC(CLASS, PARENT) \
3486 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
3487#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003488 }
John McCall02db245d2010-08-18 09:41:07 +00003489 }
Mike Stump11289f42009-09-09 15:08:12 +00003490
John McCall02db245d2010-08-18 09:41:07 +00003491 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3492 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
3493 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00003494 if (!TL.getArg(I))
3495 continue;
3496
John McCall02db245d2010-08-18 09:41:07 +00003497 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
3498 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003499 }
John McCall02db245d2010-08-18 09:41:07 +00003500 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003501
John McCall02db245d2010-08-18 09:41:07 +00003502 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3503 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
3504 }
Mike Stump11289f42009-09-09 15:08:12 +00003505
John McCall02db245d2010-08-18 09:41:07 +00003506 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
3507 // Visit the type parameters from a permissive context.
3508 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
3509 TemplateArgumentLoc TAL = TL.getArgLoc(I);
3510 if (TAL.getArgument().getKind() == TemplateArgument::Type)
3511 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
3512 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
3513 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003514 }
John McCall02db245d2010-08-18 09:41:07 +00003515 }
Mike Stump11289f42009-09-09 15:08:12 +00003516
John McCall02db245d2010-08-18 09:41:07 +00003517 // Visit pointee types from a permissive context.
3518#define CheckPolymorphic(Type) \
3519 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
3520 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
3521 }
3522 CheckPolymorphic(PointerTypeLoc)
3523 CheckPolymorphic(ReferenceTypeLoc)
3524 CheckPolymorphic(MemberPointerTypeLoc)
3525 CheckPolymorphic(BlockPointerTypeLoc)
Eli Friedman0dfb8892011-10-06 23:00:33 +00003526 CheckPolymorphic(AtomicTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00003527
John McCall02db245d2010-08-18 09:41:07 +00003528 /// Handle all the types we haven't given a more specific
3529 /// implementation for above.
3530 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
3531 // Every other kind of type that we haven't called out already
3532 // that has an inner type is either (1) sugar or (2) contains that
3533 // inner type in some way as a subobject.
3534 if (TypeLoc Next = TL.getNextTypeLoc())
3535 return Visit(Next, Sel);
3536
3537 // If there's no inner type and we're in a permissive context,
3538 // don't diagnose.
3539 if (Sel == Sema::AbstractNone) return;
3540
3541 // Check whether the type matches the abstract type.
3542 QualType T = TL.getType();
3543 if (T->isArrayType()) {
3544 Sel = Sema::AbstractArrayType;
3545 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00003546 }
John McCall02db245d2010-08-18 09:41:07 +00003547 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
3548 if (CT != Info.AbstractType) return;
3549
3550 // It matched; do some magic.
3551 if (Sel == Sema::AbstractArrayType) {
3552 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
3553 << T << TL.getSourceRange();
3554 } else {
3555 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
3556 << Sel << T << TL.getSourceRange();
3557 }
3558 Info.DiagnoseAbstractType();
3559 }
3560};
3561
3562void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
3563 Sema::AbstractDiagSelID Sel) {
3564 CheckAbstractUsage(*this, D).Visit(TL, Sel);
3565}
3566
3567}
3568
3569/// Check for invalid uses of an abstract type in a method declaration.
3570static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3571 CXXMethodDecl *MD) {
3572 // No need to do the check on definitions, which require that
3573 // the return/param types be complete.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003574 if (MD->doesThisDeclarationHaveABody())
John McCall02db245d2010-08-18 09:41:07 +00003575 return;
3576
3577 // For safety's sake, just ignore it if we don't have type source
3578 // information. This should never happen for non-implicit methods,
3579 // but...
3580 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
3581 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
3582}
3583
3584/// Check for invalid uses of an abstract type within a class definition.
3585static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
3586 CXXRecordDecl *RD) {
3587 for (CXXRecordDecl::decl_iterator
3588 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
3589 Decl *D = *I;
3590 if (D->isImplicit()) continue;
3591
3592 // Methods and method templates.
3593 if (isa<CXXMethodDecl>(D)) {
3594 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
3595 } else if (isa<FunctionTemplateDecl>(D)) {
3596 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
3597 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
3598
3599 // Fields and static variables.
3600 } else if (isa<FieldDecl>(D)) {
3601 FieldDecl *FD = cast<FieldDecl>(D);
3602 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3603 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3604 } else if (isa<VarDecl>(D)) {
3605 VarDecl *VD = cast<VarDecl>(D);
3606 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3607 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3608
3609 // Nested classes and class templates.
3610 } else if (isa<CXXRecordDecl>(D)) {
3611 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3612 } else if (isa<ClassTemplateDecl>(D)) {
3613 CheckAbstractClassUsage(Info,
3614 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3615 }
3616 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00003617}
3618
Douglas Gregorc99f1552009-12-03 18:33:45 +00003619/// \brief Perform semantic checks on a class definition that has been
3620/// completing, introducing implicitly-declared members, checking for
3621/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003622void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00003623 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00003624 return;
3625
John McCall02db245d2010-08-18 09:41:07 +00003626 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3627 AbstractUsageInfo Info(*this, Record);
3628 CheckAbstractClassUsage(Info, Record);
3629 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00003630
3631 // If this is not an aggregate type and has no user-declared constructor,
3632 // complain about any non-static data members of reference or const scalar
3633 // type, since they will never get initializers.
3634 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
Douglas Gregorfbf19a02012-02-09 02:20:38 +00003635 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
3636 !Record->isLambda()) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003637 bool Complained = false;
3638 for (RecordDecl::field_iterator F = Record->field_begin(),
3639 FEnd = Record->field_end();
3640 F != FEnd; ++F) {
Douglas Gregor556e5862011-10-10 17:22:13 +00003641 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00003642 continue;
3643
Douglas Gregor454a5b62010-04-15 00:00:53 +00003644 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00003645 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00003646 if (!Complained) {
3647 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3648 << Record->getTagKind() << Record;
3649 Complained = true;
3650 }
3651
3652 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3653 << F->getType()->isReferenceType()
3654 << F->getDeclName();
3655 }
3656 }
3657 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00003658
Anders Carlssone771e762011-01-25 18:08:22 +00003659 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00003660 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00003661
3662 if (Record->getIdentifier()) {
3663 // C++ [class.mem]p13:
3664 // If T is the name of a class, then each of the following shall have a
3665 // name different from T:
3666 // - every member of every anonymous union that is a member of class T.
3667 //
3668 // C++ [class.mem]p14:
3669 // In addition, if class T has a user-declared constructor (12.1), every
3670 // non-static data member of class T shall have a name different from T.
3671 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00003672 R.first != R.second; ++R.first) {
3673 NamedDecl *D = *R.first;
3674 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3675 isa<IndirectFieldDecl>(D)) {
3676 Diag(D->getLocation(), diag::err_member_name_of_class)
3677 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00003678 break;
3679 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00003680 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00003681 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003682
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003683 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00003684 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003685 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00003686 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00003687 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3688 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3689 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003690
3691 // See if a method overloads virtual methods in a base
3692 /// class without overriding any.
3693 if (!Record->isDependentType()) {
3694 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3695 MEnd = Record->method_end();
3696 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00003697 if (!(*M)->isStatic())
3698 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00003699 }
3700 }
Sebastian Redl08905022011-02-05 19:23:19 +00003701
Richard Smitheb3c10c2011-10-01 02:31:28 +00003702 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
3703 // function that is not a constructor declares that member function to be
3704 // const. [...] The class of which that function is a member shall be
3705 // a literal type.
3706 //
3707 // It's fine to diagnose constructors here too: such constructors cannot
3708 // produce a constant expression, so are ill-formed (no diagnostic required).
3709 //
3710 // If the class has virtual bases, any constexpr members will already have
3711 // been diagnosed by the checks performed on the member declaration, so
3712 // suppress this (less useful) diagnostic.
3713 if (LangOpts.CPlusPlus0x && !Record->isDependentType() &&
3714 !Record->isLiteral() && !Record->getNumVBases()) {
3715 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3716 MEnd = Record->method_end();
3717 M != MEnd; ++M) {
Eli Friedmanc8002422012-01-13 02:31:53 +00003718 if (M->isConstexpr() && M->isInstance()) {
Richard Smitheb3c10c2011-10-01 02:31:28 +00003719 switch (Record->getTemplateSpecializationKind()) {
3720 case TSK_ImplicitInstantiation:
3721 case TSK_ExplicitInstantiationDeclaration:
3722 case TSK_ExplicitInstantiationDefinition:
3723 // If a template instantiates to a non-literal type, but its members
3724 // instantiate to constexpr functions, the template is technically
3725 // ill-formed, but we allow it for sanity. Such members are treated as
3726 // non-constexpr.
3727 (*M)->setConstexpr(false);
3728 continue;
3729
3730 case TSK_Undeclared:
3731 case TSK_ExplicitSpecialization:
3732 RequireLiteralType((*M)->getLocation(), Context.getRecordType(Record),
3733 PDiag(diag::err_constexpr_method_non_literal));
3734 break;
3735 }
3736
3737 // Only produce one error per class.
3738 break;
3739 }
3740 }
3741 }
3742
Sebastian Redl08905022011-02-05 19:23:19 +00003743 // Declare inherited constructors. We do this eagerly here because:
3744 // - The standard requires an eager diagnostic for conflicting inherited
3745 // constructors from different classes.
3746 // - The lazy declaration of the other implicit constructors is so as to not
3747 // waste space and performance on classes that are not meant to be
3748 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3749 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00003750 DeclareInheritedConstructors(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003751
Alexis Hunt1fb4e762011-05-23 21:07:59 +00003752 if (!Record->isDependentType())
3753 CheckExplicitlyDefaultedMethods(Record);
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003754}
3755
3756void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
Alexis Huntf91729462011-05-12 22:46:25 +00003757 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3758 ME = Record->method_end();
3759 MI != ME; ++MI) {
3760 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3761 switch (getSpecialMember(*MI)) {
3762 case CXXDefaultConstructor:
3763 CheckExplicitlyDefaultedDefaultConstructor(
3764 cast<CXXConstructorDecl>(*MI));
3765 break;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003766
Alexis Huntf91729462011-05-12 22:46:25 +00003767 case CXXDestructor:
3768 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3769 break;
3770
3771 case CXXCopyConstructor:
Alexis Hunt913820d2011-05-13 06:10:58 +00003772 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3773 break;
3774
Alexis Huntf91729462011-05-12 22:46:25 +00003775 case CXXCopyAssignment:
Alexis Huntc9a55732011-05-14 05:23:28 +00003776 CheckExplicitlyDefaultedCopyAssignment(*MI);
Alexis Huntf91729462011-05-12 22:46:25 +00003777 break;
3778
Alexis Hunt119c10e2011-05-25 23:16:36 +00003779 case CXXMoveConstructor:
Sebastian Redl22653ba2011-08-30 19:58:05 +00003780 CheckExplicitlyDefaultedMoveConstructor(cast<CXXConstructorDecl>(*MI));
Alexis Hunt119c10e2011-05-25 23:16:36 +00003781 break;
3782
Sebastian Redl22653ba2011-08-30 19:58:05 +00003783 case CXXMoveAssignment:
3784 CheckExplicitlyDefaultedMoveAssignment(*MI);
3785 break;
3786
3787 case CXXInvalid:
Alexis Huntf91729462011-05-12 22:46:25 +00003788 llvm_unreachable("non-special member explicitly defaulted!");
3789 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003790 }
3791 }
3792
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003793}
3794
3795void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3796 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3797
3798 // Whether this was the first-declared instance of the constructor.
3799 // This affects whether we implicitly add an exception spec (and, eventually,
3800 // constexpr). It is also ill-formed to explicitly default a constructor such
3801 // that it would be deleted. (C++0x [decl.fct.def.default])
3802 bool First = CD == CD->getCanonicalDecl();
3803
Alexis Hunt913820d2011-05-13 06:10:58 +00003804 bool HadError = false;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003805 if (CD->getNumParams() != 0) {
3806 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3807 << CD->getSourceRange();
Alexis Hunt913820d2011-05-13 06:10:58 +00003808 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003809 }
3810
3811 ImplicitExceptionSpecification Spec
3812 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3813 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Richard Smith938f40b2011-06-11 17:19:42 +00003814 if (EPI.ExceptionSpecType == EST_Delayed) {
3815 // Exception specification depends on some deferred part of the class. We'll
3816 // try again when the class's definition has been fully processed.
3817 return;
3818 }
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003819 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3820 *ExceptionType = Context.getFunctionType(
3821 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3822
Richard Smithcc36f692011-12-22 02:22:31 +00003823 // C++11 [dcl.fct.def.default]p2:
3824 // An explicitly-defaulted function may be declared constexpr only if it
3825 // would have been implicitly declared as constexpr,
3826 if (CD->isConstexpr()) {
3827 if (!CD->getParent()->defaultedDefaultConstructorIsConstexpr()) {
3828 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3829 << CXXDefaultConstructor;
3830 HadError = true;
3831 }
3832 }
3833 // and may have an explicit exception-specification only if it is compatible
3834 // with the exception-specification on the implicit declaration.
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003835 if (CtorType->hasExceptionSpec()) {
3836 if (CheckEquivalentExceptionSpec(
Alexis Huntf91729462011-05-12 22:46:25 +00003837 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003838 << CXXDefaultConstructor,
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003839 PDiag(),
3840 ExceptionType, SourceLocation(),
3841 CtorType, CD->getLocation())) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003842 HadError = true;
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003843 }
Richard Smithcc36f692011-12-22 02:22:31 +00003844 }
3845
3846 // If a function is explicitly defaulted on its first declaration,
3847 if (First) {
3848 // -- it is implicitly considered to be constexpr if the implicit
3849 // definition would be,
3850 CD->setConstexpr(CD->getParent()->defaultedDefaultConstructorIsConstexpr());
3851
3852 // -- it is implicitly considered to have the same
3853 // exception-specification as if it had been implicitly declared
3854 //
3855 // FIXME: a compatible, but different, explicit exception specification
3856 // will be silently overridden. We should issue a warning if this happens.
Alexis Huntc9a55732011-05-14 05:23:28 +00003857 EPI.ExtInfo = CtorType->getExtInfo();
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003858 }
Alexis Huntb3153022011-05-12 03:51:48 +00003859
Alexis Hunt913820d2011-05-13 06:10:58 +00003860 if (HadError) {
3861 CD->setInvalidDecl();
3862 return;
3863 }
3864
Alexis Huntd6da8762011-10-10 06:18:57 +00003865 if (ShouldDeleteSpecialMember(CD, CXXDefaultConstructor)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003866 if (First) {
Alexis Huntb3153022011-05-12 03:51:48 +00003867 CD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00003868 } else {
Alexis Huntb3153022011-05-12 03:51:48 +00003869 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003870 << CXXDefaultConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003871 CD->setInvalidDecl();
3872 }
3873 }
3874}
3875
3876void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3877 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3878
3879 // Whether this was the first-declared instance of the constructor.
3880 bool First = CD == CD->getCanonicalDecl();
3881
3882 bool HadError = false;
3883 if (CD->getNumParams() != 1) {
3884 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3885 << CD->getSourceRange();
3886 HadError = true;
3887 }
3888
3889 ImplicitExceptionSpecification Spec(Context);
3890 bool Const;
3891 llvm::tie(Spec, Const) =
3892 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3893
3894 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3895 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3896 *ExceptionType = Context.getFunctionType(
3897 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3898
3899 // Check for parameter type matching.
3900 // This is a copy ctor so we know it's a cv-qualified reference to T.
3901 QualType ArgType = CtorType->getArgType(0);
3902 if (ArgType->getPointeeType().isVolatileQualified()) {
3903 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3904 HadError = true;
3905 }
3906 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3907 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3908 HadError = true;
3909 }
3910
Richard Smithcc36f692011-12-22 02:22:31 +00003911 // C++11 [dcl.fct.def.default]p2:
3912 // An explicitly-defaulted function may be declared constexpr only if it
3913 // would have been implicitly declared as constexpr,
3914 if (CD->isConstexpr()) {
3915 if (!CD->getParent()->defaultedCopyConstructorIsConstexpr()) {
3916 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
3917 << CXXCopyConstructor;
3918 HadError = true;
3919 }
3920 }
3921 // and may have an explicit exception-specification only if it is compatible
3922 // with the exception-specification on the implicit declaration.
Alexis Hunt913820d2011-05-13 06:10:58 +00003923 if (CtorType->hasExceptionSpec()) {
3924 if (CheckEquivalentExceptionSpec(
3925 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003926 << CXXCopyConstructor,
Alexis Hunt913820d2011-05-13 06:10:58 +00003927 PDiag(),
3928 ExceptionType, SourceLocation(),
3929 CtorType, CD->getLocation())) {
3930 HadError = true;
3931 }
Richard Smithcc36f692011-12-22 02:22:31 +00003932 }
3933
3934 // If a function is explicitly defaulted on its first declaration,
3935 if (First) {
3936 // -- it is implicitly considered to be constexpr if the implicit
3937 // definition would be,
3938 CD->setConstexpr(CD->getParent()->defaultedCopyConstructorIsConstexpr());
3939
3940 // -- it is implicitly considered to have the same
3941 // exception-specification as if it had been implicitly declared, and
3942 //
3943 // FIXME: a compatible, but different, explicit exception specification
3944 // will be silently overridden. We should issue a warning if this happens.
Alexis Huntc9a55732011-05-14 05:23:28 +00003945 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithcc36f692011-12-22 02:22:31 +00003946
3947 // -- [...] it shall have the same parameter type as if it had been
3948 // implicitly declared.
Alexis Hunt913820d2011-05-13 06:10:58 +00003949 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3950 }
3951
3952 if (HadError) {
3953 CD->setInvalidDecl();
3954 return;
3955 }
3956
Alexis Hunt1bc6f712011-10-11 04:55:36 +00003957 if (ShouldDeleteSpecialMember(CD, CXXCopyConstructor)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00003958 if (First) {
3959 CD->setDeletedAsWritten();
3960 } else {
3961 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00003962 << CXXCopyConstructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00003963 CD->setInvalidDecl();
3964 }
Alexis Huntb3153022011-05-12 03:51:48 +00003965 }
Alexis Huntea6f0322011-05-11 22:34:38 +00003966}
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00003967
Alexis Huntc9a55732011-05-14 05:23:28 +00003968void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3969 assert(MD->isExplicitlyDefaulted());
3970
3971 // Whether this was the first-declared instance of the operator
3972 bool First = MD == MD->getCanonicalDecl();
3973
3974 bool HadError = false;
3975 if (MD->getNumParams() != 1) {
3976 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3977 << MD->getSourceRange();
3978 HadError = true;
3979 }
3980
3981 QualType ReturnType =
3982 MD->getType()->getAs<FunctionType>()->getResultType();
3983 if (!ReturnType->isLValueReferenceType() ||
3984 !Context.hasSameType(
3985 Context.getCanonicalType(ReturnType->getPointeeType()),
3986 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3987 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3988 HadError = true;
3989 }
3990
3991 ImplicitExceptionSpecification Spec(Context);
3992 bool Const;
3993 llvm::tie(Spec, Const) =
3994 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3995
3996 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3997 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3998 *ExceptionType = Context.getFunctionType(
3999 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4000
Alexis Huntc9a55732011-05-14 05:23:28 +00004001 QualType ArgType = OperType->getArgType(0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00004002 if (!ArgType->isLValueReferenceType()) {
Alexis Hunt604aeb32011-05-17 20:44:43 +00004003 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
Alexis Huntc9a55732011-05-14 05:23:28 +00004004 HadError = true;
Alexis Hunt604aeb32011-05-17 20:44:43 +00004005 } else {
4006 if (ArgType->getPointeeType().isVolatileQualified()) {
4007 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
4008 HadError = true;
4009 }
4010 if (ArgType->getPointeeType().isConstQualified() && !Const) {
4011 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
4012 HadError = true;
4013 }
Alexis Huntc9a55732011-05-14 05:23:28 +00004014 }
Alexis Hunt604aeb32011-05-17 20:44:43 +00004015
Alexis Huntc9a55732011-05-14 05:23:28 +00004016 if (OperType->getTypeQuals()) {
4017 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
4018 HadError = true;
4019 }
4020
4021 if (OperType->hasExceptionSpec()) {
4022 if (CheckEquivalentExceptionSpec(
4023 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004024 << CXXCopyAssignment,
Alexis Huntc9a55732011-05-14 05:23:28 +00004025 PDiag(),
4026 ExceptionType, SourceLocation(),
4027 OperType, MD->getLocation())) {
4028 HadError = true;
4029 }
Richard Smithcc36f692011-12-22 02:22:31 +00004030 }
4031 if (First) {
Alexis Huntc9a55732011-05-14 05:23:28 +00004032 // We set the declaration to have the computed exception spec here.
4033 // We duplicate the one parameter type.
4034 EPI.RefQualifier = OperType->getRefQualifier();
4035 EPI.ExtInfo = OperType->getExtInfo();
4036 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4037 }
4038
4039 if (HadError) {
4040 MD->setInvalidDecl();
4041 return;
4042 }
4043
4044 if (ShouldDeleteCopyAssignmentOperator(MD)) {
4045 if (First) {
4046 MD->setDeletedAsWritten();
4047 } else {
4048 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004049 << CXXCopyAssignment;
Alexis Huntc9a55732011-05-14 05:23:28 +00004050 MD->setInvalidDecl();
4051 }
4052 }
4053}
4054
Sebastian Redl22653ba2011-08-30 19:58:05 +00004055void Sema::CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *CD) {
4056 assert(CD->isExplicitlyDefaulted() && CD->isMoveConstructor());
4057
4058 // Whether this was the first-declared instance of the constructor.
4059 bool First = CD == CD->getCanonicalDecl();
4060
4061 bool HadError = false;
4062 if (CD->getNumParams() != 1) {
4063 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_params)
4064 << CD->getSourceRange();
4065 HadError = true;
4066 }
4067
4068 ImplicitExceptionSpecification Spec(
4069 ComputeDefaultedMoveCtorExceptionSpec(CD->getParent()));
4070
4071 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4072 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
4073 *ExceptionType = Context.getFunctionType(
4074 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4075
4076 // Check for parameter type matching.
4077 // This is a move ctor so we know it's a cv-qualified rvalue reference to T.
4078 QualType ArgType = CtorType->getArgType(0);
4079 if (ArgType->getPointeeType().isVolatileQualified()) {
4080 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_volatile_param);
4081 HadError = true;
4082 }
4083 if (ArgType->getPointeeType().isConstQualified()) {
4084 Diag(CD->getLocation(), diag::err_defaulted_move_ctor_const_param);
4085 HadError = true;
4086 }
4087
Richard Smithcc36f692011-12-22 02:22:31 +00004088 // C++11 [dcl.fct.def.default]p2:
4089 // An explicitly-defaulted function may be declared constexpr only if it
4090 // would have been implicitly declared as constexpr,
4091 if (CD->isConstexpr()) {
4092 if (!CD->getParent()->defaultedMoveConstructorIsConstexpr()) {
4093 Diag(CD->getLocStart(), diag::err_incorrect_defaulted_constexpr)
4094 << CXXMoveConstructor;
4095 HadError = true;
4096 }
4097 }
4098 // and may have an explicit exception-specification only if it is compatible
4099 // with the exception-specification on the implicit declaration.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004100 if (CtorType->hasExceptionSpec()) {
4101 if (CheckEquivalentExceptionSpec(
4102 PDiag(diag::err_incorrect_defaulted_exception_spec)
4103 << CXXMoveConstructor,
4104 PDiag(),
4105 ExceptionType, SourceLocation(),
4106 CtorType, CD->getLocation())) {
4107 HadError = true;
4108 }
Richard Smithcc36f692011-12-22 02:22:31 +00004109 }
4110
4111 // If a function is explicitly defaulted on its first declaration,
4112 if (First) {
4113 // -- it is implicitly considered to be constexpr if the implicit
4114 // definition would be,
4115 CD->setConstexpr(CD->getParent()->defaultedMoveConstructorIsConstexpr());
4116
4117 // -- it is implicitly considered to have the same
4118 // exception-specification as if it had been implicitly declared, and
4119 //
4120 // FIXME: a compatible, but different, explicit exception specification
4121 // will be silently overridden. We should issue a warning if this happens.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004122 EPI.ExtInfo = CtorType->getExtInfo();
Richard Smithcc36f692011-12-22 02:22:31 +00004123
4124 // -- [...] it shall have the same parameter type as if it had been
4125 // implicitly declared.
Sebastian Redl22653ba2011-08-30 19:58:05 +00004126 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
4127 }
4128
4129 if (HadError) {
4130 CD->setInvalidDecl();
4131 return;
4132 }
4133
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004134 if (ShouldDeleteSpecialMember(CD, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004135 if (First) {
4136 CD->setDeletedAsWritten();
4137 } else {
4138 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
4139 << CXXMoveConstructor;
4140 CD->setInvalidDecl();
4141 }
4142 }
4143}
4144
4145void Sema::CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *MD) {
4146 assert(MD->isExplicitlyDefaulted());
4147
4148 // Whether this was the first-declared instance of the operator
4149 bool First = MD == MD->getCanonicalDecl();
4150
4151 bool HadError = false;
4152 if (MD->getNumParams() != 1) {
4153 Diag(MD->getLocation(), diag::err_defaulted_move_assign_params)
4154 << MD->getSourceRange();
4155 HadError = true;
4156 }
4157
4158 QualType ReturnType =
4159 MD->getType()->getAs<FunctionType>()->getResultType();
4160 if (!ReturnType->isLValueReferenceType() ||
4161 !Context.hasSameType(
4162 Context.getCanonicalType(ReturnType->getPointeeType()),
4163 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
4164 Diag(MD->getLocation(), diag::err_defaulted_move_assign_return_type);
4165 HadError = true;
4166 }
4167
4168 ImplicitExceptionSpecification Spec(
4169 ComputeDefaultedMoveCtorExceptionSpec(MD->getParent()));
4170
4171 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4172 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
4173 *ExceptionType = Context.getFunctionType(
4174 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4175
4176 QualType ArgType = OperType->getArgType(0);
4177 if (!ArgType->isRValueReferenceType()) {
4178 Diag(MD->getLocation(), diag::err_defaulted_move_assign_not_ref);
4179 HadError = true;
4180 } else {
4181 if (ArgType->getPointeeType().isVolatileQualified()) {
4182 Diag(MD->getLocation(), diag::err_defaulted_move_assign_volatile_param);
4183 HadError = true;
4184 }
4185 if (ArgType->getPointeeType().isConstQualified()) {
4186 Diag(MD->getLocation(), diag::err_defaulted_move_assign_const_param);
4187 HadError = true;
4188 }
4189 }
4190
4191 if (OperType->getTypeQuals()) {
4192 Diag(MD->getLocation(), diag::err_defaulted_move_assign_quals);
4193 HadError = true;
4194 }
4195
4196 if (OperType->hasExceptionSpec()) {
4197 if (CheckEquivalentExceptionSpec(
4198 PDiag(diag::err_incorrect_defaulted_exception_spec)
4199 << CXXMoveAssignment,
4200 PDiag(),
4201 ExceptionType, SourceLocation(),
4202 OperType, MD->getLocation())) {
4203 HadError = true;
4204 }
Richard Smithcc36f692011-12-22 02:22:31 +00004205 }
4206 if (First) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00004207 // We set the declaration to have the computed exception spec here.
4208 // We duplicate the one parameter type.
4209 EPI.RefQualifier = OperType->getRefQualifier();
4210 EPI.ExtInfo = OperType->getExtInfo();
4211 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
4212 }
4213
4214 if (HadError) {
4215 MD->setInvalidDecl();
4216 return;
4217 }
4218
4219 if (ShouldDeleteMoveAssignmentOperator(MD)) {
4220 if (First) {
4221 MD->setDeletedAsWritten();
4222 } else {
4223 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
4224 << CXXMoveAssignment;
4225 MD->setInvalidDecl();
4226 }
4227 }
4228}
4229
Alexis Huntf91729462011-05-12 22:46:25 +00004230void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
4231 assert(DD->isExplicitlyDefaulted());
4232
4233 // Whether this was the first-declared instance of the destructor.
4234 bool First = DD == DD->getCanonicalDecl();
4235
4236 ImplicitExceptionSpecification Spec
4237 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
4238 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
4239 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
4240 *ExceptionType = Context.getFunctionType(
4241 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
4242
4243 if (DtorType->hasExceptionSpec()) {
4244 if (CheckEquivalentExceptionSpec(
4245 PDiag(diag::err_incorrect_defaulted_exception_spec)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004246 << CXXDestructor,
Alexis Huntf91729462011-05-12 22:46:25 +00004247 PDiag(),
4248 ExceptionType, SourceLocation(),
4249 DtorType, DD->getLocation())) {
4250 DD->setInvalidDecl();
4251 return;
4252 }
Richard Smithcc36f692011-12-22 02:22:31 +00004253 }
4254 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00004255 // We set the declaration to have the computed exception spec here.
4256 // There are no parameters.
Alexis Huntc9a55732011-05-14 05:23:28 +00004257 EPI.ExtInfo = DtorType->getExtInfo();
Alexis Huntf91729462011-05-12 22:46:25 +00004258 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
4259 }
4260
4261 if (ShouldDeleteDestructor(DD)) {
Alexis Hunt913820d2011-05-13 06:10:58 +00004262 if (First) {
Alexis Huntf91729462011-05-12 22:46:25 +00004263 DD->setDeletedAsWritten();
Alexis Hunt913820d2011-05-13 06:10:58 +00004264 } else {
Alexis Huntf91729462011-05-12 22:46:25 +00004265 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
Alexis Hunt119c10e2011-05-25 23:16:36 +00004266 << CXXDestructor;
Alexis Hunt913820d2011-05-13 06:10:58 +00004267 DD->setInvalidDecl();
4268 }
Alexis Huntf91729462011-05-12 22:46:25 +00004269 }
Alexis Huntf91729462011-05-12 22:46:25 +00004270}
4271
Alexis Huntd6da8762011-10-10 06:18:57 +00004272/// This function implements the following C++0x paragraphs:
4273/// - [class.ctor]/5
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004274/// - [class.copy]/11
Alexis Huntd6da8762011-10-10 06:18:57 +00004275bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM) {
4276 assert(!MD->isInvalidDecl());
4277 CXXRecordDecl *RD = MD->getParent();
Alexis Huntea6f0322011-05-11 22:34:38 +00004278 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004279 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntea6f0322011-05-11 22:34:38 +00004280 return false;
4281
Alexis Huntd6da8762011-10-10 06:18:57 +00004282 bool IsUnion = RD->isUnion();
4283 bool IsConstructor = false;
4284 bool IsAssignment = false;
4285 bool IsMove = false;
4286
4287 bool ConstArg = false;
4288
4289 switch (CSM) {
4290 case CXXDefaultConstructor:
4291 IsConstructor = true;
4292 break;
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004293 case CXXCopyConstructor:
4294 IsConstructor = true;
4295 ConstArg = MD->getParamDecl(0)->getType().isConstQualified();
4296 break;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004297 case CXXMoveConstructor:
4298 IsConstructor = true;
4299 IsMove = true;
4300 break;
Alexis Huntd6da8762011-10-10 06:18:57 +00004301 default:
4302 llvm_unreachable("function only currently implemented for default ctors");
4303 }
4304
4305 SourceLocation Loc = MD->getLocation();
Alexis Hunte77a28f2011-05-18 03:41:58 +00004306
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004307 // Do access control from the special member function
Alexis Huntd6da8762011-10-10 06:18:57 +00004308 ContextRAII MethodContext(*this, MD);
Alexis Huntea6f0322011-05-11 22:34:38 +00004309
Alexis Huntea6f0322011-05-11 22:34:38 +00004310 bool AllConst = true;
4311
Alexis Huntea6f0322011-05-11 22:34:38 +00004312 // We do this because we should never actually use an anonymous
4313 // union's constructor.
Alexis Huntd6da8762011-10-10 06:18:57 +00004314 if (IsUnion && RD->isAnonymousStructOrUnion())
Alexis Huntea6f0322011-05-11 22:34:38 +00004315 return false;
4316
4317 // FIXME: We should put some diagnostic logic right into this function.
4318
Alexis Huntea6f0322011-05-11 22:34:38 +00004319 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4320 BE = RD->bases_end();
4321 BI != BE; ++BI) {
Alexis Huntf91729462011-05-12 22:46:25 +00004322 // We'll handle this one later
4323 if (BI->isVirtual())
4324 continue;
4325
Alexis Huntea6f0322011-05-11 22:34:38 +00004326 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4327 assert(BaseDecl && "base isn't a CXXRecordDecl");
4328
Alexis Huntd6da8762011-10-10 06:18:57 +00004329 // Unless we have an assignment operator, the base's destructor must
4330 // be accessible and not deleted.
4331 if (!IsAssignment) {
4332 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4333 if (BaseDtor->isDeleted())
4334 return true;
4335 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4336 AR_accessible)
4337 return true;
4338 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004339
Alexis Huntd6da8762011-10-10 06:18:57 +00004340 // Finding the corresponding member in the base should lead to a
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004341 // unique, accessible, non-deleted function. If we are doing
4342 // a destructor, we have already checked this case.
Alexis Huntd6da8762011-10-10 06:18:57 +00004343 if (CSM != CXXDestructor) {
4344 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004345 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004346 false);
4347 if (!SMOR->hasSuccess())
4348 return true;
4349 CXXMethodDecl *BaseMember = SMOR->getMethod();
4350 if (IsConstructor) {
4351 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4352 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4353 PDiag()) != AR_accessible)
4354 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004355
4356 // For a move operation, the corresponding operation must actually
4357 // be a move operation (and not a copy selected by overload
4358 // resolution) unless we are working on a trivially copyable class.
4359 if (IsMove && !BaseCtor->isMoveConstructor() &&
4360 !BaseDecl->isTriviallyCopyable())
4361 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004362 }
4363 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004364 }
4365
4366 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4367 BE = RD->vbases_end();
4368 BI != BE; ++BI) {
4369 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4370 assert(BaseDecl && "base isn't a CXXRecordDecl");
4371
Alexis Huntd6da8762011-10-10 06:18:57 +00004372 // Unless we have an assignment operator, the base's destructor must
4373 // be accessible and not deleted.
4374 if (!IsAssignment) {
4375 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4376 if (BaseDtor->isDeleted())
4377 return true;
4378 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4379 AR_accessible)
4380 return true;
4381 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004382
Alexis Huntd6da8762011-10-10 06:18:57 +00004383 // Finding the corresponding member in the base should lead to a
4384 // unique, accessible, non-deleted function.
4385 if (CSM != CXXDestructor) {
4386 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004387 LookupSpecialMember(BaseDecl, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004388 false);
4389 if (!SMOR->hasSuccess())
4390 return true;
4391 CXXMethodDecl *BaseMember = SMOR->getMethod();
4392 if (IsConstructor) {
4393 CXXConstructorDecl *BaseCtor = cast<CXXConstructorDecl>(BaseMember);
4394 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(),
4395 PDiag()) != AR_accessible)
4396 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004397
4398 // For a move operation, the corresponding operation must actually
4399 // be a move operation (and not a copy selected by overload
4400 // resolution) unless we are working on a trivially copyable class.
4401 if (IsMove && !BaseCtor->isMoveConstructor() &&
4402 !BaseDecl->isTriviallyCopyable())
4403 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004404 }
4405 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004406 }
4407
4408 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4409 FE = RD->field_end();
4410 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004411 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
Richard Smith938f40b2011-06-11 17:19:42 +00004412 continue;
4413
Alexis Huntea6f0322011-05-11 22:34:38 +00004414 QualType FieldType = Context.getBaseElementType(FI->getType());
4415 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
Richard Smith938f40b2011-06-11 17:19:42 +00004416
Alexis Huntd6da8762011-10-10 06:18:57 +00004417 // For a default constructor, all references must be initialized in-class
4418 // and, if a union, it must have a non-const member.
4419 if (CSM == CXXDefaultConstructor) {
4420 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
4421 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004422
Alexis Huntd6da8762011-10-10 06:18:57 +00004423 if (IsUnion && !FieldType.isConstQualified())
4424 AllConst = false;
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004425 // For a copy constructor, data members must not be of rvalue reference
4426 // type.
4427 } else if (CSM == CXXCopyConstructor) {
4428 if (FieldType->isRValueReferenceType())
4429 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004430 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004431
4432 if (FieldRecord) {
Alexis Huntd6da8762011-10-10 06:18:57 +00004433 // For a default constructor, a const member must have a user-provided
4434 // default constructor or else be explicitly initialized.
4435 if (CSM == CXXDefaultConstructor && FieldType.isConstQualified() &&
Richard Smith938f40b2011-06-11 17:19:42 +00004436 !FI->hasInClassInitializer() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004437 !FieldRecord->hasUserProvidedDefaultConstructor())
4438 return true;
4439
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004440 // Some additional restrictions exist on the variant members.
4441 if (!IsUnion && FieldRecord->isUnion() &&
Alexis Huntea6f0322011-05-11 22:34:38 +00004442 FieldRecord->isAnonymousStructOrUnion()) {
4443 // We're okay to reuse AllConst here since we only care about the
4444 // value otherwise if we're in a union.
4445 AllConst = true;
4446
4447 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4448 UE = FieldRecord->field_end();
4449 UI != UE; ++UI) {
4450 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4451 CXXRecordDecl *UnionFieldRecord =
4452 UnionFieldType->getAsCXXRecordDecl();
4453
4454 if (!UnionFieldType.isConstQualified())
4455 AllConst = false;
4456
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004457 if (UnionFieldRecord) {
4458 // FIXME: Checking for accessibility and validity of this
4459 // destructor is technically going beyond the
4460 // standard, but this is believed to be a defect.
4461 if (!IsAssignment) {
4462 CXXDestructorDecl *FieldDtor = LookupDestructor(UnionFieldRecord);
4463 if (FieldDtor->isDeleted())
4464 return true;
4465 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4466 AR_accessible)
4467 return true;
4468 if (!FieldDtor->isTrivial())
4469 return true;
4470 }
4471
4472 if (CSM != CXXDestructor) {
4473 SpecialMemberOverloadResult *SMOR =
4474 LookupSpecialMember(UnionFieldRecord, CSM, ConstArg, false,
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004475 false, false, false);
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004476 // FIXME: Checking for accessibility and validity of this
4477 // corresponding member is technically going beyond the
4478 // standard, but this is believed to be a defect.
4479 if (!SMOR->hasSuccess())
4480 return true;
4481
4482 CXXMethodDecl *FieldMember = SMOR->getMethod();
4483 // A member of a union must have a trivial corresponding
4484 // constructor.
4485 if (!FieldMember->isTrivial())
4486 return true;
4487
4488 if (IsConstructor) {
4489 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4490 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4491 PDiag()) != AR_accessible)
4492 return true;
4493 }
4494 }
4495 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004496 }
Alexis Hunt1f69a022011-05-12 22:46:29 +00004497
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004498 // At least one member in each anonymous union must be non-const
4499 if (CSM == CXXDefaultConstructor && AllConst)
Alexis Huntea6f0322011-05-11 22:34:38 +00004500 return true;
4501
4502 // Don't try to initialize the anonymous union
Alexis Hunt466627c2011-05-11 22:50:12 +00004503 // This is technically non-conformant, but sanity demands it.
Alexis Huntea6f0322011-05-11 22:34:38 +00004504 continue;
4505 }
Alexis Hunteef8ee02011-06-10 03:50:41 +00004506
Alexis Hunt1bc6f712011-10-11 04:55:36 +00004507 // Unless we're doing assignment, the field's destructor must be
4508 // accessible and not deleted.
4509 if (!IsAssignment) {
4510 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4511 if (FieldDtor->isDeleted())
4512 return true;
4513 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4514 AR_accessible)
4515 return true;
4516 }
4517
Alexis Huntd6da8762011-10-10 06:18:57 +00004518 // Check that the corresponding member of the field is accessible,
4519 // unique, and non-deleted. We don't do this if it has an explicit
4520 // initialization when default-constructing.
4521 if (CSM != CXXDestructor &&
4522 (CSM != CXXDefaultConstructor || !FI->hasInClassInitializer())) {
4523 SpecialMemberOverloadResult *SMOR =
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004524 LookupSpecialMember(FieldRecord, CSM, ConstArg, false, false, false,
Alexis Huntd6da8762011-10-10 06:18:57 +00004525 false);
4526 if (!SMOR->hasSuccess())
Richard Smith938f40b2011-06-11 17:19:42 +00004527 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004528
4529 CXXMethodDecl *FieldMember = SMOR->getMethod();
4530 if (IsConstructor) {
4531 CXXConstructorDecl *FieldCtor = cast<CXXConstructorDecl>(FieldMember);
4532 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
4533 PDiag()) != AR_accessible)
4534 return true;
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00004535
4536 // For a move operation, the corresponding operation must actually
4537 // be a move operation (and not a copy selected by overload
4538 // resolution) unless we are working on a trivially copyable class.
4539 if (IsMove && !FieldCtor->isMoveConstructor() &&
4540 !FieldRecord->isTriviallyCopyable())
4541 return true;
Alexis Huntd6da8762011-10-10 06:18:57 +00004542 }
4543
4544 // We need the corresponding member of a union to be trivial so that
4545 // we can safely copy them all simultaneously.
4546 // FIXME: Note that performing the check here (where we rely on the lack
4547 // of an in-class initializer) is technically ill-formed. However, this
4548 // seems most obviously to be a bug in the standard.
4549 if (IsUnion && !FieldMember->isTrivial())
Richard Smith938f40b2011-06-11 17:19:42 +00004550 return true;
4551 }
Alexis Huntd6da8762011-10-10 06:18:57 +00004552 } else if (CSM == CXXDefaultConstructor && !IsUnion &&
4553 FieldType.isConstQualified() && !FI->hasInClassInitializer()) {
4554 // We can't initialize a const member of non-class type to any value.
Alexis Hunta671bca2011-05-20 21:43:47 +00004555 return true;
Alexis Huntea6f0322011-05-11 22:34:38 +00004556 }
Alexis Huntea6f0322011-05-11 22:34:38 +00004557 }
4558
Alexis Huntd6da8762011-10-10 06:18:57 +00004559 // We can't have all const members in a union when default-constructing,
4560 // or else they're all nonsensical garbage values that can't be changed.
4561 if (CSM == CXXDefaultConstructor && IsUnion && AllConst)
Alexis Huntea6f0322011-05-11 22:34:38 +00004562 return true;
4563
4564 return false;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004565}
4566
Alexis Huntb2f27802011-05-14 05:23:24 +00004567bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
4568 CXXRecordDecl *RD = MD->getParent();
4569 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004570 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntb2f27802011-05-14 05:23:24 +00004571 return false;
4572
Alexis Hunte77a28f2011-05-18 03:41:58 +00004573 SourceLocation Loc = MD->getLocation();
4574
Alexis Huntb2f27802011-05-14 05:23:24 +00004575 // Do access control from the constructor
4576 ContextRAII MethodContext(*this, MD);
4577
4578 bool Union = RD->isUnion();
4579
Alexis Hunt491ec602011-06-21 23:42:56 +00004580 unsigned ArgQuals =
4581 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
4582 Qualifiers::Const : 0;
Alexis Huntb2f27802011-05-14 05:23:24 +00004583
4584 // We do this because we should never actually use an anonymous
4585 // union's constructor.
4586 if (Union && RD->isAnonymousStructOrUnion())
4587 return false;
4588
Alexis Huntb2f27802011-05-14 05:23:24 +00004589 // FIXME: We should put some diagnostic logic right into this function.
4590
Sebastian Redl22653ba2011-08-30 19:58:05 +00004591 // C++0x [class.copy]/20
Alexis Huntb2f27802011-05-14 05:23:24 +00004592 // A defaulted [copy] assignment operator for class X is defined as deleted
4593 // if X has:
4594
4595 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4596 BE = RD->bases_end();
4597 BI != BE; ++BI) {
4598 // We'll handle this one later
4599 if (BI->isVirtual())
4600 continue;
4601
4602 QualType BaseType = BI->getType();
4603 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4604 assert(BaseDecl && "base isn't a CXXRecordDecl");
4605
4606 // -- a [direct base class] B that cannot be [copied] because overload
4607 // resolution, as applied to B's [copy] assignment operator, results in
Alexis Huntc9a55732011-05-14 05:23:28 +00004608 // an ambiguity or a function that is deleted or inaccessible from the
Alexis Huntb2f27802011-05-14 05:23:24 +00004609 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004610 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4611 0);
4612 if (!CopyOper || CopyOper->isDeleted())
4613 return true;
4614 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004615 return true;
4616 }
4617
4618 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4619 BE = RD->vbases_end();
4620 BI != BE; ++BI) {
4621 QualType BaseType = BI->getType();
4622 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4623 assert(BaseDecl && "base isn't a CXXRecordDecl");
4624
Alexis Huntb2f27802011-05-14 05:23:24 +00004625 // -- a [virtual base class] B that cannot be [copied] because overload
Alexis Huntc9a55732011-05-14 05:23:28 +00004626 // resolution, as applied to B's [copy] assignment operator, results in
4627 // an ambiguity or a function that is deleted or inaccessible from the
4628 // assignment operator
Alexis Hunt491ec602011-06-21 23:42:56 +00004629 CXXMethodDecl *CopyOper = LookupCopyingAssignment(BaseDecl, ArgQuals, false,
4630 0);
4631 if (!CopyOper || CopyOper->isDeleted())
4632 return true;
4633 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Alexis Huntb2f27802011-05-14 05:23:24 +00004634 return true;
Alexis Huntb2f27802011-05-14 05:23:24 +00004635 }
4636
4637 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4638 FE = RD->field_end();
4639 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004640 if (FI->isUnnamedBitfield())
4641 continue;
4642
Alexis Huntb2f27802011-05-14 05:23:24 +00004643 QualType FieldType = Context.getBaseElementType(FI->getType());
4644
4645 // -- a non-static data member of reference type
4646 if (FieldType->isReferenceType())
4647 return true;
4648
4649 // -- a non-static data member of const non-class type (or array thereof)
4650 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4651 return true;
4652
4653 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4654
4655 if (FieldRecord) {
4656 // This is an anonymous union
4657 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4658 // Anonymous unions inside unions do not variant members create
4659 if (!Union) {
4660 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4661 UE = FieldRecord->field_end();
4662 UI != UE; ++UI) {
4663 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4664 CXXRecordDecl *UnionFieldRecord =
4665 UnionFieldType->getAsCXXRecordDecl();
4666
4667 // -- a variant member with a non-trivial [copy] assignment operator
4668 // and X is a union-like class
4669 if (UnionFieldRecord &&
4670 !UnionFieldRecord->hasTrivialCopyAssignment())
4671 return true;
4672 }
4673 }
4674
4675 // Don't try to initalize an anonymous union
4676 continue;
4677 // -- a variant member with a non-trivial [copy] assignment operator
4678 // and X is a union-like class
4679 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
4680 return true;
4681 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004682
Alexis Hunt491ec602011-06-21 23:42:56 +00004683 CXXMethodDecl *CopyOper = LookupCopyingAssignment(FieldRecord, ArgQuals,
4684 false, 0);
4685 if (!CopyOper || CopyOper->isDeleted())
Sebastian Redl22653ba2011-08-30 19:58:05 +00004686 return true;
Alexis Hunt491ec602011-06-21 23:42:56 +00004687 if (CheckDirectMemberAccess(Loc, CopyOper, PDiag()) != AR_accessible)
Sebastian Redl22653ba2011-08-30 19:58:05 +00004688 return true;
4689 }
4690 }
4691
4692 return false;
4693}
4694
Sebastian Redl22653ba2011-08-30 19:58:05 +00004695bool Sema::ShouldDeleteMoveAssignmentOperator(CXXMethodDecl *MD) {
4696 CXXRecordDecl *RD = MD->getParent();
4697 assert(!RD->isDependentType() && "do deletion after instantiation");
4698 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
4699 return false;
4700
4701 SourceLocation Loc = MD->getLocation();
4702
4703 // Do access control from the constructor
4704 ContextRAII MethodContext(*this, MD);
4705
4706 bool Union = RD->isUnion();
4707
4708 // We do this because we should never actually use an anonymous
4709 // union's constructor.
4710 if (Union && RD->isAnonymousStructOrUnion())
4711 return false;
4712
4713 // C++0x [class.copy]/20
4714 // A defaulted [move] assignment operator for class X is defined as deleted
4715 // if X has:
4716
4717 // -- for the move constructor, [...] any direct or indirect virtual base
4718 // class.
4719 if (RD->getNumVBases() != 0)
4720 return true;
4721
4722 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4723 BE = RD->bases_end();
4724 BI != BE; ++BI) {
4725
4726 QualType BaseType = BI->getType();
4727 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
4728 assert(BaseDecl && "base isn't a CXXRecordDecl");
4729
4730 // -- a [direct base class] B that cannot be [moved] because overload
4731 // resolution, as applied to B's [move] assignment operator, results in
4732 // an ambiguity or a function that is deleted or inaccessible from the
4733 // assignment operator
4734 CXXMethodDecl *MoveOper = LookupMovingAssignment(BaseDecl, false, 0);
4735 if (!MoveOper || MoveOper->isDeleted())
4736 return true;
4737 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4738 return true;
4739
4740 // -- for the move assignment operator, a [direct base class] with a type
4741 // that does not have a move assignment operator and is not trivially
4742 // copyable.
4743 if (!MoveOper->isMoveAssignmentOperator() &&
4744 !BaseDecl->isTriviallyCopyable())
4745 return true;
4746 }
4747
4748 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4749 FE = RD->field_end();
4750 FI != FE; ++FI) {
Douglas Gregor556e5862011-10-10 17:22:13 +00004751 if (FI->isUnnamedBitfield())
4752 continue;
4753
Sebastian Redl22653ba2011-08-30 19:58:05 +00004754 QualType FieldType = Context.getBaseElementType(FI->getType());
4755
4756 // -- a non-static data member of reference type
4757 if (FieldType->isReferenceType())
4758 return true;
4759
4760 // -- a non-static data member of const non-class type (or array thereof)
4761 if (FieldType.isConstQualified() && !FieldType->isRecordType())
4762 return true;
4763
4764 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4765
4766 if (FieldRecord) {
4767 // This is an anonymous union
4768 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4769 // Anonymous unions inside unions do not variant members create
4770 if (!Union) {
4771 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4772 UE = FieldRecord->field_end();
4773 UI != UE; ++UI) {
4774 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
4775 CXXRecordDecl *UnionFieldRecord =
4776 UnionFieldType->getAsCXXRecordDecl();
4777
4778 // -- a variant member with a non-trivial [move] assignment operator
4779 // and X is a union-like class
4780 if (UnionFieldRecord &&
4781 !UnionFieldRecord->hasTrivialMoveAssignment())
4782 return true;
4783 }
4784 }
4785
4786 // Don't try to initalize an anonymous union
4787 continue;
4788 // -- a variant member with a non-trivial [move] assignment operator
4789 // and X is a union-like class
4790 } else if (Union && !FieldRecord->hasTrivialMoveAssignment()) {
4791 return true;
4792 }
4793
4794 CXXMethodDecl *MoveOper = LookupMovingAssignment(FieldRecord, false, 0);
4795 if (!MoveOper || MoveOper->isDeleted())
4796 return true;
4797 if (CheckDirectMemberAccess(Loc, MoveOper, PDiag()) != AR_accessible)
4798 return true;
4799
4800 // -- for the move assignment operator, a [non-static data member] with a
4801 // type that does not have a move assignment operator and is not
4802 // trivially copyable.
4803 if (!MoveOper->isMoveAssignmentOperator() &&
4804 !FieldRecord->isTriviallyCopyable())
4805 return true;
Alexis Huntc9a55732011-05-14 05:23:28 +00004806 }
Alexis Huntb2f27802011-05-14 05:23:24 +00004807 }
4808
4809 return false;
4810}
4811
Alexis Huntf91729462011-05-12 22:46:25 +00004812bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
4813 CXXRecordDecl *RD = DD->getParent();
4814 assert(!RD->isDependentType() && "do deletion after instantiation");
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00004815 if (!LangOpts.CPlusPlus0x || RD->isInvalidDecl())
Alexis Huntf91729462011-05-12 22:46:25 +00004816 return false;
4817
Alexis Hunte77a28f2011-05-18 03:41:58 +00004818 SourceLocation Loc = DD->getLocation();
4819
Alexis Huntf91729462011-05-12 22:46:25 +00004820 // Do access control from the destructor
4821 ContextRAII CtorContext(*this, DD);
4822
4823 bool Union = RD->isUnion();
4824
Alexis Hunt913820d2011-05-13 06:10:58 +00004825 // We do this because we should never actually use an anonymous
4826 // union's destructor.
4827 if (Union && RD->isAnonymousStructOrUnion())
4828 return false;
4829
Alexis Huntf91729462011-05-12 22:46:25 +00004830 // C++0x [class.dtor]p5
4831 // A defaulted destructor for a class X is defined as deleted if:
4832 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
4833 BE = RD->bases_end();
4834 BI != BE; ++BI) {
4835 // We'll handle this one later
4836 if (BI->isVirtual())
4837 continue;
4838
4839 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4840 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4841 assert(BaseDtor && "base has no destructor");
4842
4843 // -- any direct or virtual base class has a deleted destructor or
4844 // a destructor that is inaccessible from the defaulted destructor
4845 if (BaseDtor->isDeleted())
4846 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004847 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004848 AR_accessible)
4849 return true;
4850 }
4851
4852 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
4853 BE = RD->vbases_end();
4854 BI != BE; ++BI) {
4855 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
4856 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
4857 assert(BaseDtor && "base has no destructor");
4858
4859 // -- any direct or virtual base class has a deleted destructor or
4860 // a destructor that is inaccessible from the defaulted destructor
4861 if (BaseDtor->isDeleted())
4862 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004863 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004864 AR_accessible)
4865 return true;
4866 }
4867
4868 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4869 FE = RD->field_end();
4870 FI != FE; ++FI) {
4871 QualType FieldType = Context.getBaseElementType(FI->getType());
4872 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4873 if (FieldRecord) {
4874 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4875 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4876 UE = FieldRecord->field_end();
4877 UI != UE; ++UI) {
4878 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4879 CXXRecordDecl *UnionFieldRecord =
4880 UnionFieldType->getAsCXXRecordDecl();
4881
4882 // -- X is a union-like class that has a variant member with a non-
4883 // trivial destructor.
4884 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4885 return true;
4886 }
4887 // Technically we are supposed to do this next check unconditionally.
4888 // But that makes absolutely no sense.
4889 } else {
4890 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4891
4892 // -- any of the non-static data members has class type M (or array
4893 // thereof) and M has a deleted destructor or a destructor that is
4894 // inaccessible from the defaulted destructor
4895 if (FieldDtor->isDeleted())
4896 return true;
Alexis Hunte77a28f2011-05-18 03:41:58 +00004897 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
Alexis Huntf91729462011-05-12 22:46:25 +00004898 AR_accessible)
4899 return true;
4900
4901 // -- X is a union-like class that has a variant member with a non-
4902 // trivial destructor.
4903 if (Union && !FieldDtor->isTrivial())
4904 return true;
4905 }
4906 }
4907 }
4908
4909 if (DD->isVirtual()) {
4910 FunctionDecl *OperatorDelete = 0;
4911 DeclarationName Name =
4912 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Alexis Hunte77a28f2011-05-18 03:41:58 +00004913 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
Alexis Huntf91729462011-05-12 22:46:25 +00004914 false))
4915 return true;
4916 }
4917
4918
4919 return false;
4920}
4921
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004922/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00004923namespace {
4924 struct FindHiddenVirtualMethodData {
4925 Sema *S;
4926 CXXMethodDecl *Method;
4927 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004928 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
Benjamin Kramer024e6192011-03-04 13:12:48 +00004929 };
4930}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004931
4932/// \brief Member lookup function that determines whether a given C++
4933/// method overloads virtual methods in a base class without overriding any,
4934/// to be used with CXXRecordDecl::lookupInBases().
4935static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4936 CXXBasePath &Path,
4937 void *UserData) {
4938 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4939
4940 FindHiddenVirtualMethodData &Data
4941 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4942
4943 DeclarationName Name = Data.Method->getDeclName();
4944 assert(Name.getNameKind() == DeclarationName::Identifier);
4945
4946 bool foundSameNameMethod = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004947 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004948 for (Path.Decls = BaseRecord->lookup(Name);
4949 Path.Decls.first != Path.Decls.second;
4950 ++Path.Decls.first) {
4951 NamedDecl *D = *Path.Decls.first;
4952 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004953 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004954 foundSameNameMethod = true;
4955 // Interested only in hidden virtual methods.
4956 if (!MD->isVirtual())
4957 continue;
4958 // If the method we are checking overrides a method from its base
4959 // don't warn about the other overloaded methods.
4960 if (!Data.S->IsOverload(Data.Method, MD, false))
4961 return true;
4962 // Collect the overload only if its hidden.
4963 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4964 overloadedMethods.push_back(MD);
4965 }
4966 }
4967
4968 if (foundSameNameMethod)
4969 Data.OverloadedMethods.append(overloadedMethods.begin(),
4970 overloadedMethods.end());
4971 return foundSameNameMethod;
4972}
4973
4974/// \brief See if a method overloads virtual methods in a base class without
4975/// overriding any.
4976void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4977 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
David Blaikie9c902b52011-09-25 23:23:43 +00004978 MD->getLocation()) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004979 return;
4980 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4981 return;
4982
4983 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4984 /*bool RecordPaths=*/false,
4985 /*bool DetectVirtual=*/false);
4986 FindHiddenVirtualMethodData Data;
4987 Data.Method = MD;
4988 Data.S = this;
4989
4990 // Keep the base methods that were overriden or introduced in the subclass
4991 // by 'using' in a set. A base method not in this set is hidden.
4992 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4993 res.first != res.second; ++res.first) {
4994 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4995 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4996 E = MD->end_overridden_methods();
4997 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00004998 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00004999 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
5000 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00005001 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00005002 }
5003
5004 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
5005 !Data.OverloadedMethods.empty()) {
5006 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
5007 << MD << (Data.OverloadedMethods.size() > 1);
5008
5009 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
5010 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
5011 Diag(overloadedMD->getLocation(),
5012 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
5013 }
5014 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00005015}
5016
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005017void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00005018 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005019 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00005020 SourceLocation RBrac,
5021 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005022 if (!TagDecl)
5023 return;
Mike Stump11289f42009-09-09 15:08:12 +00005024
Douglas Gregorc9f9b862009-05-11 19:58:34 +00005025 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00005026
David Blaikie751c5582011-09-22 02:58:26 +00005027 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
John McCall48871652010-08-21 09:40:31 +00005028 // strict aliasing violation!
5029 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
David Blaikie751c5582011-09-22 02:58:26 +00005030 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00005031
Douglas Gregor0be31a22010-07-02 17:43:08 +00005032 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00005033 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00005034}
5035
Douglas Gregor05379422008-11-03 17:51:48 +00005036/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
5037/// special functions, such as the default constructor, copy
5038/// constructor, or destructor, to the given C++ class (C++
5039/// [special]p1). This routine can only be executed just before the
5040/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005041void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00005042 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00005043 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005044
Douglas Gregor54be3392010-07-01 17:57:27 +00005045 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00005046 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00005047
Richard Smith966c1fb2011-12-24 21:56:24 +00005048 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveConstructor())
5049 ++ASTContext::NumImplicitMoveConstructors;
5050
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005051 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
5052 ++ASTContext::NumImplicitCopyAssignmentOperators;
5053
5054 // If we have a dynamic class, then the copy assignment operator may be
5055 // virtual, so we have to declare it immediately. This ensures that, e.g.,
5056 // it shows up in the right place in the vtable and that we diagnose
5057 // problems with the implicit exception specification.
5058 if (ClassDecl->isDynamicClass())
5059 DeclareImplicitCopyAssignment(ClassDecl);
5060 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005061
Richard Smith966c1fb2011-12-24 21:56:24 +00005062 if (getLangOptions().CPlusPlus0x && ClassDecl->needsImplicitMoveAssignment()){
5063 ++ASTContext::NumImplicitMoveAssignmentOperators;
5064
5065 // Likewise for the move assignment operator.
5066 if (ClassDecl->isDynamicClass())
5067 DeclareImplicitMoveAssignment(ClassDecl);
5068 }
5069
Douglas Gregor7454c562010-07-02 20:37:36 +00005070 if (!ClassDecl->hasUserDeclaredDestructor()) {
5071 ++ASTContext::NumImplicitDestructors;
5072
5073 // If we have a dynamic class, then the destructor may be virtual, so we
5074 // have to declare the destructor immediately. This ensures that, e.g., it
5075 // shows up in the right place in the vtable and that we diagnose problems
5076 // with the implicit exception specification.
5077 if (ClassDecl->isDynamicClass())
5078 DeclareImplicitDestructor(ClassDecl);
5079 }
Douglas Gregor05379422008-11-03 17:51:48 +00005080}
5081
Francois Pichet1c229c02011-04-22 22:18:13 +00005082void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
5083 if (!D)
5084 return;
5085
5086 int NumParamList = D->getNumTemplateParameterLists();
5087 for (int i = 0; i < NumParamList; i++) {
5088 TemplateParameterList* Params = D->getTemplateParameterList(i);
5089 for (TemplateParameterList::iterator Param = Params->begin(),
5090 ParamEnd = Params->end();
5091 Param != ParamEnd; ++Param) {
5092 NamedDecl *Named = cast<NamedDecl>(*Param);
5093 if (Named->getDeclName()) {
5094 S->AddDecl(Named);
5095 IdResolver.AddDecl(Named);
5096 }
5097 }
5098 }
5099}
5100
John McCall48871652010-08-21 09:40:31 +00005101void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00005102 if (!D)
5103 return;
5104
5105 TemplateParameterList *Params = 0;
5106 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
5107 Params = Template->getTemplateParameters();
5108 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
5109 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
5110 Params = PartialSpec->getTemplateParameters();
5111 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005112 return;
5113
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005114 for (TemplateParameterList::iterator Param = Params->begin(),
5115 ParamEnd = Params->end();
5116 Param != ParamEnd; ++Param) {
5117 NamedDecl *Named = cast<NamedDecl>(*Param);
5118 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00005119 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00005120 IdResolver.AddDecl(Named);
5121 }
5122 }
5123}
5124
John McCall48871652010-08-21 09:40:31 +00005125void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005126 if (!RecordD) return;
5127 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00005128 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00005129 PushDeclContext(S, Record);
5130}
5131
John McCall48871652010-08-21 09:40:31 +00005132void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00005133 if (!RecordD) return;
5134 PopDeclContext();
5135}
5136
Douglas Gregor4d87df52008-12-16 21:30:33 +00005137/// ActOnStartDelayedCXXMethodDeclaration - We have completed
5138/// parsing a top-level (non-nested) C++ class, and we are now
5139/// parsing those parts of the given Method declaration that could
5140/// not be parsed earlier (C++ [class.mem]p2), such as default
5141/// arguments. This action should enter the scope of the given
5142/// Method declaration as if we had just parsed the qualified method
5143/// name. However, it should not bring the parameters into scope;
5144/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00005145void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005146}
5147
5148/// ActOnDelayedCXXMethodParameter - We've already started a delayed
5149/// C++ method declaration. We're (re-)introducing the given
5150/// function parameter into scope for use in parsing later parts of
5151/// the method declaration. For example, we could see an
5152/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00005153void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005154 if (!ParamD)
5155 return;
Mike Stump11289f42009-09-09 15:08:12 +00005156
John McCall48871652010-08-21 09:40:31 +00005157 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00005158
5159 // If this parameter has an unparsed default argument, clear it out
5160 // to make way for the parsed default argument.
5161 if (Param->hasUnparsedDefaultArg())
5162 Param->setDefaultArg(0);
5163
John McCall48871652010-08-21 09:40:31 +00005164 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005165 if (Param->getDeclName())
5166 IdResolver.AddDecl(Param);
5167}
5168
5169/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
5170/// processing the delayed method declaration for Method. The method
5171/// declaration is now considered finished. There may be a separate
5172/// ActOnStartOfFunctionDef action later (not necessarily
5173/// immediately!) for this method, if it was also defined inside the
5174/// class body.
John McCall48871652010-08-21 09:40:31 +00005175void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00005176 if (!MethodD)
5177 return;
Mike Stump11289f42009-09-09 15:08:12 +00005178
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005179 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00005180
John McCall48871652010-08-21 09:40:31 +00005181 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005182
5183 // Now that we have our default arguments, check the constructor
5184 // again. It could produce additional diagnostics or affect whether
5185 // the class has implicitly-declared destructors, among other
5186 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005187 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
5188 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00005189
5190 // Check the default arguments, which we may have added.
5191 if (!Method->isInvalidDecl())
5192 CheckCXXDefaultArguments(Method);
5193}
5194
Douglas Gregor831c93f2008-11-05 20:51:48 +00005195/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00005196/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00005197/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005198/// emit diagnostics and set the invalid bit to true. In any case, the type
5199/// will be updated to reflect a well-formed type for the constructor and
5200/// returned.
5201QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005202 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005203 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005204
5205 // C++ [class.ctor]p3:
5206 // A constructor shall not be virtual (10.3) or static (9.4). A
5207 // constructor can be invoked for a const, volatile or const
5208 // volatile object. A constructor shall not be declared const,
5209 // volatile, or const volatile (9.3.2).
5210 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005211 if (!D.isInvalidType())
5212 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5213 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
5214 << SourceRange(D.getIdentifierLoc());
5215 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005216 }
John McCall8e7d6562010-08-26 03:08:43 +00005217 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005218 if (!D.isInvalidType())
5219 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
5220 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5221 << SourceRange(D.getIdentifierLoc());
5222 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005223 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005224 }
Mike Stump11289f42009-09-09 15:08:12 +00005225
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005226 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005227 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00005228 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005229 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5230 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005231 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005232 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5233 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005234 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005235 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
5236 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00005237 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005238 }
Mike Stump11289f42009-09-09 15:08:12 +00005239
Douglas Gregordb9d6642011-01-26 05:01:58 +00005240 // C++0x [class.ctor]p4:
5241 // A constructor shall not be declared with a ref-qualifier.
5242 if (FTI.hasRefQualifier()) {
5243 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
5244 << FTI.RefQualifierIsLValueRef
5245 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5246 D.setInvalidType();
5247 }
5248
Douglas Gregor831c93f2008-11-05 20:51:48 +00005249 // Rebuild the function type "R" without any type qualifiers (in
5250 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00005251 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00005252 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005253 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
5254 return R;
5255
5256 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5257 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005258 EPI.RefQualifier = RQ_None;
5259
Chris Lattner38378bf2009-04-25 08:28:21 +00005260 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00005261 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005262}
5263
Douglas Gregor4d87df52008-12-16 21:30:33 +00005264/// CheckConstructor - Checks a fully-formed constructor for
5265/// well-formedness, issuing any diagnostics required. Returns true if
5266/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005267void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00005268 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005269 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
5270 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005271 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005272
5273 // C++ [class.copy]p3:
5274 // A declaration of a constructor for a class X is ill-formed if
5275 // its first parameter is of type (optionally cv-qualified) X and
5276 // either there are no other parameters or else all other
5277 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00005278 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00005279 ((Constructor->getNumParams() == 1) ||
5280 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00005281 Constructor->getParamDecl(1)->hasDefaultArg())) &&
5282 Constructor->getTemplateSpecializationKind()
5283 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00005284 QualType ParamType = Constructor->getParamDecl(0)->getType();
5285 QualType ClassTy = Context.getTagDeclType(ClassDecl);
5286 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00005287 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00005288 const char *ConstRef
5289 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
5290 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00005291 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00005292 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00005293
5294 // FIXME: Rather that making the constructor invalid, we should endeavor
5295 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005296 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00005297 }
5298 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00005299}
5300
John McCalldeb646e2010-08-04 01:04:25 +00005301/// CheckDestructor - Checks a fully-formed destructor definition for
5302/// well-formedness, issuing any diagnostics required. Returns true
5303/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00005304bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00005305 CXXRecordDecl *RD = Destructor->getParent();
5306
5307 if (Destructor->isVirtual()) {
5308 SourceLocation Loc;
5309
5310 if (!Destructor->isImplicit())
5311 Loc = Destructor->getLocation();
5312 else
5313 Loc = RD->getLocation();
5314
5315 // If we have a virtual destructor, look up the deallocation function
5316 FunctionDecl *OperatorDelete = 0;
5317 DeclarationName Name =
5318 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00005319 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00005320 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00005321
Eli Friedmanfa0df832012-02-02 03:46:19 +00005322 MarkFunctionReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00005323
5324 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00005325 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00005326
5327 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00005328}
5329
Mike Stump11289f42009-09-09 15:08:12 +00005330static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00005331FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
5332 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5333 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00005334 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00005335}
5336
Douglas Gregor831c93f2008-11-05 20:51:48 +00005337/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
5338/// the well-formednes of the destructor declarator @p D with type @p
5339/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00005340/// emit diagnostics and set the declarator to invalid. Even if this happens,
5341/// will be updated to reflect a well-formed type for the destructor and
5342/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00005343QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00005344 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005345 // C++ [class.dtor]p1:
5346 // [...] A typedef-name that names a class is a class-name
5347 // (7.1.3); however, a typedef-name that names a class shall not
5348 // be used as the identifier in the declarator for a destructor
5349 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00005350 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Richard Smithdda56e42011-04-15 14:24:37 +00005351 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
Chris Lattner38378bf2009-04-25 08:28:21 +00005352 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Richard Smithdda56e42011-04-15 14:24:37 +00005353 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
Richard Smith3f1b5d02011-05-05 21:57:07 +00005354 else if (const TemplateSpecializationType *TST =
5355 DeclaratorType->getAs<TemplateSpecializationType>())
5356 if (TST->isTypeAlias())
5357 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
5358 << DeclaratorType << 1;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005359
5360 // C++ [class.dtor]p2:
5361 // A destructor is used to destroy objects of its class type. A
5362 // destructor takes no parameters, and no return type can be
5363 // specified for it (not even void). The address of a destructor
5364 // shall not be taken. A destructor shall not be static. A
5365 // destructor can be invoked for a const, volatile or const
5366 // volatile object. A destructor shall not be declared const,
5367 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00005368 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00005369 if (!D.isInvalidType())
5370 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
5371 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00005372 << SourceRange(D.getIdentifierLoc())
5373 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5374
John McCall8e7d6562010-08-26 03:08:43 +00005375 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00005376 }
Chris Lattner38378bf2009-04-25 08:28:21 +00005377 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005378 // Destructors don't have return types, but the parser will
5379 // happily parse something like:
5380 //
5381 // class X {
5382 // float ~X();
5383 // };
5384 //
5385 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00005386 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
5387 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5388 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00005389 }
Mike Stump11289f42009-09-09 15:08:12 +00005390
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005391 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00005392 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00005393 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00005394 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5395 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005396 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00005397 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5398 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00005399 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00005400 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
5401 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00005402 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005403 }
5404
Douglas Gregordb9d6642011-01-26 05:01:58 +00005405 // C++0x [class.dtor]p2:
5406 // A destructor shall not be declared with a ref-qualifier.
5407 if (FTI.hasRefQualifier()) {
5408 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
5409 << FTI.RefQualifierIsLValueRef
5410 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
5411 D.setInvalidType();
5412 }
5413
Douglas Gregor831c93f2008-11-05 20:51:48 +00005414 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00005415 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005416 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
5417
5418 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00005419 FTI.freeArgs();
5420 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00005421 }
5422
Mike Stump11289f42009-09-09 15:08:12 +00005423 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00005424 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00005425 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00005426 D.setInvalidType();
5427 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00005428
5429 // Rebuild the function type "R" without any type qualifiers or
5430 // parameters (in case any of the errors above fired) and with
5431 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00005432 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00005433 if (!D.isInvalidType())
5434 return R;
5435
Douglas Gregor95755162010-07-01 05:10:53 +00005436 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00005437 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
5438 EPI.Variadic = false;
5439 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00005440 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00005441 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00005442}
5443
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005444/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
5445/// well-formednes of the conversion function declarator @p D with
5446/// type @p R. If there are any errors in the declarator, this routine
5447/// will emit diagnostics and return true. Otherwise, it will return
5448/// false. Either way, the type @p R will be updated to reflect a
5449/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005450void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00005451 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005452 // C++ [class.conv.fct]p1:
5453 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00005454 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00005455 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00005456 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005457 if (!D.isInvalidType())
5458 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
5459 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
5460 << SourceRange(D.getIdentifierLoc());
5461 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00005462 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005463 }
John McCall212fa2e2010-04-13 00:04:31 +00005464
5465 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
5466
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005467 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005468 // Conversion functions don't have return types, but the parser will
5469 // happily parse something like:
5470 //
5471 // class X {
5472 // float operator bool();
5473 // };
5474 //
5475 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00005476 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
5477 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
5478 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00005479 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005480 }
5481
John McCall212fa2e2010-04-13 00:04:31 +00005482 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
5483
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005484 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00005485 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005486 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
5487
5488 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00005489 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005490 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00005491 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005492 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005493 D.setInvalidType();
5494 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005495
John McCall212fa2e2010-04-13 00:04:31 +00005496 // Diagnose "&operator bool()" and other such nonsense. This
5497 // is actually a gcc extension which we don't support.
5498 if (Proto->getResultType() != ConvType) {
5499 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
5500 << Proto->getResultType();
5501 D.setInvalidType();
5502 ConvType = Proto->getResultType();
5503 }
5504
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005505 // C++ [class.conv.fct]p4:
5506 // The conversion-type-id shall not represent a function type nor
5507 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005508 if (ConvType->isArrayType()) {
5509 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
5510 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005511 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005512 } else if (ConvType->isFunctionType()) {
5513 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
5514 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00005515 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005516 }
5517
5518 // Rebuild the function type "R" without any parameters (in case any
5519 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00005520 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00005521 if (D.isInvalidType())
5522 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005523
Douglas Gregor5fb53972009-01-14 15:45:31 +00005524 // C++0x explicit conversion operators.
Richard Smith0bf8a4922011-10-18 20:49:44 +00005525 if (D.getDeclSpec().isExplicitSpecified())
Mike Stump11289f42009-09-09 15:08:12 +00005526 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Richard Smith0bf8a4922011-10-18 20:49:44 +00005527 getLangOptions().CPlusPlus0x ?
5528 diag::warn_cxx98_compat_explicit_conversion_functions :
5529 diag::ext_explicit_conversion_functions)
Douglas Gregor5fb53972009-01-14 15:45:31 +00005530 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005531}
5532
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005533/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
5534/// the declaration of the given C++ conversion function. This routine
5535/// is responsible for recording the conversion function in the C++
5536/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00005537Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005538 assert(Conversion && "Expected to receive a conversion function declaration");
5539
Douglas Gregor4287b372008-12-12 08:25:50 +00005540 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005541
5542 // Make sure we aren't redeclaring the conversion function.
5543 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005544
5545 // C++ [class.conv.fct]p1:
5546 // [...] A conversion function is never used to convert a
5547 // (possibly cv-qualified) object to the (possibly cv-qualified)
5548 // same object type (or a reference to it), to a (possibly
5549 // cv-qualified) base class of that type (or a reference to it),
5550 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00005551 // FIXME: Suppress this warning if the conversion function ends up being a
5552 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00005553 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005554 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005555 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005556 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005557 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
5558 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00005559 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00005560 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005561 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
5562 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005563 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005564 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005565 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005566 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005567 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005568 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00005569 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005570 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005571 }
5572
Douglas Gregor457104e2010-09-29 04:25:11 +00005573 if (FunctionTemplateDecl *ConversionTemplate
5574 = Conversion->getDescribedFunctionTemplate())
5575 return ConversionTemplate;
5576
John McCall48871652010-08-21 09:40:31 +00005577 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00005578}
5579
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005580//===----------------------------------------------------------------------===//
5581// Namespace Handling
5582//===----------------------------------------------------------------------===//
5583
John McCallb1be5232010-08-26 09:15:37 +00005584
5585
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005586/// ActOnStartNamespaceDef - This is called at the start of a namespace
5587/// definition.
John McCall48871652010-08-21 09:40:31 +00005588Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00005589 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005590 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00005591 SourceLocation IdentLoc,
5592 IdentifierInfo *II,
5593 SourceLocation LBrace,
5594 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005595 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
5596 // For anonymous namespace, take the location of the left brace.
5597 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregore57e7522012-01-07 09:11:48 +00005598 bool IsInline = InlineLoc.isValid();
Douglas Gregor21b3b292012-01-10 22:14:10 +00005599 bool IsInvalid = false;
Douglas Gregore57e7522012-01-07 09:11:48 +00005600 bool IsStd = false;
5601 bool AddToKnown = false;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005602 Scope *DeclRegionScope = NamespcScope->getParent();
5603
Douglas Gregore57e7522012-01-07 09:11:48 +00005604 NamespaceDecl *PrevNS = 0;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005605 if (II) {
5606 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00005607 // The identifier in an original-namespace-definition shall not
5608 // have been previously defined in the declarative region in
5609 // which the original-namespace-definition appears. The
5610 // identifier in an original-namespace-definition is the name of
5611 // the namespace. Subsequently in that declarative region, it is
5612 // treated as an original-namespace-name.
5613 //
5614 // Since namespace names are unique in their scope, and we don't
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005615 // look through using directives, just look for any ordinary names.
5616
5617 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
Douglas Gregore57e7522012-01-07 09:11:48 +00005618 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
5619 Decl::IDNS_Namespace;
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005620 NamedDecl *PrevDecl = 0;
5621 for (DeclContext::lookup_result R
Douglas Gregore57e7522012-01-07 09:11:48 +00005622 = CurContext->getRedeclContext()->lookup(II);
Douglas Gregorb578fbe2011-05-06 23:28:47 +00005623 R.first != R.second; ++R.first) {
5624 if ((*R.first)->getIdentifierNamespace() & IDNS) {
5625 PrevDecl = *R.first;
5626 break;
5627 }
5628 }
5629
Douglas Gregore57e7522012-01-07 09:11:48 +00005630 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
5631
5632 if (PrevNS) {
Douglas Gregor91f84212008-12-11 16:49:14 +00005633 // This is an extended namespace definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005634 if (IsInline != PrevNS->isInline()) {
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005635 // inline-ness must match
Douglas Gregore57e7522012-01-07 09:11:48 +00005636 if (PrevNS->isInline()) {
Douglas Gregora9121972011-05-20 15:48:31 +00005637 // The user probably just forgot the 'inline', so suggest that it
5638 // be added back.
Douglas Gregore57e7522012-01-07 09:11:48 +00005639 Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
Douglas Gregora9121972011-05-20 15:48:31 +00005640 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
5641 } else {
Douglas Gregore57e7522012-01-07 09:11:48 +00005642 Diag(Loc, diag::err_inline_namespace_mismatch)
5643 << IsInline;
Douglas Gregora9121972011-05-20 15:48:31 +00005644 }
Douglas Gregore57e7522012-01-07 09:11:48 +00005645 Diag(PrevNS->getLocation(), diag::note_previous_definition);
5646
5647 IsInline = PrevNS->isInline();
5648 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005649 } else if (PrevDecl) {
5650 // This is an invalid name redefinition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005651 Diag(Loc, diag::err_redefinition_different_kind)
5652 << II;
Douglas Gregor91f84212008-12-11 16:49:14 +00005653 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005654 IsInvalid = true;
Douglas Gregor91f84212008-12-11 16:49:14 +00005655 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregore57e7522012-01-07 09:11:48 +00005656 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00005657 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00005658 // This is the first "real" definition of the namespace "std", so update
5659 // our cache of the "std" namespace to point at this definition.
Douglas Gregore57e7522012-01-07 09:11:48 +00005660 PrevNS = getStdNamespace();
5661 IsStd = true;
5662 AddToKnown = !IsInline;
5663 } else {
5664 // We've seen this namespace for the first time.
5665 AddToKnown = !IsInline;
Mike Stump11289f42009-09-09 15:08:12 +00005666 }
Douglas Gregor91f84212008-12-11 16:49:14 +00005667 } else {
John McCall4fa53422009-10-01 00:25:31 +00005668 // Anonymous namespaces.
Douglas Gregore57e7522012-01-07 09:11:48 +00005669
5670 // Determine whether the parent already has an anonymous namespace.
Sebastian Redl50c68252010-08-31 00:36:30 +00005671 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00005672 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
Douglas Gregore57e7522012-01-07 09:11:48 +00005673 PrevNS = TU->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00005674 } else {
5675 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
Douglas Gregore57e7522012-01-07 09:11:48 +00005676 PrevNS = ND->getAnonymousNamespace();
John McCall0db42252009-12-16 02:06:49 +00005677 }
5678
Douglas Gregore57e7522012-01-07 09:11:48 +00005679 if (PrevNS && IsInline != PrevNS->isInline()) {
5680 // inline-ness must match
5681 Diag(Loc, diag::err_inline_namespace_mismatch)
5682 << IsInline;
5683 Diag(PrevNS->getLocation(), diag::note_previous_definition);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005684
Douglas Gregore57e7522012-01-07 09:11:48 +00005685 // Recover by ignoring the new namespace's inline status.
5686 IsInline = PrevNS->isInline();
5687 }
5688 }
5689
5690 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
5691 StartLoc, Loc, II, PrevNS);
Douglas Gregor21b3b292012-01-10 22:14:10 +00005692 if (IsInvalid)
5693 Namespc->setInvalidDecl();
Douglas Gregore57e7522012-01-07 09:11:48 +00005694
5695 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00005696
Douglas Gregore57e7522012-01-07 09:11:48 +00005697 // FIXME: Should we be merging attributes?
5698 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00005699 PushNamespaceVisibilityAttr(Attr, Loc);
Douglas Gregore57e7522012-01-07 09:11:48 +00005700
5701 if (IsStd)
5702 StdNamespace = Namespc;
5703 if (AddToKnown)
5704 KnownNamespaces[Namespc] = false;
5705
5706 if (II) {
5707 PushOnScopeChains(Namespc, DeclRegionScope);
5708 } else {
5709 // Link the anonymous namespace into its parent.
5710 DeclContext *Parent = CurContext->getRedeclContext();
5711 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
5712 TU->setAnonymousNamespace(Namespc);
5713 } else {
5714 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
John McCall0db42252009-12-16 02:06:49 +00005715 }
John McCall4fa53422009-10-01 00:25:31 +00005716
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00005717 CurContext->addDecl(Namespc);
5718
John McCall4fa53422009-10-01 00:25:31 +00005719 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
5720 // behaves as if it were replaced by
5721 // namespace unique { /* empty body */ }
5722 // using namespace unique;
5723 // namespace unique { namespace-body }
5724 // where all occurrences of 'unique' in a translation unit are
5725 // replaced by the same identifier and this identifier differs
5726 // from all other identifiers in the entire program.
5727
5728 // We just create the namespace with an empty name and then add an
5729 // implicit using declaration, just like the standard suggests.
5730 //
5731 // CodeGen enforces the "universally unique" aspect by giving all
5732 // declarations semantically contained within an anonymous
5733 // namespace internal linkage.
5734
Douglas Gregore57e7522012-01-07 09:11:48 +00005735 if (!PrevNS) {
John McCall0db42252009-12-16 02:06:49 +00005736 UsingDirectiveDecl* UD
5737 = UsingDirectiveDecl::Create(Context, CurContext,
5738 /* 'using' */ LBrace,
5739 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00005740 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00005741 /* identifier */ SourceLocation(),
5742 Namespc,
5743 /* Ancestor */ CurContext);
5744 UD->setImplicit();
5745 CurContext->addDecl(UD);
5746 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005747 }
5748
5749 // Although we could have an invalid decl (i.e. the namespace name is a
5750 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00005751 // FIXME: We should be able to push Namespc here, so that the each DeclContext
5752 // for the namespace has the declarations that showed up in that particular
5753 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00005754 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00005755 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005756}
5757
Sebastian Redla6602e92009-11-23 15:34:23 +00005758/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
5759/// is a namespace alias, returns the namespace it points to.
5760static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
5761 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
5762 return AD->getNamespace();
5763 return dyn_cast_or_null<NamespaceDecl>(D);
5764}
5765
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005766/// ActOnFinishNamespaceDef - This callback is called after a namespace is
5767/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00005768void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005769 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
5770 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005771 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005772 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00005773 if (Namespc->hasAttr<VisibilityAttr>())
Rafael Espindola6d65d7b2012-02-01 23:24:59 +00005774 PopPragmaVisibility(true, RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00005775}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005776
John McCall28a0cf72010-08-25 07:42:41 +00005777CXXRecordDecl *Sema::getStdBadAlloc() const {
5778 return cast_or_null<CXXRecordDecl>(
5779 StdBadAlloc.get(Context.getExternalSource()));
5780}
5781
5782NamespaceDecl *Sema::getStdNamespace() const {
5783 return cast_or_null<NamespaceDecl>(
5784 StdNamespace.get(Context.getExternalSource()));
5785}
5786
Douglas Gregorcdf87022010-06-29 17:53:46 +00005787/// \brief Retrieve the special "std" namespace, which may require us to
5788/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00005789NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00005790 if (!StdNamespace) {
5791 // The "std" namespace has not yet been defined, so build one implicitly.
5792 StdNamespace = NamespaceDecl::Create(Context,
5793 Context.getTranslationUnitDecl(),
Douglas Gregore57e7522012-01-07 09:11:48 +00005794 /*Inline=*/false,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00005795 SourceLocation(), SourceLocation(),
Douglas Gregore57e7522012-01-07 09:11:48 +00005796 &PP.getIdentifierTable().get("std"),
5797 /*PrevDecl=*/0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005798 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00005799 }
5800
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00005801 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00005802}
5803
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005804bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
5805 assert(getLangOptions().CPlusPlus &&
5806 "Looking for std::initializer_list outside of C++.");
5807
5808 // We're looking for implicit instantiations of
5809 // template <typename E> class std::initializer_list.
5810
5811 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
5812 return false;
5813
Sebastian Redl43144e72012-01-17 22:49:58 +00005814 ClassTemplateDecl *Template = 0;
5815 const TemplateArgument *Arguments = 0;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005816
Sebastian Redl43144e72012-01-17 22:49:58 +00005817 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005818
Sebastian Redl43144e72012-01-17 22:49:58 +00005819 ClassTemplateSpecializationDecl *Specialization =
5820 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
5821 if (!Specialization)
5822 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005823
Sebastian Redl43144e72012-01-17 22:49:58 +00005824 Template = Specialization->getSpecializedTemplate();
5825 Arguments = Specialization->getTemplateArgs().data();
5826 } else if (const TemplateSpecializationType *TST =
5827 Ty->getAs<TemplateSpecializationType>()) {
5828 Template = dyn_cast_or_null<ClassTemplateDecl>(
5829 TST->getTemplateName().getAsTemplateDecl());
5830 Arguments = TST->getArgs();
5831 }
5832 if (!Template)
5833 return false;
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005834
5835 if (!StdInitializerList) {
5836 // Haven't recognized std::initializer_list yet, maybe this is it.
5837 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
5838 if (TemplateClass->getIdentifier() !=
5839 &PP.getIdentifierTable().get("initializer_list") ||
Sebastian Redl09edce02012-01-23 22:09:39 +00005840 !getStdNamespace()->InEnclosingNamespaceSetOf(
5841 TemplateClass->getDeclContext()))
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005842 return false;
5843 // This is a template called std::initializer_list, but is it the right
5844 // template?
5845 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00005846 if (Params->getMinRequiredArguments() != 1)
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005847 return false;
5848 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
5849 return false;
5850
5851 // It's the right template.
5852 StdInitializerList = Template;
5853 }
5854
5855 if (Template != StdInitializerList)
5856 return false;
5857
5858 // This is an instance of std::initializer_list. Find the argument type.
Sebastian Redl43144e72012-01-17 22:49:58 +00005859 if (Element)
5860 *Element = Arguments[0].getAsType();
Sebastian Redl2bfa1042012-01-17 22:49:33 +00005861 return true;
5862}
5863
Sebastian Redl42acd4a2012-01-17 22:50:08 +00005864static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
5865 NamespaceDecl *Std = S.getStdNamespace();
5866 if (!Std) {
5867 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5868 return 0;
5869 }
5870
5871 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
5872 Loc, Sema::LookupOrdinaryName);
5873 if (!S.LookupQualifiedName(Result, Std)) {
5874 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
5875 return 0;
5876 }
5877 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
5878 if (!Template) {
5879 Result.suppressDiagnostics();
5880 // We found something weird. Complain about the first thing we found.
5881 NamedDecl *Found = *Result.begin();
5882 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
5883 return 0;
5884 }
5885
5886 // We found some template called std::initializer_list. Now verify that it's
5887 // correct.
5888 TemplateParameterList *Params = Template->getTemplateParameters();
Sebastian Redl09edce02012-01-23 22:09:39 +00005889 if (Params->getMinRequiredArguments() != 1 ||
5890 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
Sebastian Redl42acd4a2012-01-17 22:50:08 +00005891 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
5892 return 0;
5893 }
5894
5895 return Template;
5896}
5897
5898QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
5899 if (!StdInitializerList) {
5900 StdInitializerList = LookupStdInitializerList(*this, Loc);
5901 if (!StdInitializerList)
5902 return QualType();
5903 }
5904
5905 TemplateArgumentListInfo Args(Loc, Loc);
5906 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
5907 Context.getTrivialTypeSourceInfo(Element,
5908 Loc)));
5909 return Context.getCanonicalType(
5910 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
5911}
5912
Sebastian Redlbe24ec22012-01-17 22:50:14 +00005913bool Sema::isInitListConstructor(const CXXConstructorDecl* Ctor) {
5914 // C++ [dcl.init.list]p2:
5915 // A constructor is an initializer-list constructor if its first parameter
5916 // is of type std::initializer_list<E> or reference to possibly cv-qualified
5917 // std::initializer_list<E> for some type E, and either there are no other
5918 // parameters or else all other parameters have default arguments.
5919 if (Ctor->getNumParams() < 1 ||
5920 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
5921 return false;
5922
5923 QualType ArgType = Ctor->getParamDecl(0)->getType();
5924 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
5925 ArgType = RT->getPointeeType().getUnqualifiedType();
5926
5927 return isStdInitializerList(ArgType, 0);
5928}
5929
Douglas Gregora172e082011-03-26 22:25:30 +00005930/// \brief Determine whether a using statement is in a context where it will be
5931/// apply in all contexts.
5932static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
5933 switch (CurContext->getDeclKind()) {
5934 case Decl::TranslationUnit:
5935 return true;
5936 case Decl::LinkageSpec:
5937 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
5938 default:
5939 return false;
5940 }
5941}
5942
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005943namespace {
5944
5945// Callback to only accept typo corrections that are namespaces.
5946class NamespaceValidatorCCC : public CorrectionCandidateCallback {
5947 public:
5948 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
5949 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
5950 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
5951 }
5952 return false;
5953 }
5954};
5955
5956}
5957
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005958static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
5959 CXXScopeSpec &SS,
5960 SourceLocation IdentLoc,
5961 IdentifierInfo *Ident) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005962 NamespaceValidatorCCC Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005963 R.clear();
5964 if (TypoCorrection Corrected = S.CorrectTypo(R.getLookupNameInfo(),
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005965 R.getLookupKind(), Sc, &SS,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00005966 Validator)) {
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005967 std::string CorrectedStr(Corrected.getAsString(S.getLangOptions()));
5968 std::string CorrectedQuotedStr(Corrected.getQuoted(S.getLangOptions()));
5969 if (DeclContext *DC = S.computeDeclContext(SS, false))
5970 S.Diag(IdentLoc, diag::err_using_directive_member_suggest)
5971 << Ident << DC << CorrectedQuotedStr << SS.getRange()
5972 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
5973 else
5974 S.Diag(IdentLoc, diag::err_using_directive_suggest)
5975 << Ident << CorrectedQuotedStr
5976 << FixItHint::CreateReplacement(IdentLoc, CorrectedStr);
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005977
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005978 S.Diag(Corrected.getCorrectionDecl()->getLocation(),
5979 diag::note_namespace_defined_here) << CorrectedQuotedStr;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005980
Kaelyn Uhrain2d317ed2012-01-11 19:37:46 +00005981 Ident = Corrected.getCorrectionAsIdentifierInfo();
5982 R.addDecl(Corrected.getCorrectionDecl());
5983 return true;
Douglas Gregorc2fa1692011-06-28 16:20:02 +00005984 }
5985 return false;
5986}
5987
John McCall48871652010-08-21 09:40:31 +00005988Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005989 SourceLocation UsingLoc,
5990 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00005991 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00005992 SourceLocation IdentLoc,
5993 IdentifierInfo *NamespcName,
5994 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00005995 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5996 assert(NamespcName && "Invalid NamespcName.");
5997 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00005998
5999 // This can only happen along a recovery path.
6000 while (S->getFlags() & Scope::TemplateParamScope)
6001 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00006002 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00006003
Douglas Gregor889ceb72009-02-03 19:21:40 +00006004 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00006005 NestedNameSpecifier *Qualifier = 0;
6006 if (SS.isSet())
6007 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6008
Douglas Gregor34074322009-01-14 22:20:51 +00006009 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006010 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
6011 LookupParsedName(R, S, &SS);
6012 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006013 return 0;
John McCall27b18f82009-11-17 02:14:36 +00006014
Douglas Gregorcdf87022010-06-29 17:53:46 +00006015 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006016 R.clear();
Douglas Gregorcdf87022010-06-29 17:53:46 +00006017 // Allow "using namespace std;" or "using namespace ::std;" even if
6018 // "std" hasn't been defined yet, for GCC compatibility.
6019 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
6020 NamespcName->isStr("std")) {
6021 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00006022 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00006023 R.resolveKind();
6024 }
6025 // Otherwise, attempt typo correction.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006026 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00006027 }
6028
John McCall9f3059a2009-10-09 21:13:30 +00006029 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00006030 NamedDecl *Named = R.getFoundDecl();
6031 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
6032 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00006033 // C++ [namespace.udir]p1:
6034 // A using-directive specifies that the names in the nominated
6035 // namespace can be used in the scope in which the
6036 // using-directive appears after the using-directive. During
6037 // unqualified name lookup (3.4.1), the names appear as if they
6038 // were declared in the nearest enclosing namespace which
6039 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00006040 // namespace. [Note: in this context, "contains" means "contains
6041 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00006042
6043 // Find enclosing context containing both using-directive and
6044 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00006045 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006046 DeclContext *CommonAncestor = cast<DeclContext>(NS);
6047 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
6048 CommonAncestor = CommonAncestor->getParent();
6049
Sebastian Redla6602e92009-11-23 15:34:23 +00006050 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00006051 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00006052 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006053
Douglas Gregora172e082011-03-26 22:25:30 +00006054 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Chandler Carruth35f53202011-07-25 16:49:02 +00006055 !SourceMgr.isFromMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00006056 Diag(IdentLoc, diag::warn_using_directive_in_header);
6057 }
6058
Douglas Gregor889ceb72009-02-03 19:21:40 +00006059 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006060 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00006061 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00006062 }
6063
Douglas Gregor889ceb72009-02-03 19:21:40 +00006064 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00006065 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00006066}
6067
6068void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
6069 // If scope has associated entity, then using directive is at namespace
6070 // or translation unit scope. We add UsingDirectiveDecls, into
6071 // it's lookup structure.
6072 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006073 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00006074 else
6075 // Otherwise it is block-sope. using-directives will affect lookup
6076 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00006077 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00006078}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006079
Douglas Gregorfec52632009-06-20 00:51:54 +00006080
John McCall48871652010-08-21 09:40:31 +00006081Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00006082 AccessSpecifier AS,
6083 bool HasUsingKeyword,
6084 SourceLocation UsingLoc,
6085 CXXScopeSpec &SS,
6086 UnqualifiedId &Name,
6087 AttributeList *AttrList,
6088 bool IsTypeName,
6089 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00006090 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00006091
Douglas Gregor220f4272009-11-04 16:30:06 +00006092 switch (Name.getKind()) {
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00006093 case UnqualifiedId::IK_ImplicitSelfParam:
Douglas Gregor220f4272009-11-04 16:30:06 +00006094 case UnqualifiedId::IK_Identifier:
6095 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00006096 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00006097 case UnqualifiedId::IK_ConversionFunctionId:
6098 break;
6099
6100 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00006101 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00006102 // C++0x inherited constructors.
Richard Smith0bf8a4922011-10-18 20:49:44 +00006103 Diag(Name.getSourceRange().getBegin(),
6104 getLangOptions().CPlusPlus0x ?
6105 diag::warn_cxx98_compat_using_decl_constructor :
6106 diag::err_using_decl_constructor)
6107 << SS.getRange();
6108
John McCall3969e302009-12-08 07:46:18 +00006109 if (getLangOptions().CPlusPlus0x) break;
6110
John McCall48871652010-08-21 09:40:31 +00006111 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006112
6113 case UnqualifiedId::IK_DestructorName:
6114 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
6115 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006116 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006117
6118 case UnqualifiedId::IK_TemplateId:
6119 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
6120 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00006121 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00006122 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006123
6124 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
6125 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00006126 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00006127 return 0;
John McCall3969e302009-12-08 07:46:18 +00006128
John McCalla0097262009-12-11 02:10:03 +00006129 // Warn about using declarations.
6130 // TODO: store that the declaration was written without 'using' and
6131 // talk about access decls instead of using decls in the
6132 // diagnostics.
6133 if (!HasUsingKeyword) {
6134 UsingLoc = Name.getSourceRange().getBegin();
6135
6136 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00006137 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00006138 }
6139
Douglas Gregorc4356532010-12-16 00:46:58 +00006140 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
6141 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
6142 return 0;
6143
John McCall3f746822009-11-17 05:59:44 +00006144 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006145 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006146 /* IsInstantiation */ false,
6147 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00006148 if (UD)
6149 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00006150
John McCall48871652010-08-21 09:40:31 +00006151 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00006152}
6153
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006154/// \brief Determine whether a using declaration considers the given
6155/// declarations as "equivalent", e.g., if they are redeclarations of
6156/// the same entity or are both typedefs of the same type.
6157static bool
6158IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
6159 bool &SuppressRedeclaration) {
6160 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
6161 SuppressRedeclaration = false;
6162 return true;
6163 }
6164
Richard Smithdda56e42011-04-15 14:24:37 +00006165 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
6166 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006167 SuppressRedeclaration = true;
6168 return Context.hasSameType(TD1->getUnderlyingType(),
6169 TD2->getUnderlyingType());
6170 }
6171
6172 return false;
6173}
6174
6175
John McCall84d87672009-12-10 09:41:52 +00006176/// Determines whether to create a using shadow decl for a particular
6177/// decl, given the set of decls existing prior to this using lookup.
6178bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
6179 const LookupResult &Previous) {
6180 // Diagnose finding a decl which is not from a base class of the
6181 // current class. We do this now because there are cases where this
6182 // function will silently decide not to build a shadow decl, which
6183 // will pre-empt further diagnostics.
6184 //
6185 // We don't need to do this in C++0x because we do the check once on
6186 // the qualifier.
6187 //
6188 // FIXME: diagnose the following if we care enough:
6189 // struct A { int foo; };
6190 // struct B : A { using A::foo; };
6191 // template <class T> struct C : A {};
6192 // template <class T> struct D : C<T> { using B::foo; } // <---
6193 // This is invalid (during instantiation) in C++03 because B::foo
6194 // resolves to the using decl in B, which is not a base class of D<T>.
6195 // We can't diagnose it immediately because C<T> is an unknown
6196 // specialization. The UsingShadowDecl in D<T> then points directly
6197 // to A::foo, which will look well-formed when we instantiate.
6198 // The right solution is to not collapse the shadow-decl chain.
6199 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
6200 DeclContext *OrigDC = Orig->getDeclContext();
6201
6202 // Handle enums and anonymous structs.
6203 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
6204 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
6205 while (OrigRec->isAnonymousStructOrUnion())
6206 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
6207
6208 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
6209 if (OrigDC == CurContext) {
6210 Diag(Using->getLocation(),
6211 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006212 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006213 Diag(Orig->getLocation(), diag::note_using_decl_target);
6214 return true;
6215 }
6216
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006217 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00006218 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006219 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00006220 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006221 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00006222 Diag(Orig->getLocation(), diag::note_using_decl_target);
6223 return true;
6224 }
6225 }
6226
6227 if (Previous.empty()) return false;
6228
6229 NamedDecl *Target = Orig;
6230 if (isa<UsingShadowDecl>(Target))
6231 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6232
John McCalla17e83e2009-12-11 02:33:26 +00006233 // If the target happens to be one of the previous declarations, we
6234 // don't have a conflict.
6235 //
6236 // FIXME: but we might be increasing its access, in which case we
6237 // should redeclare it.
6238 NamedDecl *NonTag = 0, *Tag = 0;
6239 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6240 I != E; ++I) {
6241 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00006242 bool Result;
6243 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
6244 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00006245
6246 (isa<TagDecl>(D) ? Tag : NonTag) = D;
6247 }
6248
John McCall84d87672009-12-10 09:41:52 +00006249 if (Target->isFunctionOrFunctionTemplate()) {
6250 FunctionDecl *FD;
6251 if (isa<FunctionTemplateDecl>(Target))
6252 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
6253 else
6254 FD = cast<FunctionDecl>(Target);
6255
6256 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00006257 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00006258 case Ovl_Overload:
6259 return false;
6260
6261 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00006262 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006263 break;
6264
6265 // We found a decl with the exact signature.
6266 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00006267 // If we're in a record, we want to hide the target, so we
6268 // return true (without a diagnostic) to tell the caller not to
6269 // build a shadow decl.
6270 if (CurContext->isRecord())
6271 return true;
6272
6273 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00006274 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006275 break;
6276 }
6277
6278 Diag(Target->getLocation(), diag::note_using_decl_target);
6279 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
6280 return true;
6281 }
6282
6283 // Target is not a function.
6284
John McCall84d87672009-12-10 09:41:52 +00006285 if (isa<TagDecl>(Target)) {
6286 // No conflict between a tag and a non-tag.
6287 if (!Tag) return false;
6288
John McCalle29c5cd2009-12-10 19:51:03 +00006289 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006290 Diag(Target->getLocation(), diag::note_using_decl_target);
6291 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
6292 return true;
6293 }
6294
6295 // No conflict between a tag and a non-tag.
6296 if (!NonTag) return false;
6297
John McCalle29c5cd2009-12-10 19:51:03 +00006298 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00006299 Diag(Target->getLocation(), diag::note_using_decl_target);
6300 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
6301 return true;
6302}
6303
John McCall3f746822009-11-17 05:59:44 +00006304/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00006305UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00006306 UsingDecl *UD,
6307 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00006308
6309 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00006310 NamedDecl *Target = Orig;
6311 if (isa<UsingShadowDecl>(Target)) {
6312 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
6313 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00006314 }
6315
6316 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00006317 = UsingShadowDecl::Create(Context, CurContext,
6318 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00006319 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00006320
6321 Shadow->setAccess(UD->getAccess());
6322 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
6323 Shadow->setInvalidDecl();
6324
John McCall3f746822009-11-17 05:59:44 +00006325 if (S)
John McCall3969e302009-12-08 07:46:18 +00006326 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00006327 else
John McCall3969e302009-12-08 07:46:18 +00006328 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00006329
John McCall3969e302009-12-08 07:46:18 +00006330
John McCall84d87672009-12-10 09:41:52 +00006331 return Shadow;
6332}
John McCall3969e302009-12-08 07:46:18 +00006333
John McCall84d87672009-12-10 09:41:52 +00006334/// Hides a using shadow declaration. This is required by the current
6335/// using-decl implementation when a resolvable using declaration in a
6336/// class is followed by a declaration which would hide or override
6337/// one or more of the using decl's targets; for example:
6338///
6339/// struct Base { void foo(int); };
6340/// struct Derived : Base {
6341/// using Base::foo;
6342/// void foo(int);
6343/// };
6344///
6345/// The governing language is C++03 [namespace.udecl]p12:
6346///
6347/// When a using-declaration brings names from a base class into a
6348/// derived class scope, member functions in the derived class
6349/// override and/or hide member functions with the same name and
6350/// parameter types in a base class (rather than conflicting).
6351///
6352/// There are two ways to implement this:
6353/// (1) optimistically create shadow decls when they're not hidden
6354/// by existing declarations, or
6355/// (2) don't create any shadow decls (or at least don't make them
6356/// visible) until we've fully parsed/instantiated the class.
6357/// The problem with (1) is that we might have to retroactively remove
6358/// a shadow decl, which requires several O(n) operations because the
6359/// decl structures are (very reasonably) not designed for removal.
6360/// (2) avoids this but is very fiddly and phase-dependent.
6361void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00006362 if (Shadow->getDeclName().getNameKind() ==
6363 DeclarationName::CXXConversionFunctionName)
6364 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
6365
John McCall84d87672009-12-10 09:41:52 +00006366 // Remove it from the DeclContext...
6367 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006368
John McCall84d87672009-12-10 09:41:52 +00006369 // ...and the scope, if applicable...
6370 if (S) {
John McCall48871652010-08-21 09:40:31 +00006371 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00006372 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00006373 }
6374
John McCall84d87672009-12-10 09:41:52 +00006375 // ...and the using decl.
6376 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
6377
6378 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00006379 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00006380}
6381
John McCalle61f2ba2009-11-18 02:36:19 +00006382/// Builds a using declaration.
6383///
6384/// \param IsInstantiation - Whether this call arises from an
6385/// instantiation of an unresolved using declaration. We treat
6386/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00006387NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
6388 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006389 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006390 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00006391 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00006392 bool IsInstantiation,
6393 bool IsTypeName,
6394 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00006395 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006396 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00006397 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00006398
Anders Carlssonf038fc22009-08-28 05:49:21 +00006399 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00006400
Anders Carlsson59140b32009-08-28 03:16:11 +00006401 if (SS.isEmpty()) {
6402 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00006403 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00006404 }
Mike Stump11289f42009-09-09 15:08:12 +00006405
John McCall84d87672009-12-10 09:41:52 +00006406 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006407 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00006408 ForRedeclaration);
6409 Previous.setHideTags(false);
6410 if (S) {
6411 LookupName(Previous, S);
6412
6413 // It is really dumb that we have to do this.
6414 LookupResult::Filter F = Previous.makeFilter();
6415 while (F.hasNext()) {
6416 NamedDecl *D = F.next();
6417 if (!isDeclInScope(D, CurContext, S))
6418 F.erase();
6419 }
6420 F.done();
6421 } else {
6422 assert(IsInstantiation && "no scope in non-instantiation");
6423 assert(CurContext->isRecord() && "scope not record in instantiation");
6424 LookupQualifiedName(Previous, CurContext);
6425 }
6426
John McCall84d87672009-12-10 09:41:52 +00006427 // Check for invalid redeclarations.
6428 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
6429 return 0;
6430
6431 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00006432 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
6433 return 0;
6434
John McCall84c16cf2009-11-12 03:15:40 +00006435 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006436 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006437 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00006438 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00006439 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00006440 // FIXME: not all declaration name kinds are legal here
6441 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
6442 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006443 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006444 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00006445 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006446 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
6447 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00006448 }
John McCallb96ec562009-12-04 22:46:56 +00006449 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006450 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
6451 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00006452 }
John McCallb96ec562009-12-04 22:46:56 +00006453 D->setAccess(AS);
6454 CurContext->addDecl(D);
6455
6456 if (!LookupContext) return D;
6457 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00006458
John McCall0b66eb32010-05-01 00:40:08 +00006459 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00006460 UD->setInvalidDecl();
6461 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00006462 }
6463
Sebastian Redl08905022011-02-05 19:23:19 +00006464 // Constructor inheriting using decls get special treatment.
6465 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00006466 if (CheckInheritedConstructorUsingDecl(UD))
6467 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00006468 return UD;
6469 }
6470
6471 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00006472
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006473 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00006474
John McCall3969e302009-12-08 07:46:18 +00006475 // Unlike most lookups, we don't always want to hide tag
6476 // declarations: tag names are visible through the using declaration
6477 // even if hidden by ordinary names, *except* in a dependent context
6478 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00006479 if (!IsInstantiation)
6480 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00006481
John McCall27b18f82009-11-17 02:14:36 +00006482 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00006483
John McCall9f3059a2009-10-09 21:13:30 +00006484 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00006485 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00006486 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006487 UD->setInvalidDecl();
6488 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006489 }
6490
John McCallb96ec562009-12-04 22:46:56 +00006491 if (R.isAmbiguous()) {
6492 UD->setInvalidDecl();
6493 return UD;
6494 }
Mike Stump11289f42009-09-09 15:08:12 +00006495
John McCalle61f2ba2009-11-18 02:36:19 +00006496 if (IsTypeName) {
6497 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00006498 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006499 Diag(IdentLoc, diag::err_using_typename_non_type);
6500 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
6501 Diag((*I)->getUnderlyingDecl()->getLocation(),
6502 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006503 UD->setInvalidDecl();
6504 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006505 }
6506 } else {
6507 // If we asked for a non-typename and we got a type, error out,
6508 // but only if this is an instantiation of an unresolved using
6509 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00006510 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00006511 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
6512 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00006513 UD->setInvalidDecl();
6514 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00006515 }
Anders Carlsson59140b32009-08-28 03:16:11 +00006516 }
6517
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006518 // C++0x N2914 [namespace.udecl]p6:
6519 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00006520 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006521 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
6522 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00006523 UD->setInvalidDecl();
6524 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00006525 }
Mike Stump11289f42009-09-09 15:08:12 +00006526
John McCall84d87672009-12-10 09:41:52 +00006527 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
6528 if (!CheckUsingShadowDecl(UD, *I, Previous))
6529 BuildUsingShadowDecl(S, UD, *I);
6530 }
John McCall3f746822009-11-17 05:59:44 +00006531
6532 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00006533}
6534
Sebastian Redl08905022011-02-05 19:23:19 +00006535/// Additional checks for a using declaration referring to a constructor name.
6536bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
6537 if (UD->isTypeName()) {
6538 // FIXME: Cannot specify typename when specifying constructor
6539 return true;
6540 }
6541
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006542 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00006543 assert(SourceType &&
6544 "Using decl naming constructor doesn't have type in scope spec.");
6545 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
6546
6547 // Check whether the named type is a direct base class.
6548 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
6549 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
6550 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
6551 BaseIt != BaseE; ++BaseIt) {
6552 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
6553 if (CanonicalSourceType == BaseType)
6554 break;
6555 }
6556
6557 if (BaseIt == BaseE) {
6558 // Did not find SourceType in the bases.
6559 Diag(UD->getUsingLocation(),
6560 diag::err_using_decl_constructor_not_in_direct_base)
6561 << UD->getNameInfo().getSourceRange()
6562 << QualType(SourceType, 0) << TargetClass;
6563 return true;
6564 }
6565
6566 BaseIt->setInheritConstructors();
6567
6568 return false;
6569}
6570
John McCall84d87672009-12-10 09:41:52 +00006571/// Checks that the given using declaration is not an invalid
6572/// redeclaration. Note that this is checking only for the using decl
6573/// itself, not for any ill-formedness among the UsingShadowDecls.
6574bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
6575 bool isTypeName,
6576 const CXXScopeSpec &SS,
6577 SourceLocation NameLoc,
6578 const LookupResult &Prev) {
6579 // C++03 [namespace.udecl]p8:
6580 // C++0x [namespace.udecl]p10:
6581 // A using-declaration is a declaration and can therefore be used
6582 // repeatedly where (and only where) multiple declarations are
6583 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00006584 //
John McCall032092f2010-11-29 18:01:58 +00006585 // That's in non-member contexts.
6586 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00006587 return false;
6588
6589 NestedNameSpecifier *Qual
6590 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6591
6592 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
6593 NamedDecl *D = *I;
6594
6595 bool DTypename;
6596 NestedNameSpecifier *DQual;
6597 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
6598 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006599 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006600 } else if (UnresolvedUsingValueDecl *UD
6601 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
6602 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006603 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006604 } else if (UnresolvedUsingTypenameDecl *UD
6605 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
6606 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00006607 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00006608 } else continue;
6609
6610 // using decls differ if one says 'typename' and the other doesn't.
6611 // FIXME: non-dependent using decls?
6612 if (isTypeName != DTypename) continue;
6613
6614 // using decls differ if they name different scopes (but note that
6615 // template instantiation can cause this check to trigger when it
6616 // didn't before instantiation).
6617 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
6618 Context.getCanonicalNestedNameSpecifier(DQual))
6619 continue;
6620
6621 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00006622 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00006623 return true;
6624 }
6625
6626 return false;
6627}
6628
John McCall3969e302009-12-08 07:46:18 +00006629
John McCallb96ec562009-12-04 22:46:56 +00006630/// Checks that the given nested-name qualifier used in a using decl
6631/// in the current context is appropriately related to the current
6632/// scope. If an error is found, diagnoses it and returns true.
6633bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
6634 const CXXScopeSpec &SS,
6635 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00006636 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00006637
John McCall3969e302009-12-08 07:46:18 +00006638 if (!CurContext->isRecord()) {
6639 // C++03 [namespace.udecl]p3:
6640 // C++0x [namespace.udecl]p8:
6641 // A using-declaration for a class member shall be a member-declaration.
6642
6643 // If we weren't able to compute a valid scope, it must be a
6644 // dependent class scope.
6645 if (!NamedContext || NamedContext->isRecord()) {
6646 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
6647 << SS.getRange();
6648 return true;
6649 }
6650
6651 // Otherwise, everything is known to be fine.
6652 return false;
6653 }
6654
6655 // The current scope is a record.
6656
6657 // If the named context is dependent, we can't decide much.
6658 if (!NamedContext) {
6659 // FIXME: in C++0x, we can diagnose if we can prove that the
6660 // nested-name-specifier does not refer to a base class, which is
6661 // still possible in some cases.
6662
6663 // Otherwise we have to conservatively report that things might be
6664 // okay.
6665 return false;
6666 }
6667
6668 if (!NamedContext->isRecord()) {
6669 // Ideally this would point at the last name in the specifier,
6670 // but we don't have that level of source info.
6671 Diag(SS.getRange().getBegin(),
6672 diag::err_using_decl_nested_name_specifier_is_not_class)
6673 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
6674 return true;
6675 }
6676
Douglas Gregor7c842292010-12-21 07:41:49 +00006677 if (!NamedContext->isDependentContext() &&
6678 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
6679 return true;
6680
John McCall3969e302009-12-08 07:46:18 +00006681 if (getLangOptions().CPlusPlus0x) {
6682 // C++0x [namespace.udecl]p3:
6683 // In a using-declaration used as a member-declaration, the
6684 // nested-name-specifier shall name a base class of the class
6685 // being defined.
6686
6687 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
6688 cast<CXXRecordDecl>(NamedContext))) {
6689 if (CurContext == NamedContext) {
6690 Diag(NameLoc,
6691 diag::err_using_decl_nested_name_specifier_is_current_class)
6692 << SS.getRange();
6693 return true;
6694 }
6695
6696 Diag(SS.getRange().getBegin(),
6697 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6698 << (NestedNameSpecifier*) SS.getScopeRep()
6699 << cast<CXXRecordDecl>(CurContext)
6700 << SS.getRange();
6701 return true;
6702 }
6703
6704 return false;
6705 }
6706
6707 // C++03 [namespace.udecl]p4:
6708 // A using-declaration used as a member-declaration shall refer
6709 // to a member of a base class of the class being defined [etc.].
6710
6711 // Salient point: SS doesn't have to name a base class as long as
6712 // lookup only finds members from base classes. Therefore we can
6713 // diagnose here only if we can prove that that can't happen,
6714 // i.e. if the class hierarchies provably don't intersect.
6715
6716 // TODO: it would be nice if "definitely valid" results were cached
6717 // in the UsingDecl and UsingShadowDecl so that these checks didn't
6718 // need to be repeated.
6719
6720 struct UserData {
6721 llvm::DenseSet<const CXXRecordDecl*> Bases;
6722
6723 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
6724 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6725 Data->Bases.insert(Base);
6726 return true;
6727 }
6728
6729 bool hasDependentBases(const CXXRecordDecl *Class) {
6730 return !Class->forallBases(collect, this);
6731 }
6732
6733 /// Returns true if the base is dependent or is one of the
6734 /// accumulated base classes.
6735 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
6736 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
6737 return !Data->Bases.count(Base);
6738 }
6739
6740 bool mightShareBases(const CXXRecordDecl *Class) {
6741 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
6742 }
6743 };
6744
6745 UserData Data;
6746
6747 // Returns false if we find a dependent base.
6748 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
6749 return false;
6750
6751 // Returns false if the class has a dependent base or if it or one
6752 // of its bases is present in the base set of the current context.
6753 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
6754 return false;
6755
6756 Diag(SS.getRange().getBegin(),
6757 diag::err_using_decl_nested_name_specifier_is_not_base_class)
6758 << (NestedNameSpecifier*) SS.getScopeRep()
6759 << cast<CXXRecordDecl>(CurContext)
6760 << SS.getRange();
6761
6762 return true;
John McCallb96ec562009-12-04 22:46:56 +00006763}
6764
Richard Smithdda56e42011-04-15 14:24:37 +00006765Decl *Sema::ActOnAliasDeclaration(Scope *S,
6766 AccessSpecifier AS,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006767 MultiTemplateParamsArg TemplateParamLists,
Richard Smithdda56e42011-04-15 14:24:37 +00006768 SourceLocation UsingLoc,
6769 UnqualifiedId &Name,
6770 TypeResult Type) {
Richard Smith3f1b5d02011-05-05 21:57:07 +00006771 // Skip up to the relevant declaration scope.
6772 while (S->getFlags() & Scope::TemplateParamScope)
6773 S = S->getParent();
Richard Smithdda56e42011-04-15 14:24:37 +00006774 assert((S->getFlags() & Scope::DeclScope) &&
6775 "got alias-declaration outside of declaration scope");
6776
6777 if (Type.isInvalid())
6778 return 0;
6779
6780 bool Invalid = false;
6781 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
6782 TypeSourceInfo *TInfo = 0;
Nick Lewycky82e47802011-05-02 01:07:19 +00006783 GetTypeFromParser(Type.get(), &TInfo);
Richard Smithdda56e42011-04-15 14:24:37 +00006784
6785 if (DiagnoseClassNameShadow(CurContext, NameInfo))
6786 return 0;
6787
6788 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
Richard Smith3f1b5d02011-05-05 21:57:07 +00006789 UPPC_DeclarationType)) {
Richard Smithdda56e42011-04-15 14:24:37 +00006790 Invalid = true;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006791 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6792 TInfo->getTypeLoc().getBeginLoc());
6793 }
Richard Smithdda56e42011-04-15 14:24:37 +00006794
6795 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
6796 LookupName(Previous, S);
6797
6798 // Warn about shadowing the name of a template parameter.
6799 if (Previous.isSingleResult() &&
6800 Previous.getFoundDecl()->isTemplateParameter()) {
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00006801 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
Richard Smithdda56e42011-04-15 14:24:37 +00006802 Previous.clear();
6803 }
6804
6805 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
6806 "name in alias declaration must be an identifier");
6807 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
6808 Name.StartLocation,
6809 Name.Identifier, TInfo);
6810
6811 NewTD->setAccess(AS);
6812
6813 if (Invalid)
6814 NewTD->setInvalidDecl();
6815
Richard Smith3f1b5d02011-05-05 21:57:07 +00006816 CheckTypedefForVariablyModifiedType(S, NewTD);
6817 Invalid |= NewTD->isInvalidDecl();
6818
Richard Smithdda56e42011-04-15 14:24:37 +00006819 bool Redeclaration = false;
Richard Smith3f1b5d02011-05-05 21:57:07 +00006820
6821 NamedDecl *NewND;
6822 if (TemplateParamLists.size()) {
6823 TypeAliasTemplateDecl *OldDecl = 0;
6824 TemplateParameterList *OldTemplateParams = 0;
6825
6826 if (TemplateParamLists.size() != 1) {
6827 Diag(UsingLoc, diag::err_alias_template_extra_headers)
6828 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
6829 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
6830 }
6831 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
6832
6833 // Only consider previous declarations in the same scope.
6834 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
6835 /*ExplicitInstantiationOrSpecialization*/false);
6836 if (!Previous.empty()) {
6837 Redeclaration = true;
6838
6839 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
6840 if (!OldDecl && !Invalid) {
6841 Diag(UsingLoc, diag::err_redefinition_different_kind)
6842 << Name.Identifier;
6843
6844 NamedDecl *OldD = Previous.getRepresentativeDecl();
6845 if (OldD->getLocation().isValid())
6846 Diag(OldD->getLocation(), diag::note_previous_definition);
6847
6848 Invalid = true;
6849 }
6850
6851 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
6852 if (TemplateParameterListsAreEqual(TemplateParams,
6853 OldDecl->getTemplateParameters(),
6854 /*Complain=*/true,
6855 TPL_TemplateMatch))
6856 OldTemplateParams = OldDecl->getTemplateParameters();
6857 else
6858 Invalid = true;
6859
6860 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
6861 if (!Invalid &&
6862 !Context.hasSameType(OldTD->getUnderlyingType(),
6863 NewTD->getUnderlyingType())) {
6864 // FIXME: The C++0x standard does not clearly say this is ill-formed,
6865 // but we can't reasonably accept it.
6866 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
6867 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
6868 if (OldTD->getLocation().isValid())
6869 Diag(OldTD->getLocation(), diag::note_previous_definition);
6870 Invalid = true;
6871 }
6872 }
6873 }
6874
6875 // Merge any previous default template arguments into our parameters,
6876 // and check the parameter list.
6877 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
6878 TPC_TypeAliasTemplate))
6879 return 0;
6880
6881 TypeAliasTemplateDecl *NewDecl =
6882 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
6883 Name.Identifier, TemplateParams,
6884 NewTD);
6885
6886 NewDecl->setAccess(AS);
6887
6888 if (Invalid)
6889 NewDecl->setInvalidDecl();
6890 else if (OldDecl)
6891 NewDecl->setPreviousDeclaration(OldDecl);
6892
6893 NewND = NewDecl;
6894 } else {
6895 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
6896 NewND = NewTD;
6897 }
Richard Smithdda56e42011-04-15 14:24:37 +00006898
6899 if (!Redeclaration)
Richard Smith3f1b5d02011-05-05 21:57:07 +00006900 PushOnScopeChains(NewND, S);
Richard Smithdda56e42011-04-15 14:24:37 +00006901
Richard Smith3f1b5d02011-05-05 21:57:07 +00006902 return NewND;
Richard Smithdda56e42011-04-15 14:24:37 +00006903}
6904
John McCall48871652010-08-21 09:40:31 +00006905Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006906 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00006907 SourceLocation AliasLoc,
6908 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00006909 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00006910 SourceLocation IdentLoc,
6911 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00006912
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006913 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00006914 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
6915 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006916
Anders Carlssondca83c42009-03-28 06:23:46 +00006917 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00006918 NamedDecl *PrevDecl
6919 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
6920 ForRedeclaration);
6921 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
6922 PrevDecl = 0;
6923
6924 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006925 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00006926 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006927 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00006928 // FIXME: At some point, we'll want to create the (redundant)
6929 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00006930 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00006931 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00006932 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00006933 }
Mike Stump11289f42009-09-09 15:08:12 +00006934
Anders Carlssondca83c42009-03-28 06:23:46 +00006935 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
6936 diag::err_redefinition_different_kind;
6937 Diag(AliasLoc, DiagID) << Alias;
6938 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00006939 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00006940 }
6941
John McCall27b18f82009-11-17 02:14:36 +00006942 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00006943 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00006944
John McCall9f3059a2009-10-09 21:13:30 +00006945 if (R.empty()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00006946 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006947 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00006948 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00006949 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00006950 }
Mike Stump11289f42009-09-09 15:08:12 +00006951
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00006952 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00006953 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00006954 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00006955 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006956
John McCalld8d0d432010-02-16 06:53:13 +00006957 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00006958 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00006959}
6960
Douglas Gregora57478e2010-05-01 15:04:51 +00006961namespace {
6962 /// \brief Scoped object used to handle the state changes required in Sema
6963 /// to implicitly define the body of a C++ member function;
6964 class ImplicitlyDefinedFunctionScope {
6965 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00006966 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00006967
6968 public:
6969 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00006970 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00006971 {
Douglas Gregora57478e2010-05-01 15:04:51 +00006972 S.PushFunctionScope();
6973 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
6974 }
6975
6976 ~ImplicitlyDefinedFunctionScope() {
6977 S.PopExpressionEvaluationContext();
Eli Friedman71c80552012-01-05 03:35:19 +00006978 S.PopFunctionScopeInfo();
Douglas Gregora57478e2010-05-01 15:04:51 +00006979 }
6980 };
6981}
6982
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00006983Sema::ImplicitExceptionSpecification
6984Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregor6d880b12010-07-01 22:31:05 +00006985 // C++ [except.spec]p14:
6986 // An implicitly declared special member function (Clause 12) shall have an
6987 // exception-specification. [...]
6988 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00006989 if (ClassDecl->isInvalidDecl())
6990 return ExceptSpec;
Douglas Gregor6d880b12010-07-01 22:31:05 +00006991
Sebastian Redlfa453cf2011-03-12 11:50:43 +00006992 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00006993 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6994 BEnd = ClassDecl->bases_end();
6995 B != BEnd; ++B) {
6996 if (B->isVirtual()) // Handled below.
6997 continue;
6998
Douglas Gregor9672f922010-07-03 00:47:00 +00006999 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7000 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007001 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7002 // If this is a deleted function, add it anyway. This might be conformant
7003 // with the standard. This might not. I'm not sure. It might not matter.
7004 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007005 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007006 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007007 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007008
7009 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007010 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7011 BEnd = ClassDecl->vbases_end();
7012 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00007013 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
7014 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00007015 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
7016 // If this is a deleted function, add it anyway. This might be conformant
7017 // with the standard. This might not. I'm not sure. It might not matter.
7018 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007019 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007020 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007021 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007022
7023 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00007024 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7025 FEnd = ClassDecl->field_end();
7026 F != FEnd; ++F) {
Richard Smith938f40b2011-06-11 17:19:42 +00007027 if (F->hasInClassInitializer()) {
7028 if (Expr *E = F->getInClassInitializer())
7029 ExceptSpec.CalledExpr(E);
7030 else if (!F->isInvalidDecl())
7031 ExceptSpec.SetDelayed();
7032 } else if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00007033 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
Alexis Hunteef8ee02011-06-10 03:50:41 +00007034 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7035 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
7036 // If this is a deleted function, add it anyway. This might be conformant
7037 // with the standard. This might not. I'm not sure. It might not matter.
7038 // In particular, the problem is that this function never gets called. It
7039 // might just be ill-formed because this function attempts to refer to
7040 // a deleted function here.
7041 if (Constructor)
Douglas Gregor6d880b12010-07-01 22:31:05 +00007042 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00007043 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00007044 }
John McCalldb40c7f2010-12-14 08:05:40 +00007045
Alexis Hunt6d5b96c2011-05-10 00:49:42 +00007046 return ExceptSpec;
7047}
7048
7049CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
7050 CXXRecordDecl *ClassDecl) {
7051 // C++ [class.ctor]p5:
7052 // A default constructor for a class X is a constructor of class X
7053 // that can be called without an argument. If there is no
7054 // user-declared constructor for class X, a default constructor is
7055 // implicitly declared. An implicitly-declared default constructor
7056 // is an inline public member of its class.
7057 assert(!ClassDecl->hasUserDeclaredConstructor() &&
7058 "Should not build implicit default constructor!");
7059
7060 ImplicitExceptionSpecification Spec =
7061 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7062 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00007063
Douglas Gregor6d880b12010-07-01 22:31:05 +00007064 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007065 CanQualType ClassType
7066 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007067 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007068 DeclarationName Name
7069 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007070 DeclarationNameInfo NameInfo(Name, ClassLoc);
Richard Smithcc36f692011-12-22 02:22:31 +00007071 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
7072 Context, ClassDecl, ClassLoc, NameInfo,
7073 Context.getFunctionType(Context.VoidTy, 0, 0, EPI), /*TInfo=*/0,
7074 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
7075 /*isConstexpr=*/ClassDecl->defaultedDefaultConstructorIsConstexpr() &&
7076 getLangOptions().CPlusPlus0x);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007077 DefaultCon->setAccess(AS_public);
Alexis Huntf92197c2011-05-12 03:51:51 +00007078 DefaultCon->setDefaulted();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007079 DefaultCon->setImplicit();
Alexis Huntf479f1b2011-05-09 18:22:59 +00007080 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00007081
7082 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00007083 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
7084
Douglas Gregor0be31a22010-07-02 17:43:08 +00007085 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00007086 PushOnScopeChains(DefaultCon, S, false);
7087 ClassDecl->addDecl(DefaultCon);
Alexis Hunte77a28f2011-05-18 03:41:58 +00007088
Alexis Huntd6da8762011-10-10 06:18:57 +00007089 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007090 DefaultCon->setDeletedAsWritten();
Douglas Gregor9672f922010-07-03 00:47:00 +00007091
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00007092 return DefaultCon;
7093}
7094
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007095void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
7096 CXXConstructorDecl *Constructor) {
Alexis Huntf92197c2011-05-12 03:51:51 +00007097 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007098 !Constructor->doesThisDeclarationHaveABody() &&
7099 !Constructor->isDeleted()) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00007100 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00007101
Anders Carlsson423f5d82010-04-23 16:04:08 +00007102 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00007103 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00007104
Douglas Gregora57478e2010-05-01 15:04:51 +00007105 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007106 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00007107 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00007108 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007109 Diag(CurrentLocation, diag::note_member_synthesized_at)
Alexis Hunt80f00ff2011-05-10 19:08:14 +00007110 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00007111 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00007112 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00007113 }
Douglas Gregor73193272010-09-20 16:48:21 +00007114
7115 SourceLocation Loc = Constructor->getLocation();
7116 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
7117
7118 Constructor->setUsed();
7119 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007120
7121 if (ASTMutationListener *L = getASTMutationListener()) {
7122 L->CompletedImplicitDefinition(Constructor);
7123 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00007124}
7125
Richard Smith938f40b2011-06-11 17:19:42 +00007126/// Get any existing defaulted default constructor for the given class. Do not
7127/// implicitly define one if it does not exist.
7128static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
7129 CXXRecordDecl *D) {
7130 ASTContext &Context = Self.Context;
7131 QualType ClassType = Context.getTypeDeclType(D);
7132 DeclarationName ConstructorName
7133 = Context.DeclarationNames.getCXXConstructorName(
7134 Context.getCanonicalType(ClassType.getUnqualifiedType()));
7135
7136 DeclContext::lookup_const_iterator Con, ConEnd;
7137 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
7138 Con != ConEnd; ++Con) {
7139 // A function template cannot be defaulted.
7140 if (isa<FunctionTemplateDecl>(*Con))
7141 continue;
7142
7143 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
7144 if (Constructor->isDefaultConstructor())
7145 return Constructor->isDefaulted() ? Constructor : 0;
7146 }
7147 return 0;
7148}
7149
7150void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
7151 if (!D) return;
7152 AdjustDeclIfTemplate(D);
7153
7154 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
7155 CXXConstructorDecl *CtorDecl
7156 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
7157
7158 if (!CtorDecl) return;
7159
7160 // Compute the exception specification for the default constructor.
7161 const FunctionProtoType *CtorTy =
7162 CtorDecl->getType()->castAs<FunctionProtoType>();
7163 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
7164 ImplicitExceptionSpecification Spec =
7165 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
7166 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7167 assert(EPI.ExceptionSpecType != EST_Delayed);
7168
7169 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
7170 }
7171
7172 // If the default constructor is explicitly defaulted, checking the exception
7173 // specification is deferred until now.
7174 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
7175 !ClassDecl->isDependentType())
7176 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
7177}
7178
Sebastian Redl08905022011-02-05 19:23:19 +00007179void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
7180 // We start with an initial pass over the base classes to collect those that
7181 // inherit constructors from. If there are none, we can forgo all further
7182 // processing.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007183 typedef SmallVector<const RecordType *, 4> BasesVector;
Sebastian Redl08905022011-02-05 19:23:19 +00007184 BasesVector BasesToInheritFrom;
7185 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
7186 BaseE = ClassDecl->bases_end();
7187 BaseIt != BaseE; ++BaseIt) {
7188 if (BaseIt->getInheritConstructors()) {
7189 QualType Base = BaseIt->getType();
7190 if (Base->isDependentType()) {
7191 // If we inherit constructors from anything that is dependent, just
7192 // abort processing altogether. We'll get another chance for the
7193 // instantiations.
7194 return;
7195 }
7196 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
7197 }
7198 }
7199 if (BasesToInheritFrom.empty())
7200 return;
7201
7202 // Now collect the constructors that we already have in the current class.
7203 // Those take precedence over inherited constructors.
7204 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
7205 // unless there is a user-declared constructor with the same signature in
7206 // the class where the using-declaration appears.
7207 llvm::SmallSet<const Type *, 8> ExistingConstructors;
7208 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
7209 CtorE = ClassDecl->ctor_end();
7210 CtorIt != CtorE; ++CtorIt) {
7211 ExistingConstructors.insert(
7212 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
7213 }
7214
7215 Scope *S = getScopeForContext(ClassDecl);
7216 DeclarationName CreatedCtorName =
7217 Context.DeclarationNames.getCXXConstructorName(
7218 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
7219
7220 // Now comes the true work.
7221 // First, we keep a map from constructor types to the base that introduced
7222 // them. Needed for finding conflicting constructors. We also keep the
7223 // actually inserted declarations in there, for pretty diagnostics.
7224 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
7225 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
7226 ConstructorToSourceMap InheritedConstructors;
7227 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
7228 BaseE = BasesToInheritFrom.end();
7229 BaseIt != BaseE; ++BaseIt) {
7230 const RecordType *Base = *BaseIt;
7231 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
7232 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
7233 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
7234 CtorE = BaseDecl->ctor_end();
7235 CtorIt != CtorE; ++CtorIt) {
7236 // Find the using declaration for inheriting this base's constructors.
7237 DeclarationName Name =
7238 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
7239 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
7240 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
7241 SourceLocation UsingLoc = UD ? UD->getLocation() :
7242 ClassDecl->getLocation();
7243
7244 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
7245 // from the class X named in the using-declaration consists of actual
7246 // constructors and notional constructors that result from the
7247 // transformation of defaulted parameters as follows:
7248 // - all non-template default constructors of X, and
7249 // - for each non-template constructor of X that has at least one
7250 // parameter with a default argument, the set of constructors that
7251 // results from omitting any ellipsis parameter specification and
7252 // successively omitting parameters with a default argument from the
7253 // end of the parameter-type-list.
7254 CXXConstructorDecl *BaseCtor = *CtorIt;
7255 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
7256 const FunctionProtoType *BaseCtorType =
7257 BaseCtor->getType()->getAs<FunctionProtoType>();
7258
7259 for (unsigned params = BaseCtor->getMinRequiredArguments(),
7260 maxParams = BaseCtor->getNumParams();
7261 params <= maxParams; ++params) {
7262 // Skip default constructors. They're never inherited.
7263 if (params == 0)
7264 continue;
7265 // Skip copy and move constructors for the same reason.
7266 if (CanBeCopyOrMove && params == 1)
7267 continue;
7268
7269 // Build up a function type for this particular constructor.
7270 // FIXME: The working paper does not consider that the exception spec
7271 // for the inheriting constructor might be larger than that of the
Richard Smith938f40b2011-06-11 17:19:42 +00007272 // source. This code doesn't yet, either. When it does, this code will
7273 // need to be delayed until after exception specifications and in-class
7274 // member initializers are attached.
Sebastian Redl08905022011-02-05 19:23:19 +00007275 const Type *NewCtorType;
7276 if (params == maxParams)
7277 NewCtorType = BaseCtorType;
7278 else {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007279 SmallVector<QualType, 16> Args;
Sebastian Redl08905022011-02-05 19:23:19 +00007280 for (unsigned i = 0; i < params; ++i) {
7281 Args.push_back(BaseCtorType->getArgType(i));
7282 }
7283 FunctionProtoType::ExtProtoInfo ExtInfo =
7284 BaseCtorType->getExtProtoInfo();
7285 ExtInfo.Variadic = false;
7286 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
7287 Args.data(), params, ExtInfo)
7288 .getTypePtr();
7289 }
7290 const Type *CanonicalNewCtorType =
7291 Context.getCanonicalType(NewCtorType);
7292
7293 // Now that we have the type, first check if the class already has a
7294 // constructor with this signature.
7295 if (ExistingConstructors.count(CanonicalNewCtorType))
7296 continue;
7297
7298 // Then we check if we have already declared an inherited constructor
7299 // with this signature.
7300 std::pair<ConstructorToSourceMap::iterator, bool> result =
7301 InheritedConstructors.insert(std::make_pair(
7302 CanonicalNewCtorType,
7303 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
7304 if (!result.second) {
7305 // Already in the map. If it came from a different class, that's an
7306 // error. Not if it's from the same.
7307 CanQualType PreviousBase = result.first->second.first;
7308 if (CanonicalBase != PreviousBase) {
7309 const CXXConstructorDecl *PrevCtor = result.first->second.second;
7310 const CXXConstructorDecl *PrevBaseCtor =
7311 PrevCtor->getInheritedConstructor();
7312 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
7313
7314 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
7315 Diag(BaseCtor->getLocation(),
7316 diag::note_using_decl_constructor_conflict_current_ctor);
7317 Diag(PrevBaseCtor->getLocation(),
7318 diag::note_using_decl_constructor_conflict_previous_ctor);
7319 Diag(PrevCtor->getLocation(),
7320 diag::note_using_decl_constructor_conflict_previous_using);
7321 }
7322 continue;
7323 }
7324
7325 // OK, we're there, now add the constructor.
7326 // C++0x [class.inhctor]p8: [...] that would be performed by a
Richard Smitha77a0a62011-08-15 21:04:07 +00007327 // user-written inline constructor [...]
Sebastian Redl08905022011-02-05 19:23:19 +00007328 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
7329 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00007330 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
7331 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Richard Smitha77a0a62011-08-15 21:04:07 +00007332 /*ImplicitlyDeclared=*/true,
7333 // FIXME: Due to a defect in the standard, we treat inherited
7334 // constructors as constexpr even if that makes them ill-formed.
7335 /*Constexpr=*/BaseCtor->isConstexpr());
Sebastian Redl08905022011-02-05 19:23:19 +00007336 NewCtor->setAccess(BaseCtor->getAccess());
7337
7338 // Build up the parameter decls and add them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007339 SmallVector<ParmVarDecl *, 16> ParamDecls;
Sebastian Redl08905022011-02-05 19:23:19 +00007340 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00007341 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
7342 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00007343 /*IdentifierInfo=*/0,
7344 BaseCtorType->getArgType(i),
7345 /*TInfo=*/0, SC_None,
7346 SC_None, /*DefaultArg=*/0));
7347 }
David Blaikie9c70e042011-09-21 18:16:56 +00007348 NewCtor->setParams(ParamDecls);
Sebastian Redl08905022011-02-05 19:23:19 +00007349 NewCtor->setInheritedConstructor(BaseCtor);
7350
7351 PushOnScopeChains(NewCtor, S, false);
7352 ClassDecl->addDecl(NewCtor);
7353 result.first->second.second = NewCtor;
7354 }
7355 }
7356 }
7357}
7358
Alexis Huntf91729462011-05-12 22:46:25 +00007359Sema::ImplicitExceptionSpecification
7360Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00007361 // C++ [except.spec]p14:
7362 // An implicitly declared special member function (Clause 12) shall have
7363 // an exception-specification.
7364 ImplicitExceptionSpecification ExceptSpec(Context);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007365 if (ClassDecl->isInvalidDecl())
7366 return ExceptSpec;
7367
Douglas Gregorf1203042010-07-01 19:09:28 +00007368 // Direct base-class destructors.
7369 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
7370 BEnd = ClassDecl->bases_end();
7371 B != BEnd; ++B) {
7372 if (B->isVirtual()) // Handled below.
7373 continue;
7374
7375 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7376 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007377 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007378 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007379
Douglas Gregorf1203042010-07-01 19:09:28 +00007380 // Virtual base-class destructors.
7381 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
7382 BEnd = ClassDecl->vbases_end();
7383 B != BEnd; ++B) {
7384 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
7385 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007386 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007387 }
Sebastian Redl623ea822011-05-19 05:13:44 +00007388
Douglas Gregorf1203042010-07-01 19:09:28 +00007389 // Field destructors.
7390 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
7391 FEnd = ClassDecl->field_end();
7392 F != FEnd; ++F) {
7393 if (const RecordType *RecordTy
7394 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
7395 ExceptSpec.CalledDecl(
Sebastian Redl623ea822011-05-19 05:13:44 +00007396 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00007397 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007398
Alexis Huntf91729462011-05-12 22:46:25 +00007399 return ExceptSpec;
7400}
7401
7402CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
7403 // C++ [class.dtor]p2:
7404 // If a class has no user-declared destructor, a destructor is
7405 // declared implicitly. An implicitly-declared destructor is an
7406 // inline public member of its class.
7407
7408 ImplicitExceptionSpecification Spec =
Sebastian Redl623ea822011-05-19 05:13:44 +00007409 ComputeDefaultedDtorExceptionSpec(ClassDecl);
Alexis Huntf91729462011-05-12 22:46:25 +00007410 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7411
Douglas Gregor7454c562010-07-02 20:37:36 +00007412 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00007413 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007414
Douglas Gregorf1203042010-07-01 19:09:28 +00007415 CanQualType ClassType
7416 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00007417 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00007418 DeclarationName Name
7419 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007420 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00007421 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007422 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
7423 /*isInline=*/true,
7424 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00007425 Destructor->setAccess(AS_public);
Alexis Huntf91729462011-05-12 22:46:25 +00007426 Destructor->setDefaulted();
Douglas Gregorf1203042010-07-01 19:09:28 +00007427 Destructor->setImplicit();
7428 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00007429
7430 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00007431 ++ASTContext::NumImplicitDestructorsDeclared;
7432
7433 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00007434 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00007435 PushOnScopeChains(Destructor, S, false);
7436 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00007437
7438 // This could be uniqued if it ever proves significant.
7439 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Alexis Huntf91729462011-05-12 22:46:25 +00007440
7441 if (ShouldDeleteDestructor(Destructor))
7442 Destructor->setDeletedAsWritten();
Douglas Gregorf1203042010-07-01 19:09:28 +00007443
7444 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00007445
Douglas Gregorf1203042010-07-01 19:09:28 +00007446 return Destructor;
7447}
7448
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007449void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00007450 CXXDestructorDecl *Destructor) {
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007451 assert((Destructor->isDefaulted() &&
7452 !Destructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007453 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00007454 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007455 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007456
Douglas Gregor54818f02010-05-12 16:39:35 +00007457 if (Destructor->isInvalidDecl())
7458 return;
7459
Douglas Gregora57478e2010-05-01 15:04:51 +00007460 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00007461
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007462 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00007463 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
7464 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00007465
Douglas Gregor54818f02010-05-12 16:39:35 +00007466 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00007467 Diag(CurrentLocation, diag::note_member_synthesized_at)
7468 << CXXDestructor << Context.getTagDeclType(ClassDecl);
7469
7470 Destructor->setInvalidDecl();
7471 return;
7472 }
7473
Douglas Gregor73193272010-09-20 16:48:21 +00007474 SourceLocation Loc = Destructor->getLocation();
7475 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
Douglas Gregoreb4089a2011-09-22 20:32:43 +00007476 Destructor->setImplicitlyDefined(true);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007477 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007478 MarkVTableUsed(CurrentLocation, ClassDecl);
Sebastian Redlab238a72011-04-24 16:28:06 +00007479
7480 if (ASTMutationListener *L = getASTMutationListener()) {
7481 L->CompletedImplicitDefinition(Destructor);
7482 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00007483}
7484
Sebastian Redl623ea822011-05-19 05:13:44 +00007485void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
7486 CXXDestructorDecl *destructor) {
7487 // C++11 [class.dtor]p3:
7488 // A declaration of a destructor that does not have an exception-
7489 // specification is implicitly considered to have the same exception-
7490 // specification as an implicit declaration.
7491 const FunctionProtoType *dtorType = destructor->getType()->
7492 getAs<FunctionProtoType>();
7493 if (dtorType->hasExceptionSpec())
7494 return;
7495
7496 ImplicitExceptionSpecification exceptSpec =
7497 ComputeDefaultedDtorExceptionSpec(classDecl);
7498
Chandler Carruth9a797572011-09-20 04:55:26 +00007499 // Replace the destructor's type, building off the existing one. Fortunately,
7500 // the only thing of interest in the destructor type is its extended info.
7501 // The return and arguments are fixed.
7502 FunctionProtoType::ExtProtoInfo epi = dtorType->getExtProtoInfo();
Sebastian Redl623ea822011-05-19 05:13:44 +00007503 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
7504 epi.NumExceptions = exceptSpec.size();
7505 epi.Exceptions = exceptSpec.data();
7506 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
7507
7508 destructor->setType(ty);
7509
7510 // FIXME: If the destructor has a body that could throw, and the newly created
7511 // spec doesn't allow exceptions, we should emit a warning, because this
7512 // change in behavior can break conforming C++03 programs at runtime.
7513 // However, we don't have a body yet, so it needs to be done somewhere else.
7514}
7515
Sebastian Redl22653ba2011-08-30 19:58:05 +00007516/// \brief Builds a statement that copies/moves the given entity from \p From to
Douglas Gregorb139cd52010-05-01 20:49:11 +00007517/// \c To.
7518///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007519/// This routine is used to copy/move the members of a class with an
7520/// implicitly-declared copy/move assignment operator. When the entities being
Douglas Gregorb139cd52010-05-01 20:49:11 +00007521/// copied are arrays, this routine builds for loops to copy them.
7522///
7523/// \param S The Sema object used for type-checking.
7524///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007525/// \param Loc The location where the implicit copy/move is being generated.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007526///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007527/// \param T The type of the expressions being copied/moved. Both expressions
7528/// must have this type.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007529///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007530/// \param To The expression we are copying/moving to.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007531///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007532/// \param From The expression we are copying/moving from.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007533///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007534/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007535/// Otherwise, it's a non-static member subobject.
7536///
Sebastian Redl22653ba2011-08-30 19:58:05 +00007537/// \param Copying Whether we're copying or moving.
7538///
Douglas Gregorb139cd52010-05-01 20:49:11 +00007539/// \param Depth Internal parameter recording the depth of the recursion.
7540///
7541/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00007542static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00007543BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00007544 Expr *To, Expr *From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007545 bool CopyingBaseSubobject, bool Copying,
7546 unsigned Depth = 0) {
7547 // C++0x [class.copy]p28:
Douglas Gregorb139cd52010-05-01 20:49:11 +00007548 // Each subobject is assigned in the manner appropriate to its type:
7549 //
Sebastian Redl22653ba2011-08-30 19:58:05 +00007550 // - if the subobject is of class type, as if by a call to operator= with
7551 // the subobject as the object expression and the corresponding
7552 // subobject of x as a single function argument (as if by explicit
7553 // qualification; that is, ignoring any possible virtual overriding
7554 // functions in more derived classes);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007555 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
7556 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7557
7558 // Look for operator=.
7559 DeclarationName Name
7560 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
7561 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
7562 S.LookupQualifiedName(OpLookup, ClassDecl, false);
7563
Sebastian Redl22653ba2011-08-30 19:58:05 +00007564 // Filter out any result that isn't a copy/move-assignment operator.
Douglas Gregorb139cd52010-05-01 20:49:11 +00007565 LookupResult::Filter F = OpLookup.makeFilter();
7566 while (F.hasNext()) {
7567 NamedDecl *D = F.next();
7568 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
Sebastian Redl22653ba2011-08-30 19:58:05 +00007569 if (Copying ? Method->isCopyAssignmentOperator() :
7570 Method->isMoveAssignmentOperator())
Douglas Gregorb139cd52010-05-01 20:49:11 +00007571 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00007572
Douglas Gregorb139cd52010-05-01 20:49:11 +00007573 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00007574 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007575 F.done();
7576
Douglas Gregor40c92bb2010-05-04 15:20:55 +00007577 // Suppress the protected check (C++ [class.protected]) for each of the
7578 // assignment operators we found. This strange dance is required when
7579 // we're assigning via a base classes's copy-assignment operator. To
7580 // ensure that we're getting the right base class subobject (without
7581 // ambiguities), we need to cast "this" to that subobject type; to
7582 // ensure that we don't go through the virtual call mechanism, we need
7583 // to qualify the operator= name with the base class (see below). However,
7584 // this means that if the base class has a protected copy assignment
7585 // operator, the protected member access check will fail. So, we
7586 // rewrite "protected" access to "public" access in this case, since we
7587 // know by construction that we're calling from a derived class.
7588 if (CopyingBaseSubobject) {
7589 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
7590 L != LEnd; ++L) {
7591 if (L.getAccess() == AS_protected)
7592 L.setAccess(AS_public);
7593 }
7594 }
7595
Douglas Gregorb139cd52010-05-01 20:49:11 +00007596 // Create the nested-name-specifier that will be used to qualify the
7597 // reference to operator=; this is required to suppress the virtual
7598 // call mechanism.
7599 CXXScopeSpec SS;
Manuel Klimeke7167412012-02-06 21:51:39 +00007600 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
Douglas Gregor869ad452011-02-24 17:54:50 +00007601 SS.MakeTrivial(S.Context,
7602 NestedNameSpecifier::Create(S.Context, 0, false,
Manuel Klimeke7167412012-02-06 21:51:39 +00007603 CanonicalT),
Douglas Gregor869ad452011-02-24 17:54:50 +00007604 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007605
7606 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00007607 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00007608 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00007609 /*TemplateKWLoc=*/SourceLocation(),
7610 /*FirstQualifierInScope=*/0,
7611 OpLookup,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007612 /*TemplateArgs=*/0,
7613 /*SuppressQualifierCheck=*/true);
7614 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007615 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007616
7617 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00007618
John McCalldadc5752010-08-24 06:29:42 +00007619 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007620 OpEqualRef.takeAs<Expr>(),
7621 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007622 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007623 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007624
7625 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007626 }
John McCallab8c2732010-03-16 06:11:48 +00007627
Douglas Gregorb139cd52010-05-01 20:49:11 +00007628 // - if the subobject is of scalar type, the built-in assignment
7629 // operator is used.
7630 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
7631 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00007632 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007633 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007634 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007635
7636 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007637 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00007638
7639 // - if the subobject is an array, each element is assigned, in the
7640 // manner appropriate to the element type;
7641
7642 // Construct a loop over the array bounds, e.g.,
7643 //
7644 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
7645 //
7646 // that will copy each of the array elements.
7647 QualType SizeType = S.Context.getSizeType();
7648
7649 // Create the iteration variable.
7650 IdentifierInfo *IterationVarName = 0;
7651 {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00007652 SmallString<8> Str;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007653 llvm::raw_svector_ostream OS(Str);
7654 OS << "__i" << Depth;
7655 IterationVarName = &S.Context.Idents.get(OS.str());
7656 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00007657 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007658 IterationVarName, SizeType,
7659 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00007660 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007661
7662 // Initialize the iteration variable to zero.
7663 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007664 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00007665
7666 // Create a reference to the iteration variable; we'll use this several
7667 // times throughout.
7668 Expr *IterationVarRef
Eli Friedman844f9452012-01-23 02:35:22 +00007669 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007670 assert(IterationVarRef && "Reference to invented variable cannot fail!");
Eli Friedman844f9452012-01-23 02:35:22 +00007671 Expr *IterationVarRefRVal = S.DefaultLvalueConversion(IterationVarRef).take();
7672 assert(IterationVarRefRVal && "Conversion of invented variable cannot fail!");
7673
Douglas Gregorb139cd52010-05-01 20:49:11 +00007674 // Create the DeclStmt that holds the iteration variable.
7675 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
7676
7677 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00007678 llvm::APInt Upper
7679 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00007680 Expr *Comparison
Eli Friedman844f9452012-01-23 02:35:22 +00007681 = new (S.Context) BinaryOperator(IterationVarRefRVal,
John McCall7decc9e2010-11-18 06:31:45 +00007682 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
7683 BO_NE, S.Context.BoolTy,
7684 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007685
7686 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007687 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00007688 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
7689 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007690
7691 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00007692 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
Eli Friedman844f9452012-01-23 02:35:22 +00007693 IterationVarRefRVal,
7694 Loc));
John McCallb268a282010-08-23 23:25:46 +00007695 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
Eli Friedman844f9452012-01-23 02:35:22 +00007696 IterationVarRefRVal,
7697 Loc));
Sebastian Redl22653ba2011-08-30 19:58:05 +00007698 if (!Copying) // Cast to rvalue
7699 From = CastForMoving(S, From);
7700
7701 // Build the copy/move for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00007702 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
7703 To, From, CopyingBaseSubobject,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007704 Copying, Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00007705 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007706 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007707
7708 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00007709 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00007710 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00007711 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00007712 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00007713}
7714
Alexis Hunt119f3652011-05-14 05:23:20 +00007715std::pair<Sema::ImplicitExceptionSpecification, bool>
7716Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
7717 CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007718 if (ClassDecl->isInvalidDecl())
7719 return std::make_pair(ImplicitExceptionSpecification(Context), false);
7720
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007721 // C++ [class.copy]p10:
7722 // If the class definition does not explicitly declare a copy
7723 // assignment operator, one is declared implicitly.
7724 // The implicitly-defined copy assignment operator for a class X
7725 // will have the form
7726 //
7727 // X& X::operator=(const X&)
7728 //
7729 // if
7730 bool HasConstCopyAssignment = true;
7731
7732 // -- each direct base class B of X has a copy assignment operator
7733 // whose parameter is of type const B&, const volatile B& or B,
7734 // and
7735 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7736 BaseEnd = ClassDecl->bases_end();
7737 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007738 // We'll handle this below
7739 if (LangOpts.CPlusPlus0x && Base->isVirtual())
7740 continue;
7741
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007742 assert(!Base->getType()->isDependentType() &&
7743 "Cannot generate implicit members for class with dependent bases.");
Alexis Hunt491ec602011-06-21 23:42:56 +00007744 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7745 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7746 &HasConstCopyAssignment);
7747 }
7748
Richard Smith0bf8a4922011-10-18 20:49:44 +00007749 // In C++11, the above citation has "or virtual" added
Alexis Hunt491ec602011-06-21 23:42:56 +00007750 if (LangOpts.CPlusPlus0x) {
7751 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7752 BaseEnd = ClassDecl->vbases_end();
7753 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
7754 assert(!Base->getType()->isDependentType() &&
7755 "Cannot generate implicit members for class with dependent bases.");
7756 CXXRecordDecl *BaseClassDecl = Base->getType()->getAsCXXRecordDecl();
7757 LookupCopyingAssignment(BaseClassDecl, Qualifiers::Const, false, 0,
7758 &HasConstCopyAssignment);
7759 }
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007760 }
7761
7762 // -- for all the nonstatic data members of X that are of a class
7763 // type M (or array thereof), each such class type has a copy
7764 // assignment operator whose parameter is of type const M&,
7765 // const volatile M& or M.
7766 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7767 FieldEnd = ClassDecl->field_end();
7768 HasConstCopyAssignment && Field != FieldEnd;
7769 ++Field) {
7770 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007771 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7772 LookupCopyingAssignment(FieldClassDecl, Qualifiers::Const, false, 0,
7773 &HasConstCopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007774 }
7775 }
7776
7777 // Otherwise, the implicitly declared copy assignment operator will
7778 // have the form
7779 //
7780 // X& X::operator=(X&)
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007781
Douglas Gregor68e11362010-07-01 17:48:08 +00007782 // C++ [except.spec]p14:
7783 // An implicitly declared special member function (Clause 12) shall have an
7784 // exception-specification. [...]
Alexis Hunt491ec602011-06-21 23:42:56 +00007785
7786 // It is unspecified whether or not an implicit copy assignment operator
7787 // attempts to deduplicate calls to assignment operators of virtual bases are
7788 // made. As such, this exception specification is effectively unspecified.
7789 // Based on a similar decision made for constness in C++0x, we're erring on
7790 // the side of assuming such calls to be made regardless of whether they
7791 // actually happen.
Douglas Gregor68e11362010-07-01 17:48:08 +00007792 ImplicitExceptionSpecification ExceptSpec(Context);
Alexis Hunt491ec602011-06-21 23:42:56 +00007793 unsigned ArgQuals = HasConstCopyAssignment ? Qualifiers::Const : 0;
Douglas Gregor68e11362010-07-01 17:48:08 +00007794 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7795 BaseEnd = ClassDecl->bases_end();
7796 Base != BaseEnd; ++Base) {
Alexis Hunt491ec602011-06-21 23:42:56 +00007797 if (Base->isVirtual())
7798 continue;
7799
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007800 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00007801 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00007802 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7803 ArgQuals, false, 0))
Douglas Gregor68e11362010-07-01 17:48:08 +00007804 ExceptSpec.CalledDecl(CopyAssign);
7805 }
Alexis Hunt491ec602011-06-21 23:42:56 +00007806
7807 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7808 BaseEnd = ClassDecl->vbases_end();
7809 Base != BaseEnd; ++Base) {
7810 CXXRecordDecl *BaseClassDecl
7811 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7812 if (CXXMethodDecl *CopyAssign = LookupCopyingAssignment(BaseClassDecl,
7813 ArgQuals, false, 0))
7814 ExceptSpec.CalledDecl(CopyAssign);
7815 }
7816
Douglas Gregor68e11362010-07-01 17:48:08 +00007817 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7818 FieldEnd = ClassDecl->field_end();
7819 Field != FieldEnd;
7820 ++Field) {
7821 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt491ec602011-06-21 23:42:56 +00007822 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7823 if (CXXMethodDecl *CopyAssign =
7824 LookupCopyingAssignment(FieldClassDecl, ArgQuals, false, 0))
7825 ExceptSpec.CalledDecl(CopyAssign);
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00007826 }
Douglas Gregor68e11362010-07-01 17:48:08 +00007827 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00007828
Alexis Hunt119f3652011-05-14 05:23:20 +00007829 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
7830}
7831
7832CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
7833 // Note: The following rules are largely analoguous to the copy
7834 // constructor rules. Note that virtual bases are not taken into account
7835 // for determining the argument type of the operator. Note also that
7836 // operators taking an object instead of a reference are allowed.
7837
7838 ImplicitExceptionSpecification Spec(Context);
7839 bool Const;
7840 llvm::tie(Spec, Const) =
7841 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
7842
7843 QualType ArgType = Context.getTypeDeclType(ClassDecl);
7844 QualType RetType = Context.getLValueReferenceType(ArgType);
7845 if (Const)
7846 ArgType = ArgType.withConst();
7847 ArgType = Context.getLValueReferenceType(ArgType);
7848
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007849 // An implicitly-declared copy assignment operator is an inline public
7850 // member of its class.
Alexis Hunt119f3652011-05-14 05:23:20 +00007851 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007852 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00007853 SourceLocation ClassLoc = ClassDecl->getLocation();
7854 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007855 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00007856 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00007857 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007858 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00007859 /*StorageClassAsWritten=*/SC_None,
Richard Smitha77a0a62011-08-15 21:04:07 +00007860 /*isInline=*/true, /*isConstexpr=*/false,
Douglas Gregorf2f08062011-03-08 17:10:18 +00007861 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007862 CopyAssignment->setAccess(AS_public);
Alexis Huntb2f27802011-05-14 05:23:24 +00007863 CopyAssignment->setDefaulted();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007864 CopyAssignment->setImplicit();
7865 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007866
7867 // Add the parameter to the operator.
7868 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00007869 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007870 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00007871 SC_None,
7872 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00007873 CopyAssignment->setParams(FromParam);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007874
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007875 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007876 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
Alexis Huntb2f27802011-05-14 05:23:24 +00007877
Douglas Gregor0be31a22010-07-02 17:43:08 +00007878 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00007879 PushOnScopeChains(CopyAssignment, S, false);
7880 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007881
Nico Weber94e746d2012-01-23 03:19:29 +00007882 // C++0x [class.copy]p19:
7883 // .... If the class definition does not explicitly declare a copy
7884 // assignment operator, there is no user-declared move constructor, and
7885 // there is no user-declared move assignment operator, a copy assignment
7886 // operator is implicitly declared as defaulted.
7887 if ((ClassDecl->hasUserDeclaredMoveConstructor() &&
Nico Weber323076f2012-01-23 04:01:33 +00007888 !getLangOptions().MicrosoftMode) ||
7889 ClassDecl->hasUserDeclaredMoveAssignment() ||
Alexis Huntd74c85f2011-06-22 01:05:13 +00007890 ShouldDeleteCopyAssignmentOperator(CopyAssignment))
Alexis Hunte77a28f2011-05-18 03:41:58 +00007891 CopyAssignment->setDeletedAsWritten();
7892
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00007893 AddOverriddenMethods(ClassDecl, CopyAssignment);
7894 return CopyAssignment;
7895}
7896
Douglas Gregorb139cd52010-05-01 20:49:11 +00007897void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
7898 CXXMethodDecl *CopyAssignOperator) {
Alexis Huntb2f27802011-05-14 05:23:24 +00007899 assert((CopyAssignOperator->isDefaulted() &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007900 CopyAssignOperator->isOverloadedOperator() &&
7901 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00007902 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00007903 "DefineImplicitCopyAssignment called for wrong function");
7904
7905 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
7906
7907 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
7908 CopyAssignOperator->setInvalidDecl();
7909 return;
7910 }
7911
7912 CopyAssignOperator->setUsed();
7913
7914 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00007915 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007916
7917 // C++0x [class.copy]p30:
7918 // The implicitly-defined or explicitly-defaulted copy assignment operator
7919 // for a non-union class X performs memberwise copy assignment of its
7920 // subobjects. The direct base classes of X are assigned first, in the
7921 // order of their declaration in the base-specifier-list, and then the
7922 // immediate non-static data members of X are assigned, in the order in
7923 // which they were declared in the class definition.
7924
7925 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00007926 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007927
7928 // The parameter for the "other" object, which we are copying from.
7929 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
7930 Qualifiers OtherQuals = Other->getType().getQualifiers();
7931 QualType OtherRefType = Other->getType();
7932 if (const LValueReferenceType *OtherRef
7933 = OtherRefType->getAs<LValueReferenceType>()) {
7934 OtherRefType = OtherRef->getPointeeType();
7935 OtherQuals = OtherRefType.getQualifiers();
7936 }
7937
7938 // Our location for everything implicitly-generated.
7939 SourceLocation Loc = CopyAssignOperator->getLocation();
7940
7941 // Construct a reference to the "other" object. We'll be using this
7942 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00007943 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007944 assert(OtherRef && "Reference to parameter cannot fail!");
7945
7946 // Construct the "this" pointer. We'll be using this throughout the generated
7947 // ASTs.
7948 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
7949 assert(This && "Reference to this cannot fail!");
7950
7951 // Assign base classes.
7952 bool Invalid = false;
7953 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7954 E = ClassDecl->bases_end(); Base != E; ++Base) {
7955 // Form the assignment:
7956 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
7957 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00007958 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00007959 Invalid = true;
7960 continue;
7961 }
7962
John McCallcf142162010-08-07 06:22:56 +00007963 CXXCastPath BasePath;
7964 BasePath.push_back(Base);
7965
Douglas Gregorb139cd52010-05-01 20:49:11 +00007966 // Construct the "from" expression, which is an implicit cast to the
7967 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00007968 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00007969 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
7970 CK_UncheckedDerivedToBase,
7971 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00007972
7973 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00007974 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007975
7976 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00007977 To = ImpCastExprToType(To.take(),
7978 Context.getCVRQualifiedType(BaseType,
7979 CopyAssignOperator->getTypeQualifiers()),
7980 CK_UncheckedDerivedToBase,
7981 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007982
7983 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00007984 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00007985 To.get(), From,
Sebastian Redl22653ba2011-08-30 19:58:05 +00007986 /*CopyingBaseSubobject=*/true,
7987 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00007988 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00007989 Diag(CurrentLocation, diag::note_member_synthesized_at)
7990 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7991 CopyAssignOperator->setInvalidDecl();
7992 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00007993 }
7994
7995 // Success! Record the copy.
7996 Statements.push_back(Copy.takeAs<Expr>());
7997 }
7998
7999 // \brief Reference to the __builtin_memcpy function.
8000 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00008001 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008002 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008003
8004 // Assign non-static members.
8005 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8006 FieldEnd = ClassDecl->field_end();
8007 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00008008 if (Field->isUnnamedBitfield())
8009 continue;
8010
Douglas Gregorb139cd52010-05-01 20:49:11 +00008011 // Check for members of reference type; we can't copy those.
8012 if (Field->getType()->isReferenceType()) {
8013 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8014 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8015 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008016 Diag(CurrentLocation, diag::note_member_synthesized_at)
8017 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008018 Invalid = true;
8019 continue;
8020 }
8021
8022 // Check for members of const-qualified, non-class type.
8023 QualType BaseType = Context.getBaseElementType(Field->getType());
8024 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8025 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8026 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8027 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008028 Diag(CurrentLocation, diag::note_member_synthesized_at)
8029 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008030 Invalid = true;
8031 continue;
8032 }
John McCall1b1a1db2011-06-17 00:18:42 +00008033
8034 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00008035 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8036 continue;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008037
8038 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00008039 if (FieldType->isIncompleteArrayType()) {
8040 assert(ClassDecl->hasFlexibleArrayMember() &&
8041 "Incomplete array type is not valid");
8042 continue;
8043 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008044
8045 // Build references to the field in the object we're copying from and to.
8046 CXXScopeSpec SS; // Intentionally empty
8047 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8048 LookupMemberName);
8049 MemberLookup.addDecl(*Field);
8050 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00008051 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00008052 Loc, /*IsArrow=*/false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008053 SS, SourceLocation(), 0,
8054 MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00008055 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00008056 Loc, /*IsArrow=*/true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008057 SS, SourceLocation(), 0,
8058 MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008059 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8060 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8061
8062 // If the field should be copied with __builtin_memcpy rather than via
8063 // explicit assignments, do so. This optimization only applies for arrays
8064 // of scalars and arrays of class type with trivial copy-assignment
8065 // operators.
Fariborz Jahanianc1a151b2011-08-09 00:26:11 +00008066 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
Sebastian Redl22653ba2011-08-30 19:58:05 +00008067 && BaseType.hasTrivialAssignment(Context, /*Copying=*/true)) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00008068 // Compute the size of the memory buffer to be copied.
8069 QualType SizeType = Context.getSizeType();
8070 llvm::APInt Size(Context.getTypeSize(SizeType),
8071 Context.getTypeSizeInChars(BaseType).getQuantity());
8072 for (const ConstantArrayType *Array
8073 = Context.getAsConstantArrayType(FieldType);
8074 Array;
8075 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00008076 llvm::APInt ArraySize
8077 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00008078 Size *= ArraySize;
8079 }
8080
8081 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00008082 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
8083 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008084
8085 bool NeedsCollectableMemCpy =
8086 (BaseType->isRecordType() &&
8087 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8088
8089 if (NeedsCollectableMemCpy) {
8090 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00008091 // Create a reference to the __builtin_objc_memmove_collectable function.
8092 LookupResult R(*this,
8093 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008094 Loc, LookupOrdinaryName);
8095 LookupName(R, TUScope, true);
8096
8097 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8098 if (!CollectableMemCpy) {
8099 // Something went horribly wrong earlier, and we will have
8100 // complained about it.
8101 Invalid = true;
8102 continue;
8103 }
8104
8105 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8106 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008107 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008108 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8109 }
8110 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008111 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00008112 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00008113 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8114 LookupOrdinaryName);
8115 LookupName(R, TUScope, true);
8116
8117 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8118 if (!BuiltinMemCpy) {
8119 // Something went horribly wrong earlier, and we will have complained
8120 // about it.
8121 Invalid = true;
8122 continue;
8123 }
8124
8125 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8126 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008127 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00008128 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8129 }
8130
John McCall37ad5512010-08-23 06:44:23 +00008131 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008132 CallArgs.push_back(To.takeAs<Expr>());
8133 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008134 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00008135 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008136 if (NeedsCollectableMemCpy)
8137 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008138 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008139 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008140 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008141 else
8142 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00008143 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008144 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008145 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00008146
Douglas Gregorb139cd52010-05-01 20:49:11 +00008147 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8148 Statements.push_back(Call.takeAs<Expr>());
8149 continue;
8150 }
8151
8152 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00008153 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Sebastian Redl22653ba2011-08-30 19:58:05 +00008154 To.get(), From.get(),
8155 /*CopyingBaseSubobject=*/false,
8156 /*Copying=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008157 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00008158 Diag(CurrentLocation, diag::note_member_synthesized_at)
8159 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8160 CopyAssignOperator->setInvalidDecl();
8161 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00008162 }
8163
8164 // Success! Record the copy.
8165 Statements.push_back(Copy.takeAs<Stmt>());
8166 }
8167
8168 if (!Invalid) {
8169 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00008170 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00008171
John McCalldadc5752010-08-24 06:29:42 +00008172 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00008173 if (Return.isInvalid())
8174 Invalid = true;
8175 else {
8176 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00008177
8178 if (Trap.hasErrorOccurred()) {
8179 Diag(CurrentLocation, diag::note_member_synthesized_at)
8180 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
8181 Invalid = true;
8182 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00008183 }
8184 }
8185
8186 if (Invalid) {
8187 CopyAssignOperator->setInvalidDecl();
8188 return;
8189 }
8190
John McCalldadc5752010-08-24 06:29:42 +00008191 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00008192 /*isStmtExpr=*/false);
8193 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8194 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Sebastian Redlab238a72011-04-24 16:28:06 +00008195
8196 if (ASTMutationListener *L = getASTMutationListener()) {
8197 L->CompletedImplicitDefinition(CopyAssignOperator);
8198 }
Fariborz Jahanian41f79272009-06-25 21:45:19 +00008199}
8200
Sebastian Redl22653ba2011-08-30 19:58:05 +00008201Sema::ImplicitExceptionSpecification
8202Sema::ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl) {
8203 ImplicitExceptionSpecification ExceptSpec(Context);
8204
8205 if (ClassDecl->isInvalidDecl())
8206 return ExceptSpec;
8207
8208 // C++0x [except.spec]p14:
8209 // An implicitly declared special member function (Clause 12) shall have an
8210 // exception-specification. [...]
8211
8212 // It is unspecified whether or not an implicit move assignment operator
8213 // attempts to deduplicate calls to assignment operators of virtual bases are
8214 // made. As such, this exception specification is effectively unspecified.
8215 // Based on a similar decision made for constness in C++0x, we're erring on
8216 // the side of assuming such calls to be made regardless of whether they
8217 // actually happen.
8218 // Note that a move constructor is not implicitly declared when there are
8219 // virtual bases, but it can still be user-declared and explicitly defaulted.
8220 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8221 BaseEnd = ClassDecl->bases_end();
8222 Base != BaseEnd; ++Base) {
8223 if (Base->isVirtual())
8224 continue;
8225
8226 CXXRecordDecl *BaseClassDecl
8227 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8228 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8229 false, 0))
8230 ExceptSpec.CalledDecl(MoveAssign);
8231 }
8232
8233 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8234 BaseEnd = ClassDecl->vbases_end();
8235 Base != BaseEnd; ++Base) {
8236 CXXRecordDecl *BaseClassDecl
8237 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
8238 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(BaseClassDecl,
8239 false, 0))
8240 ExceptSpec.CalledDecl(MoveAssign);
8241 }
8242
8243 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8244 FieldEnd = ClassDecl->field_end();
8245 Field != FieldEnd;
8246 ++Field) {
8247 QualType FieldType = Context.getBaseElementType((*Field)->getType());
8248 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8249 if (CXXMethodDecl *MoveAssign = LookupMovingAssignment(FieldClassDecl,
8250 false, 0))
8251 ExceptSpec.CalledDecl(MoveAssign);
8252 }
8253 }
8254
8255 return ExceptSpec;
8256}
8257
8258CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
8259 // Note: The following rules are largely analoguous to the move
8260 // constructor rules.
8261
8262 ImplicitExceptionSpecification Spec(
8263 ComputeDefaultedMoveAssignmentExceptionSpec(ClassDecl));
8264
8265 QualType ArgType = Context.getTypeDeclType(ClassDecl);
8266 QualType RetType = Context.getLValueReferenceType(ArgType);
8267 ArgType = Context.getRValueReferenceType(ArgType);
8268
8269 // An implicitly-declared move assignment operator is an inline public
8270 // member of its class.
8271 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8272 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
8273 SourceLocation ClassLoc = ClassDecl->getLocation();
8274 DeclarationNameInfo NameInfo(Name, ClassLoc);
8275 CXXMethodDecl *MoveAssignment
8276 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
8277 Context.getFunctionType(RetType, &ArgType, 1, EPI),
8278 /*TInfo=*/0, /*isStatic=*/false,
8279 /*StorageClassAsWritten=*/SC_None,
8280 /*isInline=*/true,
8281 /*isConstexpr=*/false,
8282 SourceLocation());
8283 MoveAssignment->setAccess(AS_public);
8284 MoveAssignment->setDefaulted();
8285 MoveAssignment->setImplicit();
8286 MoveAssignment->setTrivial(ClassDecl->hasTrivialMoveAssignment());
8287
8288 // Add the parameter to the operator.
8289 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
8290 ClassLoc, ClassLoc, /*Id=*/0,
8291 ArgType, /*TInfo=*/0,
8292 SC_None,
8293 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008294 MoveAssignment->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008295
8296 // Note that we have added this copy-assignment operator.
8297 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
8298
8299 // C++0x [class.copy]p9:
8300 // If the definition of a class X does not explicitly declare a move
8301 // assignment operator, one will be implicitly declared as defaulted if and
8302 // only if:
8303 // [...]
8304 // - the move assignment operator would not be implicitly defined as
8305 // deleted.
8306 if (ShouldDeleteMoveAssignmentOperator(MoveAssignment)) {
8307 // Cache this result so that we don't try to generate this over and over
8308 // on every lookup, leaking memory and wasting time.
8309 ClassDecl->setFailedImplicitMoveAssignment();
8310 return 0;
8311 }
8312
8313 if (Scope *S = getScopeForContext(ClassDecl))
8314 PushOnScopeChains(MoveAssignment, S, false);
8315 ClassDecl->addDecl(MoveAssignment);
8316
8317 AddOverriddenMethods(ClassDecl, MoveAssignment);
8318 return MoveAssignment;
8319}
8320
8321void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
8322 CXXMethodDecl *MoveAssignOperator) {
8323 assert((MoveAssignOperator->isDefaulted() &&
8324 MoveAssignOperator->isOverloadedOperator() &&
8325 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
8326 !MoveAssignOperator->doesThisDeclarationHaveABody()) &&
8327 "DefineImplicitMoveAssignment called for wrong function");
8328
8329 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
8330
8331 if (ClassDecl->isInvalidDecl() || MoveAssignOperator->isInvalidDecl()) {
8332 MoveAssignOperator->setInvalidDecl();
8333 return;
8334 }
8335
8336 MoveAssignOperator->setUsed();
8337
8338 ImplicitlyDefinedFunctionScope Scope(*this, MoveAssignOperator);
8339 DiagnosticErrorTrap Trap(Diags);
8340
8341 // C++0x [class.copy]p28:
8342 // The implicitly-defined or move assignment operator for a non-union class
8343 // X performs memberwise move assignment of its subobjects. The direct base
8344 // classes of X are assigned first, in the order of their declaration in the
8345 // base-specifier-list, and then the immediate non-static data members of X
8346 // are assigned, in the order in which they were declared in the class
8347 // definition.
8348
8349 // The statements that form the synthesized function body.
8350 ASTOwningVector<Stmt*> Statements(*this);
8351
8352 // The parameter for the "other" object, which we are move from.
8353 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
8354 QualType OtherRefType = Other->getType()->
8355 getAs<RValueReferenceType>()->getPointeeType();
8356 assert(OtherRefType.getQualifiers() == 0 &&
8357 "Bad argument type of defaulted move assignment");
8358
8359 // Our location for everything implicitly-generated.
8360 SourceLocation Loc = MoveAssignOperator->getLocation();
8361
8362 // Construct a reference to the "other" object. We'll be using this
8363 // throughout the generated ASTs.
8364 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
8365 assert(OtherRef && "Reference to parameter cannot fail!");
8366 // Cast to rvalue.
8367 OtherRef = CastForMoving(*this, OtherRef);
8368
8369 // Construct the "this" pointer. We'll be using this throughout the generated
8370 // ASTs.
8371 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
8372 assert(This && "Reference to this cannot fail!");
8373
8374 // Assign base classes.
8375 bool Invalid = false;
8376 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8377 E = ClassDecl->bases_end(); Base != E; ++Base) {
8378 // Form the assignment:
8379 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
8380 QualType BaseType = Base->getType().getUnqualifiedType();
8381 if (!BaseType->isRecordType()) {
8382 Invalid = true;
8383 continue;
8384 }
8385
8386 CXXCastPath BasePath;
8387 BasePath.push_back(Base);
8388
8389 // Construct the "from" expression, which is an implicit cast to the
8390 // appropriately-qualified base type.
8391 Expr *From = OtherRef;
8392 From = ImpCastExprToType(From, BaseType, CK_UncheckedDerivedToBase,
Douglas Gregor146b8e92011-09-06 16:26:56 +00008393 VK_XValue, &BasePath).take();
Sebastian Redl22653ba2011-08-30 19:58:05 +00008394
8395 // Dereference "this".
8396 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8397
8398 // Implicitly cast "this" to the appropriately-qualified base type.
8399 To = ImpCastExprToType(To.take(),
8400 Context.getCVRQualifiedType(BaseType,
8401 MoveAssignOperator->getTypeQualifiers()),
8402 CK_UncheckedDerivedToBase,
8403 VK_LValue, &BasePath);
8404
8405 // Build the move.
8406 StmtResult Move = BuildSingleCopyAssign(*this, Loc, BaseType,
8407 To.get(), From,
8408 /*CopyingBaseSubobject=*/true,
8409 /*Copying=*/false);
8410 if (Move.isInvalid()) {
8411 Diag(CurrentLocation, diag::note_member_synthesized_at)
8412 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8413 MoveAssignOperator->setInvalidDecl();
8414 return;
8415 }
8416
8417 // Success! Record the move.
8418 Statements.push_back(Move.takeAs<Expr>());
8419 }
8420
8421 // \brief Reference to the __builtin_memcpy function.
8422 Expr *BuiltinMemCpyRef = 0;
8423 // \brief Reference to the __builtin_objc_memmove_collectable function.
8424 Expr *CollectableMemCpyRef = 0;
8425
8426 // Assign non-static members.
8427 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8428 FieldEnd = ClassDecl->field_end();
8429 Field != FieldEnd; ++Field) {
Douglas Gregor556e5862011-10-10 17:22:13 +00008430 if (Field->isUnnamedBitfield())
8431 continue;
8432
Sebastian Redl22653ba2011-08-30 19:58:05 +00008433 // Check for members of reference type; we can't move those.
8434 if (Field->getType()->isReferenceType()) {
8435 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8436 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
8437 Diag(Field->getLocation(), diag::note_declared_at);
8438 Diag(CurrentLocation, diag::note_member_synthesized_at)
8439 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8440 Invalid = true;
8441 continue;
8442 }
8443
8444 // Check for members of const-qualified, non-class type.
8445 QualType BaseType = Context.getBaseElementType(Field->getType());
8446 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
8447 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
8448 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
8449 Diag(Field->getLocation(), diag::note_declared_at);
8450 Diag(CurrentLocation, diag::note_member_synthesized_at)
8451 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8452 Invalid = true;
8453 continue;
8454 }
8455
8456 // Suppress assigning zero-width bitfields.
Richard Smithcaf33902011-10-10 18:28:20 +00008457 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
8458 continue;
Sebastian Redl22653ba2011-08-30 19:58:05 +00008459
8460 QualType FieldType = Field->getType().getNonReferenceType();
8461 if (FieldType->isIncompleteArrayType()) {
8462 assert(ClassDecl->hasFlexibleArrayMember() &&
8463 "Incomplete array type is not valid");
8464 continue;
8465 }
8466
8467 // Build references to the field in the object we're copying from and to.
8468 CXXScopeSpec SS; // Intentionally empty
8469 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
8470 LookupMemberName);
8471 MemberLookup.addDecl(*Field);
8472 MemberLookup.resolveKind();
8473 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
8474 Loc, /*IsArrow=*/false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008475 SS, SourceLocation(), 0,
8476 MemberLookup, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008477 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
8478 Loc, /*IsArrow=*/true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00008479 SS, SourceLocation(), 0,
8480 MemberLookup, 0);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008481 assert(!From.isInvalid() && "Implicit field reference cannot fail");
8482 assert(!To.isInvalid() && "Implicit field reference cannot fail");
8483
8484 assert(!From.get()->isLValue() && // could be xvalue or prvalue
8485 "Member reference with rvalue base must be rvalue except for reference "
8486 "members, which aren't allowed for move assignment.");
8487
8488 // If the field should be copied with __builtin_memcpy rather than via
8489 // explicit assignments, do so. This optimization only applies for arrays
8490 // of scalars and arrays of class type with trivial move-assignment
8491 // operators.
8492 if (FieldType->isArrayType() && !FieldType.isVolatileQualified()
8493 && BaseType.hasTrivialAssignment(Context, /*Copying=*/false)) {
8494 // Compute the size of the memory buffer to be copied.
8495 QualType SizeType = Context.getSizeType();
8496 llvm::APInt Size(Context.getTypeSize(SizeType),
8497 Context.getTypeSizeInChars(BaseType).getQuantity());
8498 for (const ConstantArrayType *Array
8499 = Context.getAsConstantArrayType(FieldType);
8500 Array;
8501 Array = Context.getAsConstantArrayType(Array->getElementType())) {
8502 llvm::APInt ArraySize
8503 = Array->getSize().zextOrTrunc(Size.getBitWidth());
8504 Size *= ArraySize;
8505 }
8506
Douglas Gregor528499b2011-09-01 02:09:07 +00008507 // Take the address of the field references for "from" and "to". We
8508 // directly construct UnaryOperators here because semantic analysis
8509 // does not permit us to take the address of an xvalue.
8510 From = new (Context) UnaryOperator(From.get(), UO_AddrOf,
8511 Context.getPointerType(From.get()->getType()),
8512 VK_RValue, OK_Ordinary, Loc);
8513 To = new (Context) UnaryOperator(To.get(), UO_AddrOf,
8514 Context.getPointerType(To.get()->getType()),
8515 VK_RValue, OK_Ordinary, Loc);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008516
8517 bool NeedsCollectableMemCpy =
8518 (BaseType->isRecordType() &&
8519 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
8520
8521 if (NeedsCollectableMemCpy) {
8522 if (!CollectableMemCpyRef) {
8523 // Create a reference to the __builtin_objc_memmove_collectable function.
8524 LookupResult R(*this,
8525 &Context.Idents.get("__builtin_objc_memmove_collectable"),
8526 Loc, LookupOrdinaryName);
8527 LookupName(R, TUScope, true);
8528
8529 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
8530 if (!CollectableMemCpy) {
8531 // Something went horribly wrong earlier, and we will have
8532 // complained about it.
8533 Invalid = true;
8534 continue;
8535 }
8536
8537 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
8538 CollectableMemCpy->getType(),
8539 VK_LValue, Loc, 0).take();
8540 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
8541 }
8542 }
8543 // Create a reference to the __builtin_memcpy builtin function.
8544 else if (!BuiltinMemCpyRef) {
8545 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
8546 LookupOrdinaryName);
8547 LookupName(R, TUScope, true);
8548
8549 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
8550 if (!BuiltinMemCpy) {
8551 // Something went horribly wrong earlier, and we will have complained
8552 // about it.
8553 Invalid = true;
8554 continue;
8555 }
8556
8557 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
8558 BuiltinMemCpy->getType(),
8559 VK_LValue, Loc, 0).take();
8560 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
8561 }
8562
8563 ASTOwningVector<Expr*> CallArgs(*this);
8564 CallArgs.push_back(To.takeAs<Expr>());
8565 CallArgs.push_back(From.takeAs<Expr>());
8566 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
8567 ExprResult Call = ExprError();
8568 if (NeedsCollectableMemCpy)
8569 Call = ActOnCallExpr(/*Scope=*/0,
8570 CollectableMemCpyRef,
8571 Loc, move_arg(CallArgs),
8572 Loc);
8573 else
8574 Call = ActOnCallExpr(/*Scope=*/0,
8575 BuiltinMemCpyRef,
8576 Loc, move_arg(CallArgs),
8577 Loc);
8578
8579 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
8580 Statements.push_back(Call.takeAs<Expr>());
8581 continue;
8582 }
8583
8584 // Build the move of this field.
8585 StmtResult Move = BuildSingleCopyAssign(*this, Loc, FieldType,
8586 To.get(), From.get(),
8587 /*CopyingBaseSubobject=*/false,
8588 /*Copying=*/false);
8589 if (Move.isInvalid()) {
8590 Diag(CurrentLocation, diag::note_member_synthesized_at)
8591 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8592 MoveAssignOperator->setInvalidDecl();
8593 return;
8594 }
8595
8596 // Success! Record the copy.
8597 Statements.push_back(Move.takeAs<Stmt>());
8598 }
8599
8600 if (!Invalid) {
8601 // Add a "return *this;"
8602 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
8603
8604 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
8605 if (Return.isInvalid())
8606 Invalid = true;
8607 else {
8608 Statements.push_back(Return.takeAs<Stmt>());
8609
8610 if (Trap.hasErrorOccurred()) {
8611 Diag(CurrentLocation, diag::note_member_synthesized_at)
8612 << CXXMoveAssignment << Context.getTagDeclType(ClassDecl);
8613 Invalid = true;
8614 }
8615 }
8616 }
8617
8618 if (Invalid) {
8619 MoveAssignOperator->setInvalidDecl();
8620 return;
8621 }
8622
8623 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
8624 /*isStmtExpr=*/false);
8625 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
8626 MoveAssignOperator->setBody(Body.takeAs<Stmt>());
8627
8628 if (ASTMutationListener *L = getASTMutationListener()) {
8629 L->CompletedImplicitDefinition(MoveAssignOperator);
8630 }
8631}
8632
Alexis Hunt913820d2011-05-13 06:10:58 +00008633std::pair<Sema::ImplicitExceptionSpecification, bool>
8634Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
Abramo Bagnaradd8fc042011-07-11 08:52:40 +00008635 if (ClassDecl->isInvalidDecl())
8636 return std::make_pair(ImplicitExceptionSpecification(Context), false);
8637
Douglas Gregor54be3392010-07-01 17:57:27 +00008638 // C++ [class.copy]p5:
8639 // The implicitly-declared copy constructor for a class X will
8640 // have the form
8641 //
8642 // X::X(const X&)
8643 //
8644 // if
Alexis Hunt899bd442011-06-10 04:44:37 +00008645 // FIXME: It ought to be possible to store this on the record.
Douglas Gregor54be3392010-07-01 17:57:27 +00008646 bool HasConstCopyConstructor = true;
8647
8648 // -- each direct or virtual base class B of X has a copy
8649 // constructor whose first parameter is of type const B& or
8650 // const volatile B&, and
8651 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8652 BaseEnd = ClassDecl->bases_end();
8653 HasConstCopyConstructor && Base != BaseEnd;
8654 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008655 // Virtual bases are handled below.
8656 if (Base->isVirtual())
8657 continue;
8658
Douglas Gregora6d69502010-07-02 23:41:54 +00008659 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00008660 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008661 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8662 &HasConstCopyConstructor);
Douglas Gregorcfe68222010-07-01 18:27:03 +00008663 }
8664
8665 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8666 BaseEnd = ClassDecl->vbases_end();
8667 HasConstCopyConstructor && Base != BaseEnd;
8668 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008669 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00008670 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt491ec602011-06-21 23:42:56 +00008671 LookupCopyingConstructor(BaseClassDecl, Qualifiers::Const,
8672 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008673 }
8674
8675 // -- for all the nonstatic data members of X that are of a
8676 // class type M (or array thereof), each such class type
8677 // has a copy constructor whose first parameter is of type
8678 // const M& or const volatile M&.
8679 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8680 FieldEnd = ClassDecl->field_end();
8681 HasConstCopyConstructor && Field != FieldEnd;
8682 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00008683 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008684 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
Alexis Hunt491ec602011-06-21 23:42:56 +00008685 LookupCopyingConstructor(FieldClassDecl, Qualifiers::Const,
8686 &HasConstCopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00008687 }
8688 }
Douglas Gregor54be3392010-07-01 17:57:27 +00008689 // Otherwise, the implicitly declared copy constructor will have
8690 // the form
8691 //
8692 // X::X(X&)
Alexis Hunt913820d2011-05-13 06:10:58 +00008693
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008694 // C++ [except.spec]p14:
8695 // An implicitly declared special member function (Clause 12) shall have an
8696 // exception-specification. [...]
8697 ImplicitExceptionSpecification ExceptSpec(Context);
8698 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
8699 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
8700 BaseEnd = ClassDecl->bases_end();
8701 Base != BaseEnd;
8702 ++Base) {
8703 // Virtual bases are handled below.
8704 if (Base->isVirtual())
8705 continue;
8706
Douglas Gregora6d69502010-07-02 23:41:54 +00008707 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008708 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008709 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008710 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008711 ExceptSpec.CalledDecl(CopyConstructor);
8712 }
8713 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
8714 BaseEnd = ClassDecl->vbases_end();
8715 Base != BaseEnd;
8716 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00008717 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008718 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Alexis Hunt899bd442011-06-10 04:44:37 +00008719 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008720 LookupCopyingConstructor(BaseClassDecl, Quals))
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008721 ExceptSpec.CalledDecl(CopyConstructor);
8722 }
8723 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
8724 FieldEnd = ClassDecl->field_end();
8725 Field != FieldEnd;
8726 ++Field) {
8727 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Alexis Hunt899bd442011-06-10 04:44:37 +00008728 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
8729 if (CXXConstructorDecl *CopyConstructor =
Alexis Hunt491ec602011-06-21 23:42:56 +00008730 LookupCopyingConstructor(FieldClassDecl, Quals))
Alexis Hunt899bd442011-06-10 04:44:37 +00008731 ExceptSpec.CalledDecl(CopyConstructor);
Douglas Gregor8453ddb2010-07-01 20:59:04 +00008732 }
8733 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00008734
Alexis Hunt913820d2011-05-13 06:10:58 +00008735 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
8736}
8737
8738CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
8739 CXXRecordDecl *ClassDecl) {
8740 // C++ [class.copy]p4:
8741 // If the class definition does not explicitly declare a copy
8742 // constructor, one is declared implicitly.
8743
8744 ImplicitExceptionSpecification Spec(Context);
8745 bool Const;
8746 llvm::tie(Spec, Const) =
8747 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
8748
8749 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8750 QualType ArgType = ClassType;
8751 if (Const)
8752 ArgType = ArgType.withConst();
8753 ArgType = Context.getLValueReferenceType(ArgType);
8754
8755 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8756
Douglas Gregor54be3392010-07-01 17:57:27 +00008757 DeclarationName Name
8758 = Context.DeclarationNames.getCXXConstructorName(
8759 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00008760 SourceLocation ClassLoc = ClassDecl->getLocation();
8761 DeclarationNameInfo NameInfo(Name, ClassLoc);
Alexis Hunt913820d2011-05-13 06:10:58 +00008762
8763 // An implicitly-declared copy constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +00008764 // member of its class.
8765 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
8766 Context, ClassDecl, ClassLoc, NameInfo,
8767 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8768 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8769 /*isConstexpr=*/ClassDecl->defaultedCopyConstructorIsConstexpr() &&
8770 getLangOptions().CPlusPlus0x);
Douglas Gregor54be3392010-07-01 17:57:27 +00008771 CopyConstructor->setAccess(AS_public);
Alexis Hunt913820d2011-05-13 06:10:58 +00008772 CopyConstructor->setDefaulted();
Douglas Gregor54be3392010-07-01 17:57:27 +00008773 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Richard Smithcc36f692011-12-22 02:22:31 +00008774
Douglas Gregora6d69502010-07-02 23:41:54 +00008775 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00008776 ++ASTContext::NumImplicitCopyConstructorsDeclared;
8777
Douglas Gregor54be3392010-07-01 17:57:27 +00008778 // Add the parameter to the constructor.
8779 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00008780 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00008781 /*IdentifierInfo=*/0,
8782 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00008783 SC_None,
8784 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008785 CopyConstructor->setParams(FromParam);
Alexis Hunt913820d2011-05-13 06:10:58 +00008786
Douglas Gregor0be31a22010-07-02 17:43:08 +00008787 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00008788 PushOnScopeChains(CopyConstructor, S, false);
8789 ClassDecl->addDecl(CopyConstructor);
Alexis Hunte77a28f2011-05-18 03:41:58 +00008790
Nico Weber94e746d2012-01-23 03:19:29 +00008791 // C++11 [class.copy]p8:
8792 // ... If the class definition does not explicitly declare a copy
8793 // constructor, there is no user-declared move constructor, and there is no
8794 // user-declared move assignment operator, a copy constructor is implicitly
8795 // declared as defaulted.
Alexis Huntd74c85f2011-06-22 01:05:13 +00008796 if (ClassDecl->hasUserDeclaredMoveConstructor() ||
Nico Weber94e746d2012-01-23 03:19:29 +00008797 (ClassDecl->hasUserDeclaredMoveAssignment() &&
Nico Weber323076f2012-01-23 04:01:33 +00008798 !getLangOptions().MicrosoftMode) ||
Alexis Hunt1bc6f712011-10-11 04:55:36 +00008799 ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor))
Alexis Hunte77a28f2011-05-18 03:41:58 +00008800 CopyConstructor->setDeletedAsWritten();
Douglas Gregor54be3392010-07-01 17:57:27 +00008801
8802 return CopyConstructor;
8803}
8804
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008805void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
Alexis Hunt913820d2011-05-13 06:10:58 +00008806 CXXConstructorDecl *CopyConstructor) {
8807 assert((CopyConstructor->isDefaulted() &&
8808 CopyConstructor->isCopyConstructor() &&
Alexis Hunt61ae8d32011-05-23 23:14:04 +00008809 !CopyConstructor->doesThisDeclarationHaveABody()) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008810 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00008811
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00008812 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008813 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008814
Douglas Gregora57478e2010-05-01 15:04:51 +00008815 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00008816 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008817
Alexis Hunt1d792652011-01-08 20:30:50 +00008818 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00008819 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00008820 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00008821 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00008822 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00008823 } else {
8824 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
8825 CopyConstructor->getLocation(),
8826 MultiStmtArg(*this, 0, 0),
8827 /*isStmtExpr=*/false)
8828 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008829 CopyConstructor->setImplicitlyDefined(true);
Anders Carlsson53e1ba92010-04-25 00:52:09 +00008830 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00008831
8832 CopyConstructor->setUsed();
Sebastian Redlab238a72011-04-24 16:28:06 +00008833 if (ASTMutationListener *L = getASTMutationListener()) {
8834 L->CompletedImplicitDefinition(CopyConstructor);
8835 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00008836}
8837
Sebastian Redl22653ba2011-08-30 19:58:05 +00008838Sema::ImplicitExceptionSpecification
8839Sema::ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
8840 // C++ [except.spec]p14:
8841 // An implicitly declared special member function (Clause 12) shall have an
8842 // exception-specification. [...]
8843 ImplicitExceptionSpecification ExceptSpec(Context);
8844 if (ClassDecl->isInvalidDecl())
8845 return ExceptSpec;
8846
8847 // Direct base-class constructors.
8848 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
8849 BEnd = ClassDecl->bases_end();
8850 B != BEnd; ++B) {
8851 if (B->isVirtual()) // Handled below.
8852 continue;
8853
8854 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8855 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8856 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8857 // If this is a deleted function, add it anyway. This might be conformant
8858 // with the standard. This might not. I'm not sure. It might not matter.
8859 if (Constructor)
8860 ExceptSpec.CalledDecl(Constructor);
8861 }
8862 }
8863
8864 // Virtual base-class constructors.
8865 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
8866 BEnd = ClassDecl->vbases_end();
8867 B != BEnd; ++B) {
8868 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
8869 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
8870 CXXConstructorDecl *Constructor = LookupMovingConstructor(BaseClassDecl);
8871 // If this is a deleted function, add it anyway. This might be conformant
8872 // with the standard. This might not. I'm not sure. It might not matter.
8873 if (Constructor)
8874 ExceptSpec.CalledDecl(Constructor);
8875 }
8876 }
8877
8878 // Field constructors.
8879 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
8880 FEnd = ClassDecl->field_end();
8881 F != FEnd; ++F) {
Douglas Gregor7db3e952011-11-28 20:03:15 +00008882 if (const RecordType *RecordTy
Sebastian Redl22653ba2011-08-30 19:58:05 +00008883 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
8884 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
8885 CXXConstructorDecl *Constructor = LookupMovingConstructor(FieldRecDecl);
8886 // If this is a deleted function, add it anyway. This might be conformant
8887 // with the standard. This might not. I'm not sure. It might not matter.
8888 // In particular, the problem is that this function never gets called. It
8889 // might just be ill-formed because this function attempts to refer to
8890 // a deleted function here.
8891 if (Constructor)
8892 ExceptSpec.CalledDecl(Constructor);
8893 }
8894 }
8895
8896 return ExceptSpec;
8897}
8898
8899CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
8900 CXXRecordDecl *ClassDecl) {
8901 ImplicitExceptionSpecification Spec(
8902 ComputeDefaultedMoveCtorExceptionSpec(ClassDecl));
8903
8904 QualType ClassType = Context.getTypeDeclType(ClassDecl);
8905 QualType ArgType = Context.getRValueReferenceType(ClassType);
8906
8907 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
8908
8909 DeclarationName Name
8910 = Context.DeclarationNames.getCXXConstructorName(
8911 Context.getCanonicalType(ClassType));
8912 SourceLocation ClassLoc = ClassDecl->getLocation();
8913 DeclarationNameInfo NameInfo(Name, ClassLoc);
8914
8915 // C++0x [class.copy]p11:
8916 // An implicitly-declared copy/move constructor is an inline public
Richard Smithcc36f692011-12-22 02:22:31 +00008917 // member of its class.
8918 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
8919 Context, ClassDecl, ClassLoc, NameInfo,
8920 Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI), /*TInfo=*/0,
8921 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
8922 /*isConstexpr=*/ClassDecl->defaultedMoveConstructorIsConstexpr() &&
8923 getLangOptions().CPlusPlus0x);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008924 MoveConstructor->setAccess(AS_public);
8925 MoveConstructor->setDefaulted();
8926 MoveConstructor->setTrivial(ClassDecl->hasTrivialMoveConstructor());
Richard Smithcc36f692011-12-22 02:22:31 +00008927
Sebastian Redl22653ba2011-08-30 19:58:05 +00008928 // Add the parameter to the constructor.
8929 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
8930 ClassLoc, ClassLoc,
8931 /*IdentifierInfo=*/0,
8932 ArgType, /*TInfo=*/0,
8933 SC_None,
8934 SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00008935 MoveConstructor->setParams(FromParam);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008936
8937 // C++0x [class.copy]p9:
8938 // If the definition of a class X does not explicitly declare a move
8939 // constructor, one will be implicitly declared as defaulted if and only if:
8940 // [...]
8941 // - the move constructor would not be implicitly defined as deleted.
Alexis Hunt77c1f9f2011-10-11 06:43:29 +00008942 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00008943 // Cache this result so that we don't try to generate this over and over
8944 // on every lookup, leaking memory and wasting time.
8945 ClassDecl->setFailedImplicitMoveConstructor();
8946 return 0;
8947 }
8948
8949 // Note that we have declared this constructor.
8950 ++ASTContext::NumImplicitMoveConstructorsDeclared;
8951
8952 if (Scope *S = getScopeForContext(ClassDecl))
8953 PushOnScopeChains(MoveConstructor, S, false);
8954 ClassDecl->addDecl(MoveConstructor);
8955
8956 return MoveConstructor;
8957}
8958
8959void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
8960 CXXConstructorDecl *MoveConstructor) {
8961 assert((MoveConstructor->isDefaulted() &&
8962 MoveConstructor->isMoveConstructor() &&
8963 !MoveConstructor->doesThisDeclarationHaveABody()) &&
8964 "DefineImplicitMoveConstructor - call it for implicit move ctor");
8965
8966 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
8967 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
8968
8969 ImplicitlyDefinedFunctionScope Scope(*this, MoveConstructor);
8970 DiagnosticErrorTrap Trap(Diags);
8971
8972 if (SetCtorInitializers(MoveConstructor, 0, 0, /*AnyErrors=*/false) ||
8973 Trap.hasErrorOccurred()) {
8974 Diag(CurrentLocation, diag::note_member_synthesized_at)
8975 << CXXMoveConstructor << Context.getTagDeclType(ClassDecl);
8976 MoveConstructor->setInvalidDecl();
8977 } else {
8978 MoveConstructor->setBody(ActOnCompoundStmt(MoveConstructor->getLocation(),
8979 MoveConstructor->getLocation(),
8980 MultiStmtArg(*this, 0, 0),
8981 /*isStmtExpr=*/false)
8982 .takeAs<Stmt>());
Douglas Gregoreb4089a2011-09-22 20:32:43 +00008983 MoveConstructor->setImplicitlyDefined(true);
Sebastian Redl22653ba2011-08-30 19:58:05 +00008984 }
8985
8986 MoveConstructor->setUsed();
8987
8988 if (ASTMutationListener *L = getASTMutationListener()) {
8989 L->CompletedImplicitDefinition(MoveConstructor);
8990 }
8991}
8992
John McCalldadc5752010-08-24 06:29:42 +00008993ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00008994Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00008995 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00008996 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008997 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00008998 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00008999 unsigned ConstructKind,
9000 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00009001 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00009002
Douglas Gregor45cf7e32010-04-02 18:24:57 +00009003 // C++0x [class.copy]p34:
9004 // When certain criteria are met, an implementation is allowed to
9005 // omit the copy/move construction of a class object, even if the
9006 // copy/move constructor and/or destructor for the object have
9007 // side effects. [...]
9008 // - when a temporary class object that has not been bound to a
9009 // reference (12.2) would be copied/moved to a class object
9010 // with the same cv-unqualified type, the copy/move operation
9011 // can be omitted by constructing the temporary object
9012 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00009013 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00009014 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00009015 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00009016 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00009017 }
Mike Stump11289f42009-09-09 15:08:12 +00009018
9019 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009020 Elidable, move(ExprArgs), HadMultipleCandidates,
9021 RequiresZeroInit, ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00009022}
9023
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009024/// BuildCXXConstructExpr - Creates a complete call to a constructor,
9025/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00009026ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00009027Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
9028 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00009029 MultiExprArg ExprArgs,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009030 bool HadMultipleCandidates,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00009031 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00009032 unsigned ConstructKind,
9033 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00009034 unsigned NumExprs = ExprArgs.size();
9035 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00009036
Nick Lewyckyd4693212011-03-25 01:44:32 +00009037 for (specific_attr_iterator<NonNullAttr>
9038 i = Constructor->specific_attr_begin<NonNullAttr>(),
9039 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
9040 const NonNullAttr *NonNull = *i;
9041 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
9042 }
9043
Eli Friedmanfa0df832012-02-02 03:46:19 +00009044 MarkFunctionReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00009045 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009046 Constructor, Elidable, Exprs, NumExprs,
9047 HadMultipleCandidates, RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00009048 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
9049 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009050}
9051
Mike Stump11289f42009-09-09 15:08:12 +00009052bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00009053 CXXConstructorDecl *Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009054 MultiExprArg Exprs,
9055 bool HadMultipleCandidates) {
Chandler Carruth01718152010-10-25 08:47:36 +00009056 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00009057 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00009058 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009059 move(Exprs), HadMultipleCandidates, false,
9060 CXXConstructExpr::CK_Complete, SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00009061 if (TempResult.isInvalid())
9062 return true;
Mike Stump11289f42009-09-09 15:08:12 +00009063
Anders Carlsson6eb55572009-08-25 05:12:04 +00009064 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00009065 CheckImplicitConversions(Temp, VD->getLocation());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009066 MarkFunctionReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00009067 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00009068 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00009069
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00009070 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00009071}
9072
John McCall03c48482010-02-02 09:10:11 +00009073void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00009074 if (VD->isInvalidDecl()) return;
9075
John McCall03c48482010-02-02 09:10:11 +00009076 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00009077 if (ClassDecl->isInvalidDecl()) return;
9078 if (ClassDecl->hasTrivialDestructor()) return;
9079 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00009080
Chandler Carruth86d17d32011-03-27 21:26:48 +00009081 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
Eli Friedmanfa0df832012-02-02 03:46:19 +00009082 MarkFunctionReferenced(VD->getLocation(), Destructor);
Chandler Carruth86d17d32011-03-27 21:26:48 +00009083 CheckDestructorAccess(VD->getLocation(), Destructor,
9084 PDiag(diag::err_access_dtor_var)
9085 << VD->getDeclName()
9086 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00009087
Chandler Carruth86d17d32011-03-27 21:26:48 +00009088 if (!VD->hasGlobalStorage()) return;
9089
9090 // Emit warning for non-trivial dtor in global scope (a real global,
9091 // class-static, function-static).
9092 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
9093
9094 // TODO: this should be re-enabled for static locals by !CXAAtExit
9095 if (!VD->isStaticLocal())
9096 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009097}
9098
Mike Stump11289f42009-09-09 15:08:12 +00009099/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009100/// ActOnDeclarator, when a C++ direct initializer is present.
9101/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00009102void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00009103 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009104 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00009105 SourceLocation RParenLoc,
9106 bool TypeMayContainAuto) {
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009107 // If there is no declaration, there was an error parsing it. Just ignore
9108 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00009109 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009110 return;
Mike Stump11289f42009-09-09 15:08:12 +00009111
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009112 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9113 if (!VDecl) {
9114 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9115 RealDecl->setInvalidDecl();
9116 return;
9117 }
9118
Eli Friedmande30e522012-01-05 22:34:08 +00009119 // C++0x [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith30482bc2011-02-20 03:19:35 +00009120 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Eli Friedmande30e522012-01-05 22:34:08 +00009121 if (Exprs.size() == 0) {
9122 // It isn't possible to write this directly, but it is possible to
9123 // end up in this situation with "auto x(some_pack...);"
9124 Diag(LParenLoc, diag::err_auto_var_init_no_expression)
9125 << VDecl->getDeclName() << VDecl->getType()
9126 << VDecl->getSourceRange();
9127 RealDecl->setInvalidDecl();
9128 return;
9129 }
9130
Richard Smith30482bc2011-02-20 03:19:35 +00009131 if (Exprs.size() > 1) {
9132 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
9133 diag::err_auto_var_init_multiple_expressions)
9134 << VDecl->getDeclName() << VDecl->getType()
9135 << VDecl->getSourceRange();
9136 RealDecl->setInvalidDecl();
9137 return;
9138 }
9139
9140 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00009141 TypeSourceInfo *DeducedType = 0;
Sebastian Redl09edce02012-01-23 22:09:39 +00009142 if (DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType) ==
9143 DAR_Failed)
Sebastian Redl42acd4a2012-01-17 22:50:08 +00009144 DiagnoseAutoDeductionFailure(VDecl, Init);
Richard Smith9647d3c2011-03-17 16:11:59 +00009145 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00009146 RealDecl->setInvalidDecl();
9147 return;
9148 }
Richard Smith9647d3c2011-03-17 16:11:59 +00009149 VDecl->setTypeSourceInfo(DeducedType);
9150 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00009151
John McCall31168b02011-06-15 23:02:42 +00009152 // In ARC, infer lifetime.
9153 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9154 VDecl->setInvalidDecl();
9155
Richard Smith30482bc2011-02-20 03:19:35 +00009156 // If this is a redeclaration, check that the type we just deduced matches
9157 // the previously declared type.
Douglas Gregorec9fd132012-01-14 16:38:05 +00009158 if (VarDecl *Old = VDecl->getPreviousDecl())
Richard Smith30482bc2011-02-20 03:19:35 +00009159 MergeVarDeclTypes(VDecl, Old);
9160 }
9161
Douglas Gregor402250f2009-08-26 21:14:46 +00009162 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00009163 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009164 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9165 //
9166 // Clients that want to distinguish between the two forms, can check for
9167 // direct initializer using VarDecl::hasCXXDirectInitializer().
9168 // A major benefit is that clients that don't particularly care about which
9169 // exactly form was it (like the CodeGen) can handle both cases without
9170 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009171
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009172 // C++ 8.5p11:
9173 // The form of initialization (using parentheses or '=') is generally
9174 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009175 // class type.
9176
Douglas Gregor50dc2192010-02-11 22:55:30 +00009177 if (!VDecl->getType()->isDependentType() &&
Douglas Gregorb06fa542011-10-10 16:05:18 +00009178 !VDecl->getType()->isIncompleteArrayType() &&
Douglas Gregor50dc2192010-02-11 22:55:30 +00009179 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00009180 diag::err_typecheck_decl_incomplete_type)) {
9181 VDecl->setInvalidDecl();
9182 return;
9183 }
9184
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009185 // The variable can not have an abstract class type.
9186 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9187 diag::err_abstract_type_in_decl,
9188 AbstractVariableType))
9189 VDecl->setInvalidDecl();
9190
Sebastian Redl5ca79842010-02-01 20:16:42 +00009191 const VarDecl *Def;
9192 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009193 Diag(VDecl->getLocation(), diag::err_redefinition)
9194 << VDecl->getDeclName();
9195 Diag(Def->getLocation(), diag::note_previous_definition);
9196 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00009197 return;
9198 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00009199
Douglas Gregorf0f83692010-08-24 05:27:49 +00009200 // C++ [class.static.data]p4
9201 // If a static data member is of const integral or const
9202 // enumeration type, its declaration in the class definition can
9203 // specify a constant-initializer which shall be an integral
9204 // constant expression (5.19). In that case, the member can appear
9205 // in integral constant expressions. The member shall still be
9206 // defined in a namespace scope if it is used in the program and the
9207 // namespace scope definition shall not contain an initializer.
9208 //
9209 // We already performed a redefinition check above, but for static
9210 // data members we also need to check whether there was an in-class
9211 // declaration with an initializer.
9212 const VarDecl* PrevInit = 0;
9213 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
9214 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
9215 Diag(PrevInit->getLocation(), diag::note_previous_definition);
9216 return;
9217 }
9218
Douglas Gregor71f39c92010-12-16 01:31:22 +00009219 bool IsDependent = false;
9220 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
9221 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
9222 VDecl->setInvalidDecl();
9223 return;
9224 }
9225
9226 if (Exprs.get()[I]->isTypeDependent())
9227 IsDependent = true;
9228 }
9229
Douglas Gregor50dc2192010-02-11 22:55:30 +00009230 // If either the declaration has a dependent type or if any of the
9231 // expressions is type-dependent, we represent the initialization
9232 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00009233 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00009234 // Let clients know that initialization was done with a direct initializer.
9235 VDecl->setCXXDirectInitializer(true);
9236
9237 // Store the initialization expressions as a ParenListExpr.
9238 unsigned NumExprs = Exprs.size();
Manuel Klimekf2b4b692011-06-22 20:02:16 +00009239 VDecl->setInit(new (Context) ParenListExpr(
9240 Context, LParenLoc, (Expr **)Exprs.release(), NumExprs, RParenLoc,
9241 VDecl->getType().getNonReferenceType()));
Douglas Gregor50dc2192010-02-11 22:55:30 +00009242 return;
9243 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009244
9245 // Capture the variable that is being initialized and the style of
9246 // initialization.
9247 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9248
9249 // FIXME: Poor source location information.
9250 InitializationKind Kind
9251 = InitializationKind::CreateDirect(VDecl->getLocation(),
9252 LParenLoc, RParenLoc);
9253
Douglas Gregorb06fa542011-10-10 16:05:18 +00009254 QualType T = VDecl->getType();
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009255 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00009256 Exprs.get(), Exprs.size());
Douglas Gregorb06fa542011-10-10 16:05:18 +00009257 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs), &T);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00009258 if (Result.isInvalid()) {
9259 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009260 return;
Douglas Gregorb06fa542011-10-10 16:05:18 +00009261 } else if (T != VDecl->getType()) {
9262 VDecl->setType(T);
9263 Result.get()->setType(T);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009264 }
John McCallacf0ee52010-10-08 02:01:28 +00009265
Douglas Gregorb06fa542011-10-10 16:05:18 +00009266
Richard Smith2316cd82011-09-29 19:11:37 +00009267 Expr *Init = Result.get();
9268 CheckImplicitConversions(Init, LParenLoc);
Richard Smith2316cd82011-09-29 19:11:37 +00009269
9270 Init = MaybeCreateExprWithCleanups(Init);
9271 VDecl->setInit(Init);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009272 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00009273
John McCall8b7fd8f12011-01-19 11:48:09 +00009274 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00009275}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00009276
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009277/// \brief Given a constructor and the set of arguments provided for the
9278/// constructor, convert the arguments and add any required default arguments
9279/// to form a proper call to this constructor.
9280///
9281/// \returns true if an error occurred, false otherwise.
9282bool
9283Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
9284 MultiExprArg ArgsPtr,
9285 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00009286 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009287 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
9288 unsigned NumArgs = ArgsPtr.size();
9289 Expr **Args = (Expr **)ArgsPtr.get();
9290
9291 const FunctionProtoType *Proto
9292 = Constructor->getType()->getAs<FunctionProtoType>();
9293 assert(Proto && "Constructor without a prototype?");
9294 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009295
9296 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009297 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009298 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009299 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00009300 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009301
9302 VariadicCallType CallType =
9303 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009304 SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00009305 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
9306 Proto, 0, Args, NumArgs, AllArgs,
9307 CallType);
9308 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
9309 ConvertedArgs.push_back(AllArgs[i]);
9310 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00009311}
9312
Anders Carlssone363c8e2009-12-12 00:32:00 +00009313static inline bool
9314CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
9315 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00009316 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00009317 if (isa<NamespaceDecl>(DC)) {
9318 return SemaRef.Diag(FnDecl->getLocation(),
9319 diag::err_operator_new_delete_declared_in_namespace)
9320 << FnDecl->getDeclName();
9321 }
9322
9323 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00009324 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009325 return SemaRef.Diag(FnDecl->getLocation(),
9326 diag::err_operator_new_delete_declared_static)
9327 << FnDecl->getDeclName();
9328 }
9329
Anders Carlsson60659a82009-12-12 02:43:16 +00009330 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00009331}
9332
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009333static inline bool
9334CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
9335 CanQualType ExpectedResultType,
9336 CanQualType ExpectedFirstParamType,
9337 unsigned DependentParamTypeDiag,
9338 unsigned InvalidParamTypeDiag) {
9339 QualType ResultType =
9340 FnDecl->getType()->getAs<FunctionType>()->getResultType();
9341
9342 // Check that the result type is not dependent.
9343 if (ResultType->isDependentType())
9344 return SemaRef.Diag(FnDecl->getLocation(),
9345 diag::err_operator_new_delete_dependent_result_type)
9346 << FnDecl->getDeclName() << ExpectedResultType;
9347
9348 // Check that the result type is what we expect.
9349 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
9350 return SemaRef.Diag(FnDecl->getLocation(),
9351 diag::err_operator_new_delete_invalid_result_type)
9352 << FnDecl->getDeclName() << ExpectedResultType;
9353
9354 // A function template must have at least 2 parameters.
9355 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
9356 return SemaRef.Diag(FnDecl->getLocation(),
9357 diag::err_operator_new_delete_template_too_few_parameters)
9358 << FnDecl->getDeclName();
9359
9360 // The function decl must have at least 1 parameter.
9361 if (FnDecl->getNumParams() == 0)
9362 return SemaRef.Diag(FnDecl->getLocation(),
9363 diag::err_operator_new_delete_too_few_parameters)
9364 << FnDecl->getDeclName();
9365
9366 // Check the the first parameter type is not dependent.
9367 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
9368 if (FirstParamType->isDependentType())
9369 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
9370 << FnDecl->getDeclName() << ExpectedFirstParamType;
9371
9372 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00009373 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009374 ExpectedFirstParamType)
9375 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
9376 << FnDecl->getDeclName() << ExpectedFirstParamType;
9377
9378 return false;
9379}
9380
Anders Carlsson12308f42009-12-11 23:23:22 +00009381static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009382CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00009383 // C++ [basic.stc.dynamic.allocation]p1:
9384 // A program is ill-formed if an allocation function is declared in a
9385 // namespace scope other than global scope or declared static in global
9386 // scope.
9387 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9388 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009389
9390 CanQualType SizeTy =
9391 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
9392
9393 // C++ [basic.stc.dynamic.allocation]p1:
9394 // The return type shall be void*. The first parameter shall have type
9395 // std::size_t.
9396 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
9397 SizeTy,
9398 diag::err_operator_new_dependent_param_type,
9399 diag::err_operator_new_param_type))
9400 return true;
9401
9402 // C++ [basic.stc.dynamic.allocation]p1:
9403 // The first parameter shall not have an associated default argument.
9404 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00009405 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009406 diag::err_operator_new_default_arg)
9407 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
9408
9409 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00009410}
9411
9412static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00009413CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
9414 // C++ [basic.stc.dynamic.deallocation]p1:
9415 // A program is ill-formed if deallocation functions are declared in a
9416 // namespace scope other than global scope or declared static in global
9417 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00009418 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
9419 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009420
9421 // C++ [basic.stc.dynamic.deallocation]p2:
9422 // Each deallocation function shall return void and its first parameter
9423 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009424 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
9425 SemaRef.Context.VoidPtrTy,
9426 diag::err_operator_delete_dependent_param_type,
9427 diag::err_operator_delete_param_type))
9428 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00009429
Anders Carlsson12308f42009-12-11 23:23:22 +00009430 return false;
9431}
9432
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009433/// CheckOverloadedOperatorDeclaration - Check whether the declaration
9434/// of this overloaded operator is well-formed. If so, returns false;
9435/// otherwise, emits appropriate diagnostics and returns true.
9436bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00009437 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009438 "Expected an overloaded operator declaration");
9439
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009440 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
9441
Mike Stump11289f42009-09-09 15:08:12 +00009442 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009443 // The allocation and deallocation functions, operator new,
9444 // operator new[], operator delete and operator delete[], are
9445 // described completely in 3.7.3. The attributes and restrictions
9446 // found in the rest of this subclause do not apply to them unless
9447 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00009448 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00009449 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00009450
Anders Carlsson22f443f2009-12-12 00:26:23 +00009451 if (Op == OO_New || Op == OO_Array_New)
9452 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009453
9454 // C++ [over.oper]p6:
9455 // An operator function shall either be a non-static member
9456 // function or be a non-member function and have at least one
9457 // parameter whose type is a class, a reference to a class, an
9458 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00009459 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
9460 if (MethodDecl->isStatic())
9461 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009462 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009463 } else {
9464 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00009465 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
9466 ParamEnd = FnDecl->param_end();
9467 Param != ParamEnd; ++Param) {
9468 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00009469 if (ParamType->isDependentType() || ParamType->isRecordType() ||
9470 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009471 ClassOrEnumParam = true;
9472 break;
9473 }
9474 }
9475
Douglas Gregord69246b2008-11-17 16:14:12 +00009476 if (!ClassOrEnumParam)
9477 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009478 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009479 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009480 }
9481
9482 // C++ [over.oper]p8:
9483 // An operator function cannot have default arguments (8.3.6),
9484 // except where explicitly stated below.
9485 //
Mike Stump11289f42009-09-09 15:08:12 +00009486 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009487 // (C++ [over.call]p1).
9488 if (Op != OO_Call) {
9489 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
9490 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009491 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00009492 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00009493 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00009494 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009495 }
9496 }
9497
Douglas Gregor6cf08062008-11-10 13:38:07 +00009498 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
9499 { false, false, false }
9500#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
9501 , { Unary, Binary, MemberOnly }
9502#include "clang/Basic/OperatorKinds.def"
9503 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009504
Douglas Gregor6cf08062008-11-10 13:38:07 +00009505 bool CanBeUnaryOperator = OperatorUses[Op][0];
9506 bool CanBeBinaryOperator = OperatorUses[Op][1];
9507 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009508
9509 // C++ [over.oper]p8:
9510 // [...] Operator functions cannot have more or fewer parameters
9511 // than the number required for the corresponding operator, as
9512 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00009513 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00009514 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009515 if (Op != OO_Call &&
9516 ((NumParams == 1 && !CanBeUnaryOperator) ||
9517 (NumParams == 2 && !CanBeBinaryOperator) ||
9518 (NumParams < 1) || (NumParams > 2))) {
9519 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009520 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00009521 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009522 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00009523 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009524 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009525 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00009526 assert(CanBeBinaryOperator &&
9527 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009528 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00009529 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009530
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00009531 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009532 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009533 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00009534
Douglas Gregord69246b2008-11-17 16:14:12 +00009535 // Overloaded operators other than operator() cannot be variadic.
9536 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00009537 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00009538 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009539 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009540 }
9541
9542 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00009543 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
9544 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00009545 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00009546 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009547 }
9548
9549 // C++ [over.inc]p1:
9550 // The user-defined function called operator++ implements the
9551 // prefix and postfix ++ operator. If this function is a member
9552 // function with no parameters, or a non-member function with one
9553 // parameter of class or enumeration type, it defines the prefix
9554 // increment operator ++ for objects of that type. If the function
9555 // is a member function with one parameter (which shall be of type
9556 // int) or a non-member function with two parameters (the second
9557 // of which shall be of type int), it defines the postfix
9558 // increment operator ++ for objects of that type.
9559 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
9560 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
9561 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00009562 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009563 ParamIsInt = BT->getKind() == BuiltinType::Int;
9564
Chris Lattner2b786902008-11-21 07:50:02 +00009565 if (!ParamIsInt)
9566 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00009567 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00009568 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009569 }
9570
Douglas Gregord69246b2008-11-17 16:14:12 +00009571 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00009572}
Chris Lattner3b024a32008-12-17 07:09:26 +00009573
Alexis Huntc88db062010-01-13 09:01:02 +00009574/// CheckLiteralOperatorDeclaration - Check whether the declaration
9575/// of this literal operator function is well-formed. If so, returns
9576/// false; otherwise, emits appropriate diagnostics and returns true.
9577bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
9578 DeclContext *DC = FnDecl->getDeclContext();
9579 Decl::Kind Kind = DC->getDeclKind();
9580 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
9581 Kind != Decl::LinkageSpec) {
9582 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
9583 << FnDecl->getDeclName();
9584 return true;
9585 }
9586
9587 bool Valid = false;
9588
Alexis Hunt7dd26172010-04-07 23:11:06 +00009589 // template <char...> type operator "" name() is the only valid template
9590 // signature, and the only valid signature with no parameters.
9591 if (FnDecl->param_size() == 0) {
9592 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
9593 // Must have only one template parameter
9594 TemplateParameterList *Params = TpDecl->getTemplateParameters();
9595 if (Params->size() == 1) {
9596 NonTypeTemplateParmDecl *PmDecl =
9597 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00009598
Alexis Hunt7dd26172010-04-07 23:11:06 +00009599 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00009600 if (PmDecl && PmDecl->isTemplateParameterPack() &&
9601 Context.hasSameType(PmDecl->getType(), Context.CharTy))
9602 Valid = true;
9603 }
9604 }
9605 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00009606 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00009607 FunctionDecl::param_iterator Param = FnDecl->param_begin();
9608
Alexis Huntc88db062010-01-13 09:01:02 +00009609 QualType T = (*Param)->getType();
9610
Alexis Hunt079a6f72010-04-07 22:57:35 +00009611 // unsigned long long int, long double, and any character type are allowed
9612 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00009613 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
9614 Context.hasSameType(T, Context.LongDoubleTy) ||
9615 Context.hasSameType(T, Context.CharTy) ||
9616 Context.hasSameType(T, Context.WCharTy) ||
9617 Context.hasSameType(T, Context.Char16Ty) ||
9618 Context.hasSameType(T, Context.Char32Ty)) {
9619 if (++Param == FnDecl->param_end())
9620 Valid = true;
9621 goto FinishedParams;
9622 }
9623
Alexis Hunt079a6f72010-04-07 22:57:35 +00009624 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00009625 const PointerType *PT = T->getAs<PointerType>();
9626 if (!PT)
9627 goto FinishedParams;
9628 T = PT->getPointeeType();
9629 if (!T.isConstQualified())
9630 goto FinishedParams;
9631 T = T.getUnqualifiedType();
9632
9633 // Move on to the second parameter;
9634 ++Param;
9635
9636 // If there is no second parameter, the first must be a const char *
9637 if (Param == FnDecl->param_end()) {
9638 if (Context.hasSameType(T, Context.CharTy))
9639 Valid = true;
9640 goto FinishedParams;
9641 }
9642
9643 // const char *, const wchar_t*, const char16_t*, and const char32_t*
9644 // are allowed as the first parameter to a two-parameter function
9645 if (!(Context.hasSameType(T, Context.CharTy) ||
9646 Context.hasSameType(T, Context.WCharTy) ||
9647 Context.hasSameType(T, Context.Char16Ty) ||
9648 Context.hasSameType(T, Context.Char32Ty)))
9649 goto FinishedParams;
9650
9651 // The second and final parameter must be an std::size_t
9652 T = (*Param)->getType().getUnqualifiedType();
9653 if (Context.hasSameType(T, Context.getSizeType()) &&
9654 ++Param == FnDecl->param_end())
9655 Valid = true;
9656 }
9657
9658 // FIXME: This diagnostic is absolutely terrible.
9659FinishedParams:
9660 if (!Valid) {
9661 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
9662 << FnDecl->getDeclName();
9663 return true;
9664 }
9665
Douglas Gregor86325ad2011-08-30 22:40:35 +00009666 StringRef LiteralName
9667 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
9668 if (LiteralName[0] != '_') {
9669 // C++0x [usrlit.suffix]p1:
9670 // Literal suffix identifiers that do not start with an underscore are
9671 // reserved for future standardization.
9672 bool IsHexFloat = true;
9673 if (LiteralName.size() > 1 &&
9674 (LiteralName[0] == 'P' || LiteralName[0] == 'p')) {
9675 for (unsigned I = 1, N = LiteralName.size(); I < N; ++I) {
9676 if (!isdigit(LiteralName[I])) {
9677 IsHexFloat = false;
9678 break;
9679 }
9680 }
9681 }
9682
9683 if (IsHexFloat)
9684 Diag(FnDecl->getLocation(), diag::warn_user_literal_hexfloat)
9685 << LiteralName;
9686 else
9687 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved);
9688 }
9689
Alexis Huntc88db062010-01-13 09:01:02 +00009690 return false;
9691}
9692
Douglas Gregor07665a62009-01-05 19:45:36 +00009693/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
9694/// linkage specification, including the language and (if present)
9695/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
9696/// the location of the language string literal, which is provided
9697/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
9698/// the '{' brace. Otherwise, this linkage specification does not
9699/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00009700Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
9701 SourceLocation LangLoc,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009702 StringRef Lang,
Chris Lattner8ea64422010-11-09 20:15:55 +00009703 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00009704 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009705 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009706 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00009707 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00009708 Language = LinkageSpecDecl::lang_cxx;
9709 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00009710 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00009711 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00009712 }
Mike Stump11289f42009-09-09 15:08:12 +00009713
Chris Lattner438e5012008-12-17 07:13:27 +00009714 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00009715
Douglas Gregor07665a62009-01-05 19:45:36 +00009716 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009717 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009718 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00009719 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00009720 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00009721}
9722
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00009723/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00009724/// the C++ linkage specification LinkageSpec. If RBraceLoc is
9725/// valid, it's the position of the closing '}' brace in a linkage
9726/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00009727Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009728 Decl *LinkageSpec,
9729 SourceLocation RBraceLoc) {
9730 if (LinkageSpec) {
9731 if (RBraceLoc.isValid()) {
9732 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
9733 LSDecl->setRBraceLoc(RBraceLoc);
9734 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009735 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00009736 }
Douglas Gregor07665a62009-01-05 19:45:36 +00009737 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00009738}
9739
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009740/// \brief Perform semantic analysis for the variable declaration that
9741/// occurs within a C++ catch clause, returning the newly-created
9742/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00009743VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00009744 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009745 SourceLocation StartLoc,
9746 SourceLocation Loc,
9747 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009748 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009749 QualType ExDeclType = TInfo->getType();
9750
Sebastian Redl54c04d42008-12-22 19:15:10 +00009751 // Arrays and functions decay.
9752 if (ExDeclType->isArrayType())
9753 ExDeclType = Context.getArrayDecayedType(ExDeclType);
9754 else if (ExDeclType->isFunctionType())
9755 ExDeclType = Context.getPointerType(ExDeclType);
9756
9757 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
9758 // The exception-declaration shall not denote a pointer or reference to an
9759 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00009760 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00009761 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009762 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00009763 Invalid = true;
9764 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009765
Sebastian Redl54c04d42008-12-22 19:15:10 +00009766 QualType BaseType = ExDeclType;
9767 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00009768 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009769 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009770 BaseType = Ptr->getPointeeType();
9771 Mode = 1;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009772 DK = diag::err_catch_incomplete_ptr;
Mike Stump11289f42009-09-09 15:08:12 +00009773 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00009774 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009775 BaseType = Ref->getPointeeType();
9776 Mode = 2;
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009777 DK = diag::err_catch_incomplete_ref;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009778 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00009779 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor3ecbc3d2012-01-24 19:01:26 +00009780 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl54c04d42008-12-22 19:15:10 +00009781 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009782
Mike Stump11289f42009-09-09 15:08:12 +00009783 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009784 RequireNonAbstractType(Loc, ExDeclType,
9785 diag::err_abstract_type_in_decl,
9786 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00009787 Invalid = true;
9788
John McCall2ca705e2010-07-24 00:37:23 +00009789 // Only the non-fragile NeXT runtime currently supports C++ catches
9790 // of ObjC types, and no runtime supports catching ObjC types by value.
9791 if (!Invalid && getLangOptions().ObjC1) {
9792 QualType T = ExDeclType;
9793 if (const ReferenceType *RT = T->getAs<ReferenceType>())
9794 T = RT->getPointeeType();
9795
9796 if (T->isObjCObjectType()) {
9797 Diag(Loc, diag::err_objc_object_catch);
9798 Invalid = true;
9799 } else if (T->isObjCObjectPointerType()) {
Fariborz Jahanian831f0fc2011-06-23 19:00:08 +00009800 if (!getLangOptions().ObjCNonFragileABI)
9801 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
John McCall2ca705e2010-07-24 00:37:23 +00009802 }
9803 }
9804
Abramo Bagnaradff19302011-03-08 08:55:46 +00009805 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
9806 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00009807 ExDecl->setExceptionVariable(true);
9808
Douglas Gregor8ca0c642011-12-10 01:22:52 +00009809 // In ARC, infer 'retaining' for variables of retainable type.
9810 if (getLangOptions().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
9811 Invalid = true;
9812
Douglas Gregor750734c2011-07-06 18:14:43 +00009813 if (!Invalid && !ExDeclType->isDependentType()) {
John McCall1bf58462011-02-16 08:02:54 +00009814 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00009815 // C++ [except.handle]p16:
9816 // The object declared in an exception-declaration or, if the
9817 // exception-declaration does not specify a name, a temporary (12.2) is
9818 // copy-initialized (8.5) from the exception object. [...]
9819 // The object is destroyed when the handler exits, after the destruction
9820 // of any automatic objects initialized within the handler.
9821 //
9822 // We just pretend to initialize the object with itself, then make sure
9823 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00009824 QualType initType = ExDeclType;
9825
9826 InitializedEntity entity =
9827 InitializedEntity::InitializeVariable(ExDecl);
9828 InitializationKind initKind =
9829 InitializationKind::CreateCopy(Loc, SourceLocation());
9830
9831 Expr *opaqueValue =
9832 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
9833 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
9834 ExprResult result = sequence.Perform(*this, entity, initKind,
9835 MultiExprArg(&opaqueValue, 1));
9836 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00009837 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00009838 else {
9839 // If the constructor used was non-trivial, set this as the
9840 // "initializer".
9841 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
9842 if (!construct->getConstructor()->isTrivial()) {
9843 Expr *init = MaybeCreateExprWithCleanups(construct);
9844 ExDecl->setInit(init);
9845 }
9846
9847 // And make sure it's destructable.
9848 FinalizeVarWithDestructor(ExDecl, recordType);
9849 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00009850 }
9851 }
9852
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009853 if (Invalid)
9854 ExDecl->setInvalidDecl();
9855
9856 return ExDecl;
9857}
9858
9859/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
9860/// handler.
John McCall48871652010-08-21 09:40:31 +00009861Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00009862 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00009863 bool Invalid = D.isInvalidType();
9864
9865 // Check for unexpanded parameter packs.
9866 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
9867 UPPC_ExceptionType)) {
9868 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
9869 D.getIdentifierLoc());
9870 Invalid = true;
9871 }
9872
Sebastian Redl54c04d42008-12-22 19:15:10 +00009873 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00009874 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00009875 LookupOrdinaryName,
9876 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009877 // The scope should be freshly made just for us. There is just no way
9878 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00009879 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00009880 if (PrevDecl->isTemplateParameter()) {
9881 // Maybe we will complain about the shadowed template parameter.
9882 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregorf4ef4d22011-10-20 17:58:49 +00009883 PrevDecl = 0;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009884 }
9885 }
9886
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009887 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00009888 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
9889 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009890 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009891 }
9892
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00009893 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00009894 D.getSourceRange().getBegin(),
9895 D.getIdentifierLoc(),
9896 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00009897 if (Invalid)
9898 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00009899
Sebastian Redl54c04d42008-12-22 19:15:10 +00009900 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00009901 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00009902 PushOnScopeChains(ExDecl, S);
9903 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009904 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00009905
Douglas Gregor758a8692009-06-17 21:51:59 +00009906 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00009907 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00009908}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009909
Abramo Bagnaraea947882011-03-08 16:41:52 +00009910Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00009911 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00009912 Expr *AssertMessageExpr_,
9913 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00009914 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009915
Anders Carlsson54b26982009-03-14 00:33:21 +00009916 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009917 // In a static_assert-declaration, the constant-expression shall be a
9918 // constant expression that can be contextually converted to bool.
9919 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
9920 if (Converted.isInvalid())
9921 return 0;
9922
Richard Smith902ca212011-12-14 23:32:26 +00009923 llvm::APSInt Cond;
Richard Smithf4c51d92012-02-04 09:53:13 +00009924 if (VerifyIntegerConstantExpression(Converted.get(), &Cond,
9925 PDiag(diag::err_static_assert_expression_is_not_constant),
9926 /*AllowFold=*/false).isInvalid())
John McCall48871652010-08-21 09:40:31 +00009927 return 0;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009928
Richard Smith902ca212011-12-14 23:32:26 +00009929 if (!Cond)
Abramo Bagnaraea947882011-03-08 16:41:52 +00009930 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00009931 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00009932 }
Mike Stump11289f42009-09-09 15:08:12 +00009933
Douglas Gregoref68fee2010-12-15 23:55:21 +00009934 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
9935 return 0;
9936
Abramo Bagnaraea947882011-03-08 16:41:52 +00009937 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
9938 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00009939
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00009940 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00009941 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00009942}
Sebastian Redlf769df52009-03-24 22:27:57 +00009943
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009944/// \brief Perform semantic analysis of the given friend type declaration.
9945///
9946/// \returns A friend declaration that.
Abramo Bagnara254b6302011-10-29 20:52:52 +00009947FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation Loc,
9948 SourceLocation FriendLoc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009949 TypeSourceInfo *TSInfo) {
9950 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
9951
9952 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00009953 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009954
Richard Smithc8239732011-10-18 21:39:00 +00009955 // C++03 [class.friend]p2:
9956 // An elaborated-type-specifier shall be used in a friend declaration
9957 // for a class.*
9958 //
9959 // * The class-key of the elaborated-type-specifier is required.
9960 if (!ActiveTemplateInstantiations.empty()) {
9961 // Do not complain about the form of friend template types during
9962 // template instantiation; we will already have complained when the
9963 // template was declared.
9964 } else if (!T->isElaboratedTypeSpecifier()) {
9965 // If we evaluated the type to a record type, suggest putting
9966 // a tag in front.
9967 if (const RecordType *RT = T->getAs<RecordType>()) {
9968 RecordDecl *RD = RT->getDecl();
9969
9970 std::string InsertionText = std::string(" ") + RD->getKindName();
9971
9972 Diag(TypeRange.getBegin(),
9973 getLangOptions().CPlusPlus0x ?
9974 diag::warn_cxx98_compat_unelaborated_friend_type :
9975 diag::ext_unelaborated_friend_type)
9976 << (unsigned) RD->getTagKind()
9977 << T
9978 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
9979 InsertionText);
9980 } else {
9981 Diag(FriendLoc,
9982 getLangOptions().CPlusPlus0x ?
9983 diag::warn_cxx98_compat_nonclass_type_friend :
9984 diag::ext_nonclass_type_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009985 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009986 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009987 }
Richard Smithc8239732011-10-18 21:39:00 +00009988 } else if (T->getAs<EnumType>()) {
9989 Diag(FriendLoc,
9990 getLangOptions().CPlusPlus0x ?
9991 diag::warn_cxx98_compat_enum_friend :
9992 diag::ext_enum_friend)
9993 << T
9994 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00009995 }
9996
Douglas Gregor3b4abb62010-04-07 17:57:12 +00009997 // C++0x [class.friend]p3:
9998 // If the type specifier in a friend declaration designates a (possibly
9999 // cv-qualified) class type, that class is declared as a friend; otherwise,
10000 // the friend declaration is ignored.
10001
10002 // FIXME: C++0x has some syntactic restrictions on friend type declarations
10003 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010004
Abramo Bagnara254b6302011-10-29 20:52:52 +000010005 return FriendDecl::Create(Context, CurContext, Loc, TSInfo, FriendLoc);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010006}
10007
John McCallace48cd2010-10-19 01:40:49 +000010008/// Handle a friend tag declaration where the scope specifier was
10009/// templated.
10010Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
10011 unsigned TagSpec, SourceLocation TagLoc,
10012 CXXScopeSpec &SS,
10013 IdentifierInfo *Name, SourceLocation NameLoc,
10014 AttributeList *Attr,
10015 MultiTemplateParamsArg TempParamLists) {
10016 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10017
10018 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +000010019 bool Invalid = false;
10020
10021 if (TemplateParameterList *TemplateParams
Douglas Gregor972fe532011-05-10 18:27:06 +000010022 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
John McCallace48cd2010-10-19 01:40:49 +000010023 TempParamLists.get(),
10024 TempParamLists.size(),
10025 /*friend*/ true,
10026 isExplicitSpecialization,
10027 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +000010028 if (TemplateParams->size() > 0) {
10029 // This is a declaration of a class template.
10030 if (Invalid)
10031 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010032
Eric Christopher6f228b52011-07-21 05:34:24 +000010033 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
10034 SS, Name, NameLoc, Attr,
10035 TemplateParams, AS_public,
Douglas Gregor2820e692011-09-09 19:05:14 +000010036 /*ModulePrivateLoc=*/SourceLocation(),
Eric Christopher6f228b52011-07-21 05:34:24 +000010037 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +000010038 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +000010039 } else {
10040 // The "template<>" header is extraneous.
10041 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
10042 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
10043 isExplicitSpecialization = true;
10044 }
10045 }
10046
10047 if (Invalid) return 0;
10048
John McCallace48cd2010-10-19 01:40:49 +000010049 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +000010050 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +000010051 if (TempParamLists.get()[I]->size()) {
10052 isAllExplicitSpecializations = false;
10053 break;
10054 }
10055 }
10056
10057 // FIXME: don't ignore attributes.
10058
10059 // If it's explicit specializations all the way down, just forget
10060 // about the template header and build an appropriate non-templated
10061 // friend. TODO: for source fidelity, remember the headers.
10062 if (isAllExplicitSpecializations) {
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000010063 if (SS.isEmpty()) {
10064 bool Owned = false;
10065 bool IsDependent = false;
10066 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
10067 Attr, AS_public,
10068 /*ModulePrivateLoc=*/SourceLocation(),
10069 MultiTemplateParamsArg(), Owned, IsDependent,
Richard Smith0f8ee222012-01-10 01:33:14 +000010070 /*ScopedEnumKWLoc=*/SourceLocation(),
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000010071 /*ScopedEnumUsesClassTag=*/false,
10072 /*UnderlyingType=*/TypeResult());
10073 }
10074
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010075 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +000010076 ElaboratedTypeKeyword Keyword
10077 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010078 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +000010079 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +000010080 if (T.isNull())
10081 return 0;
10082
10083 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10084 if (isa<DependentNameType>(T)) {
10085 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000010086 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010087 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000010088 TL.setNameLoc(NameLoc);
10089 } else {
10090 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000010091 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +000010092 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +000010093 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
10094 }
10095
10096 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10097 TSI, FriendLoc);
10098 Friend->setAccess(AS_public);
10099 CurContext->addDecl(Friend);
10100 return Friend;
10101 }
Douglas Gregorf65d8ff2011-10-20 15:58:54 +000010102
10103 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
10104
10105
John McCallace48cd2010-10-19 01:40:49 +000010106
10107 // Handle the case of a templated-scope friend class. e.g.
10108 // template <class T> class A<T>::B;
10109 // FIXME: we don't support these right now.
10110 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10111 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
10112 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10113 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
Abramo Bagnara9033e2b2012-02-06 19:09:27 +000010114 TL.setElaboratedKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +000010115 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +000010116 TL.setNameLoc(NameLoc);
10117
10118 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
10119 TSI, FriendLoc);
10120 Friend->setAccess(AS_public);
10121 Friend->setUnsupportedFriend(true);
10122 CurContext->addDecl(Friend);
10123 return Friend;
10124}
10125
10126
John McCall11083da2009-09-16 22:47:08 +000010127/// Handle a friend type declaration. This works in tandem with
10128/// ActOnTag.
10129///
10130/// Notes on friend class templates:
10131///
10132/// We generally treat friend class declarations as if they were
10133/// declaring a class. So, for example, the elaborated type specifier
10134/// in a friend declaration is required to obey the restrictions of a
10135/// class-head (i.e. no typedefs in the scope chain), template
10136/// parameters are required to match up with simple template-ids, &c.
10137/// However, unlike when declaring a template specialization, it's
10138/// okay to refer to a template specialization without an empty
10139/// template parameter declaration, e.g.
10140/// friend class A<T>::B<unsigned>;
10141/// We permit this as a special case; if there are any template
10142/// parameters present at all, require proper matching, i.e.
10143/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +000010144Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +000010145 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010146 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +000010147
10148 assert(DS.isFriendSpecified());
10149 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10150
John McCall11083da2009-09-16 22:47:08 +000010151 // Try to convert the decl specifier to a type. This works for
10152 // friend templates because ActOnTag never produces a ClassTemplateDecl
10153 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +000010154 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +000010155 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
10156 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +000010157 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +000010158 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010159
Douglas Gregor6c110f32010-12-16 01:14:37 +000010160 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
10161 return 0;
10162
John McCall11083da2009-09-16 22:47:08 +000010163 // This is definitely an error in C++98. It's probably meant to
10164 // be forbidden in C++0x, too, but the specification is just
10165 // poorly written.
10166 //
10167 // The problem is with declarations like the following:
10168 // template <T> friend A<T>::foo;
10169 // where deciding whether a class C is a friend or not now hinges
10170 // on whether there exists an instantiation of A that causes
10171 // 'foo' to equal C. There are restrictions on class-heads
10172 // (which we declare (by fiat) elaborated friend declarations to
10173 // be) that makes this tractable.
10174 //
10175 // FIXME: handle "template <> friend class A<T>;", which
10176 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +000010177 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +000010178 Diag(Loc, diag::err_tagless_friend_type_template)
10179 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +000010180 return 0;
John McCall11083da2009-09-16 22:47:08 +000010181 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010182
John McCallaa74a0c2009-08-28 07:59:38 +000010183 // C++98 [class.friend]p1: A friend of a class is a function
10184 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +000010185 // This is fixed in DR77, which just barely didn't make the C++03
10186 // deadline. It's also a very silly restriction that seriously
10187 // affects inner classes and which nobody else seems to implement;
10188 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +000010189 //
10190 // But note that we could warn about it: it's always useless to
10191 // friend one of your own members (it's not, however, worthless to
10192 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +000010193
John McCall11083da2009-09-16 22:47:08 +000010194 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010195 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +000010196 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010197 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +000010198 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +000010199 TSI,
John McCall11083da2009-09-16 22:47:08 +000010200 DS.getFriendSpecLoc());
10201 else
Abramo Bagnara254b6302011-10-29 20:52:52 +000010202 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010203
10204 if (!D)
John McCall48871652010-08-21 09:40:31 +000010205 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +000010206
John McCall11083da2009-09-16 22:47:08 +000010207 D->setAccess(AS_public);
10208 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +000010209
John McCall48871652010-08-21 09:40:31 +000010210 return D;
John McCallaa74a0c2009-08-28 07:59:38 +000010211}
10212
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010213Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
John McCallde3fd222010-10-12 23:13:28 +000010214 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +000010215 const DeclSpec &DS = D.getDeclSpec();
10216
10217 assert(DS.isFriendSpecified());
10218 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
10219
10220 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +000010221 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall07e91c02009-08-06 02:15:43 +000010222
10223 // C++ [class.friend]p1
10224 // A friend of a class is a function or class....
10225 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +000010226 // It *doesn't* see through dependent types, which is correct
10227 // according to [temp.arg.type]p3:
10228 // If a declaration acquires a function type through a
10229 // type dependent on a template-parameter and this causes
10230 // a declaration that does not use the syntactic form of a
10231 // function declarator to have a function type, the program
10232 // is ill-formed.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010233 if (!TInfo->getType()->isFunctionType()) {
John McCall07e91c02009-08-06 02:15:43 +000010234 Diag(Loc, diag::err_unexpected_friend);
10235
10236 // It might be worthwhile to try to recover by creating an
10237 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +000010238 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010239 }
10240
10241 // C++ [namespace.memdef]p3
10242 // - If a friend declaration in a non-local class first declares a
10243 // class or function, the friend class or function is a member
10244 // of the innermost enclosing namespace.
10245 // - The name of the friend is not found by simple name lookup
10246 // until a matching declaration is provided in that namespace
10247 // scope (either before or after the class declaration granting
10248 // friendship).
10249 // - If a friend function is called, its name may be found by the
10250 // name lookup that considers functions from namespaces and
10251 // classes associated with the types of the function arguments.
10252 // - When looking for a prior declaration of a class or a function
10253 // declared as a friend, scopes outside the innermost enclosing
10254 // namespace scope are not considered.
10255
John McCallde3fd222010-10-12 23:13:28 +000010256 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010257 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10258 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +000010259 assert(Name);
10260
Douglas Gregor6c110f32010-12-16 01:14:37 +000010261 // Check for unexpanded parameter packs.
10262 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
10263 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
10264 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
10265 return 0;
10266
John McCall07e91c02009-08-06 02:15:43 +000010267 // The context we found the declaration in, or in which we should
10268 // create the declaration.
10269 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +000010270 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010271 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +000010272 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +000010273
John McCallde3fd222010-10-12 23:13:28 +000010274 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +000010275
John McCallde3fd222010-10-12 23:13:28 +000010276 // There are four cases here.
10277 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +000010278 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +000010279 // there as appropriate.
10280 // Recover from invalid scope qualifiers as if they just weren't there.
10281 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +000010282 // C++0x [namespace.memdef]p3:
10283 // If the name in a friend declaration is neither qualified nor
10284 // a template-id and the declaration is a function or an
10285 // elaborated-type-specifier, the lookup to determine whether
10286 // the entity has been previously declared shall not consider
10287 // any scopes outside the innermost enclosing namespace.
10288 // C++0x [class.friend]p11:
10289 // If a friend declaration appears in a local class and the name
10290 // specified is an unqualified name, a prior declaration is
10291 // looked up without considering scopes that are outside the
10292 // innermost enclosing non-class scope. For a friend function
10293 // declaration, if there is no prior declaration, the program is
10294 // ill-formed.
10295 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +000010296 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +000010297
John McCallf7cfb222010-10-13 05:45:15 +000010298 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +000010299 DC = CurContext;
10300 while (true) {
10301 // Skip class contexts. If someone can cite chapter and verse
10302 // for this behavior, that would be nice --- it's what GCC and
10303 // EDG do, and it seems like a reasonable intent, but the spec
10304 // really only says that checks for unqualified existing
10305 // declarations should stop at the nearest enclosing namespace,
10306 // not that they should only consider the nearest enclosing
10307 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010308 while (DC->isRecord())
10309 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +000010310
John McCall1f82f242009-11-18 22:49:29 +000010311 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +000010312
10313 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +000010314 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +000010315 break;
John McCallf7cfb222010-10-13 05:45:15 +000010316
John McCallf4776592010-10-14 22:22:28 +000010317 if (isTemplateId) {
10318 if (isa<TranslationUnitDecl>(DC)) break;
10319 } else {
10320 if (DC->isFileContext()) break;
10321 }
John McCall07e91c02009-08-06 02:15:43 +000010322 DC = DC->getParent();
10323 }
10324
10325 // C++ [class.friend]p1: A friend of a class is a function or
10326 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000010327 // C++11 changes this for both friend types and functions.
John McCall93343b92009-08-06 20:49:32 +000010328 // Most C++ 98 compilers do seem to give an error here, so
10329 // we do, too.
Richard Smith0bf8a4922011-10-18 20:49:44 +000010330 if (!Previous.empty() && DC->Equals(CurContext))
10331 Diag(DS.getFriendSpecLoc(),
10332 getLangOptions().CPlusPlus0x ?
10333 diag::warn_cxx98_compat_friend_is_member :
10334 diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +000010335
John McCallccbc0322010-10-13 06:22:15 +000010336 DCScope = getScopeForDeclContext(S, DC);
Douglas Gregordd847ba2011-11-03 16:37:14 +000010337
Douglas Gregor16e65612011-10-10 01:11:59 +000010338 // C++ [class.friend]p6:
10339 // A function can be defined in a friend declaration of a class if and
10340 // only if the class is a non-local class (9.8), the function name is
10341 // unqualified, and the function has namespace scope.
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010342 if (isLocal && D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010343 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
10344 }
10345
John McCallde3fd222010-10-12 23:13:28 +000010346 // - There's a non-dependent scope specifier, in which case we
10347 // compute it and do a previous lookup there for a function
10348 // or function template.
10349 } else if (!SS.getScopeRep()->isDependent()) {
10350 DC = computeDeclContext(SS);
10351 if (!DC) return 0;
10352
10353 if (RequireCompleteDeclContext(SS, DC)) return 0;
10354
10355 LookupQualifiedName(Previous, DC);
10356
10357 // Ignore things found implicitly in the wrong scope.
10358 // TODO: better diagnostics for this case. Suggesting the right
10359 // qualified scope would be nice...
10360 LookupResult::Filter F = Previous.makeFilter();
10361 while (F.hasNext()) {
10362 NamedDecl *D = F.next();
10363 if (!DC->InEnclosingNamespaceSetOf(
10364 D->getDeclContext()->getRedeclContext()))
10365 F.erase();
10366 }
10367 F.done();
10368
10369 if (Previous.empty()) {
10370 D.setInvalidType();
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010371 Diag(Loc, diag::err_qualified_friend_not_found)
10372 << Name << TInfo->getType();
John McCallde3fd222010-10-12 23:13:28 +000010373 return 0;
10374 }
10375
10376 // C++ [class.friend]p1: A friend of a class is a function or
10377 // class that is not a member of the class . . .
Richard Smith0bf8a4922011-10-18 20:49:44 +000010378 if (DC->Equals(CurContext))
10379 Diag(DS.getFriendSpecLoc(),
10380 getLangOptions().CPlusPlus0x ?
10381 diag::warn_cxx98_compat_friend_is_member :
10382 diag::err_friend_is_member);
Douglas Gregor16e65612011-10-10 01:11:59 +000010383
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010384 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010385 // C++ [class.friend]p6:
10386 // A function can be defined in a friend declaration of a class if and
10387 // only if the class is a non-local class (9.8), the function name is
10388 // unqualified, and the function has namespace scope.
10389 SemaDiagnosticBuilder DB
10390 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
10391
10392 DB << SS.getScopeRep();
10393 if (DC->isFileContext())
10394 DB << FixItHint::CreateRemoval(SS.getRange());
10395 SS.clear();
10396 }
John McCallde3fd222010-10-12 23:13:28 +000010397
10398 // - There's a scope specifier that does not match any template
10399 // parameter lists, in which case we use some arbitrary context,
10400 // create a method or method template, and wait for instantiation.
10401 // - There's a scope specifier that does match some template
10402 // parameter lists, which we don't handle right now.
10403 } else {
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010404 if (D.isFunctionDefinition()) {
Douglas Gregor16e65612011-10-10 01:11:59 +000010405 // C++ [class.friend]p6:
10406 // A function can be defined in a friend declaration of a class if and
10407 // only if the class is a non-local class (9.8), the function name is
10408 // unqualified, and the function has namespace scope.
10409 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
10410 << SS.getScopeRep();
10411 }
10412
John McCallde3fd222010-10-12 23:13:28 +000010413 DC = CurContext;
10414 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +000010415 }
Douglas Gregor16e65612011-10-10 01:11:59 +000010416
John McCallf7cfb222010-10-13 05:45:15 +000010417 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +000010418 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +000010419 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
10420 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
10421 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +000010422 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +000010423 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
10424 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +000010425 return 0;
John McCall07e91c02009-08-06 02:15:43 +000010426 }
John McCall07e91c02009-08-06 02:15:43 +000010427 }
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010428
Douglas Gregordd847ba2011-11-03 16:37:14 +000010429 // FIXME: This is an egregious hack to cope with cases where the scope stack
10430 // does not contain the declaration context, i.e., in an out-of-line
10431 // definition of a class.
10432 Scope FakeDCScope(S, Scope::DeclScope, Diags);
10433 if (!DCScope) {
10434 FakeDCScope.setEntity(DC);
10435 DCScope = &FakeDCScope;
10436 }
10437
Francois Pichet00c7e6c2011-08-14 03:52:19 +000010438 bool AddToScope = true;
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +000010439 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
10440 move(TemplateParams), AddToScope);
John McCall48871652010-08-21 09:40:31 +000010441 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +000010442
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010443 assert(ND->getDeclContext() == DC);
10444 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +000010445
John McCall759e32b2009-08-31 22:39:49 +000010446 // Add the function declaration to the appropriate lookup tables,
10447 // adjusting the redeclarations list as necessary. We don't
10448 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +000010449 //
John McCall759e32b2009-08-31 22:39:49 +000010450 // Also update the scope-based lookup if the target context's
10451 // lookup context is in lexical scope.
10452 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +000010453 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010454 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010455 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010456 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +000010457 }
John McCallaa74a0c2009-08-28 07:59:38 +000010458
10459 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +000010460 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +000010461 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +000010462 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +000010463 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +000010464
John McCallde3fd222010-10-12 23:13:28 +000010465 if (ND->isInvalidDecl())
10466 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +000010467 else {
10468 FunctionDecl *FD;
10469 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
10470 FD = FTD->getTemplatedDecl();
10471 else
10472 FD = cast<FunctionDecl>(ND);
10473
10474 // Mark templated-scope function declarations as unsupported.
10475 if (FD->getNumTemplateParameterLists())
10476 FrD->setUnsupportedFriend(true);
10477 }
John McCallde3fd222010-10-12 23:13:28 +000010478
John McCall48871652010-08-21 09:40:31 +000010479 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +000010480}
10481
John McCall48871652010-08-21 09:40:31 +000010482void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
10483 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +000010484
Sebastian Redlf769df52009-03-24 22:27:57 +000010485 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
10486 if (!Fn) {
10487 Diag(DelLoc, diag::err_deleted_non_function);
10488 return;
10489 }
Douglas Gregorec9fd132012-01-14 16:38:05 +000010490 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
Sebastian Redlf769df52009-03-24 22:27:57 +000010491 Diag(DelLoc, diag::err_deleted_decl_not_first);
10492 Diag(Prev->getLocation(), diag::note_previous_declaration);
10493 // If the declaration wasn't the first, we delete the function anyway for
10494 // recovery.
10495 }
Alexis Hunt4a8ea102011-05-06 20:44:56 +000010496 Fn->setDeletedAsWritten();
Sebastian Redlf769df52009-03-24 22:27:57 +000010497}
Sebastian Redl4c018662009-04-27 21:33:24 +000010498
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010499void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
10500 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
10501
10502 if (MD) {
Alexis Hunt1fb4e762011-05-23 21:07:59 +000010503 if (MD->getParent()->isDependentType()) {
10504 MD->setDefaulted();
10505 MD->setExplicitlyDefaulted();
10506 return;
10507 }
10508
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010509 CXXSpecialMember Member = getSpecialMember(MD);
10510 if (Member == CXXInvalid) {
10511 Diag(DefaultLoc, diag::err_default_special_members);
10512 return;
10513 }
10514
10515 MD->setDefaulted();
10516 MD->setExplicitlyDefaulted();
10517
Alexis Hunt61ae8d32011-05-23 23:14:04 +000010518 // If this definition appears within the record, do the checking when
10519 // the record is complete.
10520 const FunctionDecl *Primary = MD;
10521 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
10522 // Find the uninstantiated declaration that actually had the '= default'
10523 // on it.
10524 MD->getTemplateInstantiationPattern()->isDefined(Primary);
10525
10526 if (Primary == Primary->getCanonicalDecl())
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010527 return;
10528
10529 switch (Member) {
10530 case CXXDefaultConstructor: {
10531 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10532 CheckExplicitlyDefaultedDefaultConstructor(CD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010533 if (!CD->isInvalidDecl())
10534 DefineImplicitDefaultConstructor(DefaultLoc, CD);
10535 break;
10536 }
10537
10538 case CXXCopyConstructor: {
10539 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10540 CheckExplicitlyDefaultedCopyConstructor(CD);
10541 if (!CD->isInvalidDecl())
10542 DefineImplicitCopyConstructor(DefaultLoc, CD);
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010543 break;
10544 }
Alexis Huntf91729462011-05-12 22:46:25 +000010545
Alexis Huntc9a55732011-05-14 05:23:28 +000010546 case CXXCopyAssignment: {
10547 CheckExplicitlyDefaultedCopyAssignment(MD);
10548 if (!MD->isInvalidDecl())
10549 DefineImplicitCopyAssignment(DefaultLoc, MD);
10550 break;
10551 }
10552
Alexis Huntf91729462011-05-12 22:46:25 +000010553 case CXXDestructor: {
10554 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
10555 CheckExplicitlyDefaultedDestructor(DD);
Alexis Hunt913820d2011-05-13 06:10:58 +000010556 if (!DD->isInvalidDecl())
10557 DefineImplicitDestructor(DefaultLoc, DD);
Alexis Huntf91729462011-05-12 22:46:25 +000010558 break;
10559 }
10560
Sebastian Redl22653ba2011-08-30 19:58:05 +000010561 case CXXMoveConstructor: {
10562 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
10563 CheckExplicitlyDefaultedMoveConstructor(CD);
10564 if (!CD->isInvalidDecl())
10565 DefineImplicitMoveConstructor(DefaultLoc, CD);
Alexis Hunt119c10e2011-05-25 23:16:36 +000010566 break;
Sebastian Redl22653ba2011-08-30 19:58:05 +000010567 }
Alexis Hunt119c10e2011-05-25 23:16:36 +000010568
Sebastian Redl22653ba2011-08-30 19:58:05 +000010569 case CXXMoveAssignment: {
10570 CheckExplicitlyDefaultedMoveAssignment(MD);
10571 if (!MD->isInvalidDecl())
10572 DefineImplicitMoveAssignment(DefaultLoc, MD);
10573 break;
10574 }
10575
10576 case CXXInvalid:
David Blaikie83d382b2011-09-23 05:06:16 +000010577 llvm_unreachable("Invalid special member.");
Alexis Hunt5a7fa252011-05-12 06:15:49 +000010578 }
10579 } else {
10580 Diag(DefaultLoc, diag::err_default_special_members);
10581 }
10582}
10583
Sebastian Redl4c018662009-04-27 21:33:24 +000010584static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +000010585 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +000010586 Stmt *SubStmt = *CI;
10587 if (!SubStmt)
10588 continue;
10589 if (isa<ReturnStmt>(SubStmt))
10590 Self.Diag(SubStmt->getSourceRange().getBegin(),
10591 diag::err_return_in_constructor_handler);
10592 if (!isa<Expr>(SubStmt))
10593 SearchForReturnInStmt(Self, SubStmt);
10594 }
10595}
10596
10597void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
10598 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
10599 CXXCatchStmt *Handler = TryBlock->getHandler(I);
10600 SearchForReturnInStmt(*this, Handler);
10601 }
10602}
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010603
Mike Stump11289f42009-09-09 15:08:12 +000010604bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010605 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +000010606 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
10607 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010608
Chandler Carruth284bb2e2010-02-15 11:53:20 +000010609 if (Context.hasSameType(NewTy, OldTy) ||
10610 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010611 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010612
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010613 // Check if the return types are covariant
10614 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +000010615
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010616 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010617 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
10618 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010619 NewClassTy = NewPT->getPointeeType();
10620 OldClassTy = OldPT->getPointeeType();
10621 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010622 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
10623 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
10624 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
10625 NewClassTy = NewRT->getPointeeType();
10626 OldClassTy = OldRT->getPointeeType();
10627 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010628 }
10629 }
Mike Stump11289f42009-09-09 15:08:12 +000010630
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010631 // The return types aren't either both pointers or references to a class type.
10632 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +000010633 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010634 diag::err_different_return_type_for_overriding_virtual_function)
10635 << New->getDeclName() << NewTy << OldTy;
10636 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +000010637
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010638 return true;
10639 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010640
Anders Carlssone60365b2009-12-31 18:34:24 +000010641 // C++ [class.virtual]p6:
10642 // If the return type of D::f differs from the return type of B::f, the
10643 // class type in the return type of D::f shall be complete at the point of
10644 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010645 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
10646 if (!RT->isBeingDefined() &&
10647 RequireCompleteType(New->getLocation(), NewClassTy,
10648 PDiag(diag::err_covariant_return_incomplete)
10649 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +000010650 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +000010651 }
Anders Carlssone60365b2009-12-31 18:34:24 +000010652
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +000010653 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010654 // Check if the new class derives from the old class.
10655 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
10656 Diag(New->getLocation(),
10657 diag::err_covariant_return_not_derived)
10658 << New->getDeclName() << NewTy << OldTy;
10659 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10660 return true;
10661 }
Mike Stump11289f42009-09-09 15:08:12 +000010662
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010663 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +000010664 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +000010665 diag::err_covariant_return_inaccessible_base,
10666 diag::err_covariant_return_ambiguous_derived_to_base_conv,
10667 // FIXME: Should this point to the return type?
10668 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +000010669 // FIXME: this note won't trigger for delayed access control
10670 // diagnostics, and it's impossible to get an undelayed error
10671 // here from access control during the original parse because
10672 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010673 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10674 return true;
10675 }
10676 }
Mike Stump11289f42009-09-09 15:08:12 +000010677
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010678 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +000010679 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010680 Diag(New->getLocation(),
10681 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010682 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010683 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10684 return true;
10685 };
Mike Stump11289f42009-09-09 15:08:12 +000010686
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010687
10688 // The new class type must have the same or less qualifiers as the old type.
10689 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
10690 Diag(New->getLocation(),
10691 diag::err_covariant_return_type_class_type_more_qualified)
10692 << New->getDeclName() << NewTy << OldTy;
10693 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
10694 return true;
10695 };
Mike Stump11289f42009-09-09 15:08:12 +000010696
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +000010697 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +000010698}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010699
Douglas Gregor21920e372009-12-01 17:24:26 +000010700/// \brief Mark the given method pure.
10701///
10702/// \param Method the method to be marked pure.
10703///
10704/// \param InitRange the source range that covers the "0" initializer.
10705bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010706 SourceLocation EndLoc = InitRange.getEnd();
10707 if (EndLoc.isValid())
10708 Method->setRangeEnd(EndLoc);
10709
Douglas Gregor21920e372009-12-01 17:24:26 +000010710 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
10711 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +000010712 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +000010713 }
Douglas Gregor21920e372009-12-01 17:24:26 +000010714
10715 if (!Method->isInvalidDecl())
10716 Diag(Method->getLocation(), diag::err_non_virtual_pure)
10717 << Method->getDeclName() << InitRange;
10718 return true;
10719}
10720
John McCall1f4ee7b2009-12-19 09:28:58 +000010721/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
10722/// an initializer for the out-of-line declaration 'Dcl'. The scope
10723/// is a fresh scope pushed for just this purpose.
10724///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010725/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
10726/// static data member of class X, names should be looked up in the scope of
10727/// class X.
John McCall48871652010-08-21 09:40:31 +000010728void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010729 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010730 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010731
John McCall1f4ee7b2009-12-19 09:28:58 +000010732 // We should only get called for declarations with scope specifiers, like:
10733 // int foo::bar;
10734 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010735 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010736}
10737
10738/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +000010739/// initializer for the out-of-line declaration 'D'.
10740void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010741 // If there is no declaration, there was an error parsing it.
Argyrios Kyrtzidis8e4be0b2011-04-22 18:52:25 +000010742 if (D == 0 || D->isInvalidDecl()) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010743
John McCall1f4ee7b2009-12-19 09:28:58 +000010744 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +000010745 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +000010746}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010747
10748/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
10749/// C++ if/switch/while/for statement.
10750/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +000010751DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010752 // C++ 6.4p2:
10753 // The declarator shall not specify a function or an array.
10754 // The type-specifier-seq shall not contain typedef and shall not declare a
10755 // new class or enumeration.
10756 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
10757 "Parser allowed 'typedef' as storage class of condition decl.");
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010758
10759 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010760 if (!Dcl)
10761 return true;
10762
Argyrios Kyrtzidis8ea7e582011-06-28 03:01:12 +000010763 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
10764 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010765 << D.getSourceRange();
Douglas Gregor1fe12c92011-07-05 16:13:20 +000010766 return true;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010767 }
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010768
Douglas Gregor7bab5ff2009-11-25 00:27:52 +000010769 return Dcl;
10770}
Anders Carlssonf98849e2009-12-02 17:15:43 +000010771
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010772void Sema::LoadExternalVTableUses() {
10773 if (!ExternalSource)
10774 return;
10775
10776 SmallVector<ExternalVTableUse, 4> VTables;
10777 ExternalSource->ReadUsedVTables(VTables);
10778 SmallVector<VTableUse, 4> NewUses;
10779 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
10780 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
10781 = VTablesUsed.find(VTables[I].Record);
10782 // Even if a definition wasn't required before, it may be required now.
10783 if (Pos != VTablesUsed.end()) {
10784 if (!Pos->second && VTables[I].DefinitionRequired)
10785 Pos->second = true;
10786 continue;
10787 }
10788
10789 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
10790 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
10791 }
10792
10793 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
10794}
10795
Douglas Gregor88d292c2010-05-13 16:44:06 +000010796void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
10797 bool DefinitionRequired) {
10798 // Ignore any vtable uses in unevaluated operands or for classes that do
10799 // not have a vtable.
10800 if (!Class->isDynamicClass() || Class->isDependentContext() ||
10801 CurContext->isDependentContext() ||
Eli Friedman02b58512012-01-21 04:44:06 +000010802 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +000010803 return;
10804
Douglas Gregor88d292c2010-05-13 16:44:06 +000010805 // Try to insert this class into the map.
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010806 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010807 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10808 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
10809 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
10810 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +000010811 // If we already had an entry, check to see if we are promoting this vtable
10812 // to required a definition. If so, we need to reappend to the VTableUses
10813 // list, since we may have already processed the first entry.
10814 if (DefinitionRequired && !Pos.first->second) {
10815 Pos.first->second = true;
10816 } else {
10817 // Otherwise, we can early exit.
10818 return;
10819 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010820 }
10821
10822 // Local classes need to have their virtual members marked
10823 // immediately. For all other classes, we mark their virtual members
10824 // at the end of the translation unit.
10825 if (Class->isLocalClass())
10826 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +000010827 else
Douglas Gregor88d292c2010-05-13 16:44:06 +000010828 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +000010829}
10830
Douglas Gregor88d292c2010-05-13 16:44:06 +000010831bool Sema::DefineUsedVTables() {
Douglas Gregor4daf6a32011-07-28 19:11:31 +000010832 LoadExternalVTableUses();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010833 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +000010834 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +000010835
Douglas Gregor88d292c2010-05-13 16:44:06 +000010836 // Note: The VTableUses vector could grow as a result of marking
10837 // the members of a class as "used", so we check the size each
10838 // time through the loop and prefer indices (with are stable) to
10839 // iterators (which are not).
Douglas Gregor97509692011-04-22 22:25:37 +000010840 bool DefinedAnything = false;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010841 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +000010842 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +000010843 if (!Class)
10844 continue;
10845
10846 SourceLocation Loc = VTableUses[I].second;
10847
10848 // If this class has a key function, but that key function is
10849 // defined in another translation unit, we don't need to emit the
10850 // vtable even though we're using it.
10851 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +000010852 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +000010853 switch (KeyFunction->getTemplateSpecializationKind()) {
10854 case TSK_Undeclared:
10855 case TSK_ExplicitSpecialization:
10856 case TSK_ExplicitInstantiationDeclaration:
10857 // The key function is in another translation unit.
10858 continue;
10859
10860 case TSK_ExplicitInstantiationDefinition:
10861 case TSK_ImplicitInstantiation:
10862 // We will be instantiating the key function.
10863 break;
10864 }
10865 } else if (!KeyFunction) {
10866 // If we have a class with no key function that is the subject
10867 // of an explicit instantiation declaration, suppress the
10868 // vtable; it will live with the explicit instantiation
10869 // definition.
10870 bool IsExplicitInstantiationDeclaration
10871 = Class->getTemplateSpecializationKind()
10872 == TSK_ExplicitInstantiationDeclaration;
10873 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
10874 REnd = Class->redecls_end();
10875 R != REnd; ++R) {
10876 TemplateSpecializationKind TSK
10877 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
10878 if (TSK == TSK_ExplicitInstantiationDeclaration)
10879 IsExplicitInstantiationDeclaration = true;
10880 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10881 IsExplicitInstantiationDeclaration = false;
10882 break;
10883 }
10884 }
10885
10886 if (IsExplicitInstantiationDeclaration)
10887 continue;
10888 }
10889
10890 // Mark all of the virtual members of this class as referenced, so
10891 // that we can build a vtable. Then, tell the AST consumer that a
10892 // vtable for this class is required.
Douglas Gregor97509692011-04-22 22:25:37 +000010893 DefinedAnything = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010894 MarkVirtualMembersReferenced(Loc, Class);
10895 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
10896 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
10897
10898 // Optionally warn if we're emitting a weak vtable.
10899 if (Class->getLinkage() == ExternalLinkage &&
10900 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Douglas Gregor34bc6e52011-09-23 19:04:03 +000010901 const FunctionDecl *KeyFunctionDef = 0;
10902 if (!KeyFunction ||
10903 (KeyFunction->hasBody(KeyFunctionDef) &&
10904 KeyFunctionDef->isInlined()))
David Blaikie72b61202011-12-09 18:32:50 +000010905 Diag(Class->getLocation(), Class->getTemplateSpecializationKind() ==
10906 TSK_ExplicitInstantiationDefinition
10907 ? diag::warn_weak_template_vtable : diag::warn_weak_vtable)
10908 << Class;
Douglas Gregor88d292c2010-05-13 16:44:06 +000010909 }
Anders Carlssonf98849e2009-12-02 17:15:43 +000010910 }
Douglas Gregor88d292c2010-05-13 16:44:06 +000010911 VTableUses.clear();
10912
Douglas Gregor97509692011-04-22 22:25:37 +000010913 return DefinedAnything;
Anders Carlssonf98849e2009-12-02 17:15:43 +000010914}
Anders Carlsson82fccd02009-12-07 08:24:59 +000010915
Rafael Espindola5b334082010-03-26 00:36:59 +000010916void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
10917 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +000010918 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
10919 e = RD->method_end(); i != e; ++i) {
10920 CXXMethodDecl *MD = *i;
10921
10922 // C++ [basic.def.odr]p2:
10923 // [...] A virtual member function is used if it is not pure. [...]
10924 if (MD->isVirtual() && !MD->isPure())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010925 MarkFunctionReferenced(Loc, MD);
Anders Carlsson82fccd02009-12-07 08:24:59 +000010926 }
Rafael Espindola5b334082010-03-26 00:36:59 +000010927
10928 // Only classes that have virtual bases need a VTT.
10929 if (RD->getNumVBases() == 0)
10930 return;
10931
10932 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
10933 e = RD->bases_end(); i != e; ++i) {
10934 const CXXRecordDecl *Base =
10935 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +000010936 if (Base->getNumVBases() == 0)
10937 continue;
10938 MarkVirtualMembersReferenced(Loc, Base);
10939 }
Anders Carlsson82fccd02009-12-07 08:24:59 +000010940}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010941
10942/// SetIvarInitializers - This routine builds initialization ASTs for the
10943/// Objective-C implementation whose ivars need be initialized.
10944void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
10945 if (!getLangOptions().CPlusPlus)
10946 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +000010947 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010948 SmallVector<ObjCIvarDecl*, 8> ivars;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010949 CollectIvarsToConstructOrDestruct(OID, ivars);
10950 if (ivars.empty())
10951 return;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000010952 SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010953 for (unsigned i = 0; i < ivars.size(); i++) {
10954 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +000010955 if (Field->isInvalidDecl())
10956 continue;
10957
Alexis Hunt1d792652011-01-08 20:30:50 +000010958 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010959 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
10960 InitializationKind InitKind =
10961 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
10962
10963 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +000010964 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +000010965 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +000010966 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010967 // Note, MemberInit could actually come back empty if no initialization
10968 // is required (e.g., because it would call a trivial default constructor)
10969 if (!MemberInit.get() || MemberInit.isInvalid())
10970 continue;
John McCallacf0ee52010-10-08 02:01:28 +000010971
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010972 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +000010973 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
10974 SourceLocation(),
10975 MemberInit.takeAs<Expr>(),
10976 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010977 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +000010978
10979 // Be sure that the destructor is accessible and is marked as referenced.
10980 if (const RecordType *RecordTy
10981 = Context.getBaseElementType(Field->getType())
10982 ->getAs<RecordType>()) {
10983 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +000010984 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010985 MarkFunctionReferenced(Field->getLocation(), Destructor);
Douglas Gregor527786e2010-05-20 02:24:22 +000010986 CheckDestructorAccess(Field->getLocation(), Destructor,
10987 PDiag(diag::err_access_dtor_ivar)
10988 << Context.getBaseElementType(Field->getType()));
10989 }
10990 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +000010991 }
10992 ObjCImplementation->setIvarInitializers(Context,
10993 AllToInit.data(), AllToInit.size());
10994 }
10995}
Alexis Hunt6118d662011-05-04 05:57:24 +000010996
Alexis Hunt27a761d2011-05-04 23:29:54 +000010997static
10998void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
10999 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
11000 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
11001 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
11002 Sema &S) {
11003 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11004 CE = Current.end();
11005 if (Ctor->isInvalidDecl())
11006 return;
11007
11008 const FunctionDecl *FNTarget = 0;
11009 CXXConstructorDecl *Target;
11010
11011 // We ignore the result here since if we don't have a body, Target will be
11012 // null below.
11013 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
11014 Target
11015= const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
11016
11017 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
11018 // Avoid dereferencing a null pointer here.
11019 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
11020
11021 if (!Current.insert(Canonical))
11022 return;
11023
11024 // We know that beyond here, we aren't chaining into a cycle.
11025 if (!Target || !Target->isDelegatingConstructor() ||
11026 Target->isInvalidDecl() || Valid.count(TCanonical)) {
11027 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11028 Valid.insert(*CI);
11029 Current.clear();
11030 // We've hit a cycle.
11031 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
11032 Current.count(TCanonical)) {
11033 // If we haven't diagnosed this cycle yet, do so now.
11034 if (!Invalid.count(TCanonical)) {
11035 S.Diag((*Ctor->init_begin())->getSourceLocation(),
Alexis Hunte2622992011-05-05 00:05:47 +000011036 diag::warn_delegating_ctor_cycle)
Alexis Hunt27a761d2011-05-04 23:29:54 +000011037 << Ctor;
11038
11039 // Don't add a note for a function delegating directo to itself.
11040 if (TCanonical != Canonical)
11041 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
11042
11043 CXXConstructorDecl *C = Target;
11044 while (C->getCanonicalDecl() != Canonical) {
11045 (void)C->getTargetConstructor()->hasBody(FNTarget);
11046 assert(FNTarget && "Ctor cycle through bodiless function");
11047
11048 C
11049 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
11050 S.Diag(C->getLocation(), diag::note_which_delegates_to);
11051 }
11052 }
11053
11054 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
11055 Invalid.insert(*CI);
11056 Current.clear();
11057 } else {
11058 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
11059 }
11060}
11061
11062
Alexis Hunt6118d662011-05-04 05:57:24 +000011063void Sema::CheckDelegatingCtorCycles() {
11064 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
11065
Alexis Hunt27a761d2011-05-04 23:29:54 +000011066 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
11067 CE = Current.end();
Alexis Hunt6118d662011-05-04 05:57:24 +000011068
Douglas Gregorbae31202011-07-27 21:57:17 +000011069 for (DelegatingCtorDeclsType::iterator
11070 I = DelegatingCtorDecls.begin(ExternalSource),
Alexis Hunt27a761d2011-05-04 23:29:54 +000011071 E = DelegatingCtorDecls.end();
11072 I != E; ++I) {
11073 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
Alexis Hunt6118d662011-05-04 05:57:24 +000011074 }
Alexis Hunt27a761d2011-05-04 23:29:54 +000011075
11076 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
11077 (*CI)->setInvalidDecl();
Alexis Hunt6118d662011-05-04 05:57:24 +000011078}
Peter Collingbourne7277fe82011-10-02 23:49:40 +000011079
11080/// IdentifyCUDATarget - Determine the CUDA compilation target for this function
11081Sema::CUDAFunctionTarget Sema::IdentifyCUDATarget(const FunctionDecl *D) {
11082 // Implicitly declared functions (e.g. copy constructors) are
11083 // __host__ __device__
11084 if (D->isImplicit())
11085 return CFT_HostDevice;
11086
11087 if (D->hasAttr<CUDAGlobalAttr>())
11088 return CFT_Global;
11089
11090 if (D->hasAttr<CUDADeviceAttr>()) {
11091 if (D->hasAttr<CUDAHostAttr>())
11092 return CFT_HostDevice;
11093 else
11094 return CFT_Device;
11095 }
11096
11097 return CFT_Host;
11098}
11099
11100bool Sema::CheckCUDATarget(CUDAFunctionTarget CallerTarget,
11101 CUDAFunctionTarget CalleeTarget) {
11102 // CUDA B.1.1 "The __device__ qualifier declares a function that is...
11103 // Callable from the device only."
11104 if (CallerTarget == CFT_Host && CalleeTarget == CFT_Device)
11105 return true;
11106
11107 // CUDA B.1.2 "The __global__ qualifier declares a function that is...
11108 // Callable from the host only."
11109 // CUDA B.1.3 "The __host__ qualifier declares a function that is...
11110 // Callable from the host only."
11111 if ((CallerTarget == CFT_Device || CallerTarget == CFT_Global) &&
11112 (CalleeTarget == CFT_Host || CalleeTarget == CFT_Global))
11113 return true;
11114
11115 if (CallerTarget == CFT_HostDevice && CalleeTarget != CFT_HostDevice)
11116 return true;
11117
11118 return false;
11119}