blob: 9dbca64639fe789ddc42dc8fc9bbde7032b97d5f [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"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Alexis Huntc5575cc2011-02-26 19:13:13 +000024#include "clang/AST/ExprCXX.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000025#include "clang/AST/RecordLayout.h"
26#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000027#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000028#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000029#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000031#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000032#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000033#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000034#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000035#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000036#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000037
38using namespace clang;
39
Chris Lattner58258242008-04-10 02:22:51 +000040//===----------------------------------------------------------------------===//
41// CheckDefaultArgumentVisitor
42//===----------------------------------------------------------------------===//
43
Chris Lattnerb0d38442008-04-12 23:52:44 +000044namespace {
45 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
46 /// the default argument of a parameter to determine whether it
47 /// contains any ill-formed subexpressions. For example, this will
48 /// diagnose the use of local variables or parameters within the
49 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000050 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000051 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000052 Expr *DefaultArg;
53 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000054
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 public:
Mike Stump11289f42009-09-09 15:08:12 +000056 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000057 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000058
Chris Lattnerb0d38442008-04-12 23:52:44 +000059 bool VisitExpr(Expr *Node);
60 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000061 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000062 };
Chris Lattner58258242008-04-10 02:22:51 +000063
Chris Lattnerb0d38442008-04-12 23:52:44 +000064 /// VisitExpr - Visit all of the children of this expression.
65 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
66 bool IsInvalid = false;
John McCall8322c3a2011-02-13 04:07:26 +000067 for (Stmt::child_range I = Node->children(); I; ++I)
Chris Lattner574dee62008-07-26 22:17:49 +000068 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
John McCall1c9c3fd2010-10-15 04:57:14 +000093 if (VDecl->isLocalVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Nico Weber20c9f1d2010-11-28 22:53:37 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
John McCallacf0ee52010-10-08 02:01:28 +0000139 CheckImplicitConversions(Arg, EqualLoc);
John McCall5d413782010-12-06 08:20:24 +0000140 Arg = MaybeCreateExprWithCleanups(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 // Okay: add the default argument to the parameter
143 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000144
Douglas Gregor758cb672010-10-12 18:23:32 +0000145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations.find(Param);
149 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
150 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
151 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
152
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations.erase(InstPos);
155 }
156
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000157 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000158}
159
Chris Lattner58258242008-04-10 02:22:51 +0000160/// ActOnParamDefaultArgument - Check whether the default argument
161/// provided for a function parameter is well-formed. If so, attach it
162/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000163void
John McCall48871652010-08-21 09:40:31 +0000164Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000165 Expr *DefaultArg) {
166 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000167 return;
Mike Stump11289f42009-09-09 15:08:12 +0000168
John McCall48871652010-08-21 09:40:31 +0000169 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000170 UnparsedDefaultArgLocs.erase(Param);
171
Chris Lattner199abbc2008-04-08 05:04:30 +0000172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000174 Diag(EqualLoc, diag::err_param_default_argument)
175 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000176 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000177 return;
178 }
179
Douglas Gregor6ff1fbf2010-12-16 08:48:57 +0000180 // Check for unexpanded parameter packs.
181 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
182 Param->setInvalidDecl();
183 return;
184 }
185
Anders Carlssonf1c26952009-08-25 01:02:06 +0000186 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000187 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
188 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000189 Param->setInvalidDecl();
190 return;
191 }
Mike Stump11289f42009-09-09 15:08:12 +0000192
John McCallb268a282010-08-23 23:25:46 +0000193 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000194}
195
Douglas Gregor58354032008-12-24 00:01:03 +0000196/// ActOnParamUnparsedDefaultArgument - We've seen a default
197/// argument for a function parameter, but we can't parse it yet
198/// because we're inside a class definition. Note that this default
199/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000200void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000201 SourceLocation EqualLoc,
202 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000203 if (!param)
204 return;
Mike Stump11289f42009-09-09 15:08:12 +0000205
John McCall48871652010-08-21 09:40:31 +0000206 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000207 if (Param)
208 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000209
Anders Carlsson84613c42009-06-12 16:51:40 +0000210 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000211}
212
Douglas Gregor4d87df52008-12-16 21:30:33 +0000213/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000215void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000216 if (!param)
217 return;
Mike Stump11289f42009-09-09 15:08:12 +0000218
John McCall48871652010-08-21 09:40:31 +0000219 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000220
Anders Carlsson84613c42009-06-12 16:51:40 +0000221 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000222
Anders Carlsson84613c42009-06-12 16:51:40 +0000223 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000224}
225
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000226/// CheckExtraCXXDefaultArguments - Check for any extra default
227/// arguments in the declarator, which is not a function declaration
228/// or definition and therefore is not permitted to have default
229/// arguments. This routine should be invoked for every declarator
230/// that is not a function declaration or definition.
231void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
232 // C++ [dcl.fct.default]p3
233 // A default argument expression shall be specified only in the
234 // parameter-declaration-clause of a function declaration or in a
235 // template-parameter (14.1). It shall not be specified for a
236 // parameter pack. If it is specified in a
237 // parameter-declaration-clause, it shall not occur within a
238 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000239 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000240 DeclaratorChunk &chunk = D.getTypeObject(i);
241 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000242 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
243 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000244 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000245 if (Param->hasUnparsedDefaultArg()) {
246 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000247 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
248 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
249 delete Toks;
250 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000251 } else if (Param->getDefaultArg()) {
252 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
253 << Param->getDefaultArg()->getSourceRange();
254 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000255 }
256 }
257 }
258 }
259}
260
Chris Lattner199abbc2008-04-08 05:04:30 +0000261// MergeCXXFunctionDecl - Merge two declarations of the same C++
262// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000263// type. Subroutine of MergeFunctionDecl. Returns true if there was an
264// error, false otherwise.
265bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
266 bool Invalid = false;
267
Chris Lattner199abbc2008-04-08 05:04:30 +0000268 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 // For non-template functions, default arguments can be added in
270 // later declarations of a function in the same
271 // scope. Declarations in different scopes have completely
272 // distinct sets of default arguments. That is, declarations in
273 // inner scopes do not acquire default arguments from
274 // declarations in outer scopes, and vice versa. In a given
275 // function declaration, all parameters subsequent to a
276 // parameter with a default argument shall have default
277 // arguments supplied in this or previous declarations. A
278 // default argument shall not be redefined by a later
279 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000280 //
281 // C++ [dcl.fct.default]p6:
282 // Except for member functions of class templates, the default arguments
283 // in a member function definition that appears outside of the class
284 // definition are added to the set of default arguments provided by the
285 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000286 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
287 ParmVarDecl *OldParam = Old->getParamDecl(p);
288 ParmVarDecl *NewParam = New->getParamDecl(p);
289
Douglas Gregorc732aba2009-09-11 18:44:32 +0000290 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
292 // hint here. Alternatively, we could walk the type-source information
293 // for NewParam to find the last source location in the type... but it
294 // isn't worth the effort right now. This is the kind of test case that
295 // is hard to get right:
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000296 unsigned DiagDefaultParamID =
297 diag::err_param_default_argument_redefinition;
298
299 // MSVC accepts that default parameters be redefined for member functions
300 // of template class. The new default parameter's value is ignored.
301 Invalid = true;
302 if (getLangOptions().Microsoft) {
303 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
304 if (MD && MD->getParent()->getDescribedClassTemplate()) {
305 DiagDefaultParamID = diag::war_param_default_argument_redefinition;
306 Invalid = false;
307 }
308 }
Douglas Gregor08dc5842010-01-13 00:12:48 +0000309
310 // int f(int);
311 // void g(int (*fp)(int) = f);
312 // void g(int (*fp)(int) = &f);
Francois Pichet53fe2bb2011-04-10 03:03:52 +0000313 Diag(NewParam->getLocation(), DiagDefaultParamID)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000314 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000315
316 // Look for the function declaration where the default argument was
317 // actually written, which may be a declaration prior to Old.
318 for (FunctionDecl *Older = Old->getPreviousDeclaration();
319 Older; Older = Older->getPreviousDeclaration()) {
320 if (!Older->getParamDecl(p)->hasDefaultArg())
321 break;
322
323 OldParam = Older->getParamDecl(p);
324 }
325
326 Diag(OldParam->getLocation(), diag::note_previous_definition)
327 << OldParam->getDefaultArgRange();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000328 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000329 // Merge the old default argument into the new parameter.
330 // It's important to use getInit() here; getDefaultArg()
John McCall5d413782010-12-06 08:20:24 +0000331 // strips off any top-level ExprWithCleanups.
John McCallf3cd6652010-03-12 18:31:32 +0000332 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000333 if (OldParam->hasUninstantiatedDefaultArg())
334 NewParam->setUninstantiatedDefaultArg(
335 OldParam->getUninstantiatedDefaultArg());
336 else
John McCalle61b02b2010-05-04 01:53:42 +0000337 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000338 } else if (NewParam->hasDefaultArg()) {
339 if (New->getDescribedFunctionTemplate()) {
340 // Paragraph 4, quoted above, only applies to non-template functions.
341 Diag(NewParam->getLocation(),
342 diag::err_param_default_argument_template_redecl)
343 << NewParam->getDefaultArgRange();
344 Diag(Old->getLocation(), diag::note_template_prev_declaration)
345 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000346 } else if (New->getTemplateSpecializationKind()
347 != TSK_ImplicitInstantiation &&
348 New->getTemplateSpecializationKind() != TSK_Undeclared) {
349 // C++ [temp.expr.spec]p21:
350 // Default function arguments shall not be specified in a declaration
351 // or a definition for one of the following explicit specializations:
352 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000353 // - the explicit specialization of a member function template;
354 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000355 // template where the class template specialization to which the
356 // member function specialization belongs is implicitly
357 // instantiated.
358 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
359 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
360 << New->getDeclName()
361 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000362 } else if (New->getDeclContext()->isDependentContext()) {
363 // C++ [dcl.fct.default]p6 (DR217):
364 // Default arguments for a member function of a class template shall
365 // be specified on the initial declaration of the member function
366 // within the class template.
367 //
368 // Reading the tea leaves a bit in DR217 and its reference to DR205
369 // leads me to the conclusion that one cannot add default function
370 // arguments for an out-of-line definition of a member function of a
371 // dependent type.
372 int WhichKind = 2;
373 if (CXXRecordDecl *Record
374 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
375 if (Record->getDescribedClassTemplate())
376 WhichKind = 0;
377 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
378 WhichKind = 1;
379 else
380 WhichKind = 2;
381 }
382
383 Diag(NewParam->getLocation(),
384 diag::err_param_default_argument_member_template_redecl)
385 << WhichKind
386 << NewParam->getDefaultArgRange();
387 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000388 }
389 }
390
Douglas Gregorf40863c2010-02-12 07:32:17 +0000391 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000392 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000393
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000394 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000395}
396
Sebastian Redlfa453cf2011-03-12 11:50:43 +0000397/// \brief Merge the exception specifications of two variable declarations.
398///
399/// This is called when there's a redeclaration of a VarDecl. The function
400/// checks if the redeclaration might have an exception specification and
401/// validates compatibility and merges the specs if necessary.
402void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
403 // Shortcut if exceptions are disabled.
404 if (!getLangOptions().CXXExceptions)
405 return;
406
407 assert(Context.hasSameType(New->getType(), Old->getType()) &&
408 "Should only be called if types are otherwise the same.");
409
410 QualType NewType = New->getType();
411 QualType OldType = Old->getType();
412
413 // We're only interested in pointers and references to functions, as well
414 // as pointers to member functions.
415 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
416 NewType = R->getPointeeType();
417 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
418 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
419 NewType = P->getPointeeType();
420 OldType = OldType->getAs<PointerType>()->getPointeeType();
421 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
422 NewType = M->getPointeeType();
423 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
424 }
425
426 if (!NewType->isFunctionProtoType())
427 return;
428
429 // There's lots of special cases for functions. For function pointers, system
430 // libraries are hopefully not as broken so that we don't need these
431 // workarounds.
432 if (CheckEquivalentExceptionSpec(
433 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
434 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
435 New->setInvalidDecl();
436 }
437}
438
Chris Lattner199abbc2008-04-08 05:04:30 +0000439/// CheckCXXDefaultArguments - Verify that the default arguments for a
440/// function declaration are well-formed according to C++
441/// [dcl.fct.default].
442void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
443 unsigned NumParams = FD->getNumParams();
444 unsigned p;
445
446 // Find first parameter with a default argument
447 for (p = 0; p < NumParams; ++p) {
448 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000449 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000450 break;
451 }
452
453 // C++ [dcl.fct.default]p4:
454 // In a given function declaration, all parameters
455 // subsequent to a parameter with a default argument shall
456 // have default arguments supplied in this or previous
457 // declarations. A default argument shall not be redefined
458 // by a later declaration (not even to the same value).
459 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000460 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000461 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000462 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000463 if (Param->isInvalidDecl())
464 /* We already complained about this parameter. */;
465 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000466 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000467 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000468 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000469 else
Mike Stump11289f42009-09-09 15:08:12 +0000470 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000471 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000472
Chris Lattner199abbc2008-04-08 05:04:30 +0000473 LastMissingDefaultArg = p;
474 }
475 }
476
477 if (LastMissingDefaultArg > 0) {
478 // Some default arguments were missing. Clear out all of the
479 // default arguments up to (and including) the last missing
480 // default argument, so that we leave the function parameters
481 // in a semantically valid state.
482 for (p = 0; p <= LastMissingDefaultArg; ++p) {
483 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000484 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000485 Param->setDefaultArg(0);
486 }
487 }
488 }
489}
Douglas Gregor556877c2008-04-13 21:30:24 +0000490
Douglas Gregor61956c42008-10-31 09:07:45 +0000491/// isCurrentClassName - Determine whether the identifier II is the
492/// name of the class type currently being defined. In the case of
493/// nested classes, this will only return true if II is the name of
494/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000495bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
496 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000497 assert(getLangOptions().CPlusPlus && "No class names in C!");
498
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000499 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000500 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000501 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000502 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
503 } else
504 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
505
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000506 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000507 return &II == CurDecl->getIdentifier();
508 else
509 return false;
510}
511
Mike Stump11289f42009-09-09 15:08:12 +0000512/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000513///
514/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
515/// and returns NULL otherwise.
516CXXBaseSpecifier *
517Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
518 SourceRange SpecifierRange,
519 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000520 TypeSourceInfo *TInfo,
521 SourceLocation EllipsisLoc) {
Nick Lewycky19b9f952010-07-26 16:56:01 +0000522 QualType BaseType = TInfo->getType();
523
Douglas Gregor463421d2009-03-03 04:44:36 +0000524 // C++ [class.union]p1:
525 // A union shall not have base classes.
526 if (Class->isUnion()) {
527 Diag(Class->getLocation(), diag::err_base_clause_on_union)
528 << SpecifierRange;
529 return 0;
530 }
531
Douglas Gregor752a5952011-01-03 22:36:02 +0000532 if (EllipsisLoc.isValid() &&
533 !TInfo->getType()->containsUnexpandedParameterPack()) {
534 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
535 << TInfo->getTypeLoc().getSourceRange();
536 EllipsisLoc = SourceLocation();
537 }
538
Douglas Gregor463421d2009-03-03 04:44:36 +0000539 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000540 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000541 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000542 Access, TInfo, EllipsisLoc);
Nick Lewycky19b9f952010-07-26 16:56:01 +0000543
544 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000545
546 // Base specifiers must be record types.
547 if (!BaseType->isRecordType()) {
548 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
549 return 0;
550 }
551
552 // C++ [class.union]p1:
553 // A union shall not be used as a base class.
554 if (BaseType->isUnionType()) {
555 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
556 return 0;
557 }
558
559 // C++ [class.derived]p2:
560 // The class-name in a base-specifier shall not be an incompletely
561 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000562 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000563 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000564 << SpecifierRange)) {
565 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000566 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000567 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000568
Eli Friedmanc96d4962009-08-15 21:55:26 +0000569 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000570 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000571 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000572 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000573 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000574 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
575 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000576
Anders Carlsson65c76d32011-03-25 14:55:14 +0000577 // C++ [class]p3:
578 // If a class is marked final and it appears as a base-type-specifier in
579 // base-clause, the program is ill-formed.
Anders Carlsson1eb95962011-01-24 16:26:15 +0000580 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
Anders Carlssonfc1eef42011-01-22 17:51:53 +0000581 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
582 << CXXBaseDecl->getDeclName();
583 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
584 << CXXBaseDecl->getDeclName();
585 return 0;
586 }
587
John McCall3696dcb2010-08-17 07:23:57 +0000588 if (BaseDecl->isInvalidDecl())
589 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000590
591 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000592 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000593 Class->getTagKind() == TTK_Class,
Douglas Gregor752a5952011-01-03 22:36:02 +0000594 Access, TInfo, EllipsisLoc);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000595}
596
Douglas Gregor556877c2008-04-13 21:30:24 +0000597/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
598/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000599/// example:
600/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000601/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000602BaseResult
John McCall48871652010-08-21 09:40:31 +0000603Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000604 bool Virtual, AccessSpecifier Access,
Douglas Gregor752a5952011-01-03 22:36:02 +0000605 ParsedType basetype, SourceLocation BaseLoc,
606 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000607 if (!classdecl)
608 return true;
609
Douglas Gregorc40290e2009-03-09 23:48:35 +0000610 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000611 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000612 if (!Class)
613 return true;
614
Nick Lewycky19b9f952010-07-26 16:56:01 +0000615 TypeSourceInfo *TInfo = 0;
616 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor506bd562010-12-13 22:49:22 +0000617
Douglas Gregor752a5952011-01-03 22:36:02 +0000618 if (EllipsisLoc.isInvalid() &&
619 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
Douglas Gregor506bd562010-12-13 22:49:22 +0000620 UPPC_BaseType))
621 return true;
Douglas Gregor752a5952011-01-03 22:36:02 +0000622
Douglas Gregor463421d2009-03-03 04:44:36 +0000623 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Douglas Gregor752a5952011-01-03 22:36:02 +0000624 Virtual, Access, TInfo,
625 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +0000626 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000627
Douglas Gregor463421d2009-03-03 04:44:36 +0000628 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000629}
Douglas Gregor556877c2008-04-13 21:30:24 +0000630
Douglas Gregor463421d2009-03-03 04:44:36 +0000631/// \brief Performs the actual work of attaching the given base class
632/// specifiers to a C++ class.
633bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
634 unsigned NumBases) {
635 if (NumBases == 0)
636 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000637
638 // Used to keep track of which base types we have already seen, so
639 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000640 // that the key is always the unqualified canonical type of the base
641 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000642 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
643
644 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000645 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000646 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000647 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000648 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000649 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000650 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000651 if (!Class->hasObjectMember()) {
652 if (const RecordType *FDTTy =
653 NewBaseType.getTypePtr()->getAs<RecordType>())
654 if (FDTTy->getDecl()->hasObjectMember())
655 Class->setHasObjectMember(true);
656 }
657
Douglas Gregor29a92472008-10-22 17:49:05 +0000658 if (KnownBaseTypes[NewBaseType]) {
659 // C++ [class.mi]p3:
660 // A class shall not be specified as a direct base class of a
661 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000662 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000663 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000664 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000665 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000666
667 // Delete the duplicate base class specifier; we're going to
668 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000669 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000670
671 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000672 } else {
673 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000674 KnownBaseTypes[NewBaseType] = Bases[idx];
675 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000676 }
677 }
678
679 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000680 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000681
682 // Delete the remaining (good) base class specifiers, since their
683 // data has been copied into the CXXRecordDecl.
684 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000685 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000686
687 return Invalid;
688}
689
690/// ActOnBaseSpecifiers - Attach the given base specifiers to the
691/// class, after checking whether there are any duplicate base
692/// classes.
John McCall48871652010-08-21 09:40:31 +0000693void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000694 unsigned NumBases) {
695 if (!ClassDecl || !Bases || !NumBases)
696 return;
697
698 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000699 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000700 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000701}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000702
John McCalle78aac42010-03-10 03:28:59 +0000703static CXXRecordDecl *GetClassForType(QualType T) {
704 if (const RecordType *RT = T->getAs<RecordType>())
705 return cast<CXXRecordDecl>(RT->getDecl());
706 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
707 return ICT->getDecl();
708 else
709 return 0;
710}
711
Douglas Gregor36d1b142009-10-06 17:59:45 +0000712/// \brief Determine whether the type \p Derived is a C++ class that is
713/// derived from the type \p Base.
714bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
715 if (!getLangOptions().CPlusPlus)
716 return false;
John McCalle78aac42010-03-10 03:28:59 +0000717
718 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
719 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000720 return false;
721
John McCalle78aac42010-03-10 03:28:59 +0000722 CXXRecordDecl *BaseRD = GetClassForType(Base);
723 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000724 return false;
725
John McCall67da35c2010-02-04 22:26:26 +0000726 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
727 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000728}
729
730/// \brief Determine whether the type \p Derived is a C++ class that is
731/// derived from the type \p Base.
732bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
733 if (!getLangOptions().CPlusPlus)
734 return false;
735
John McCalle78aac42010-03-10 03:28:59 +0000736 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
737 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000738 return false;
739
John McCalle78aac42010-03-10 03:28:59 +0000740 CXXRecordDecl *BaseRD = GetClassForType(Base);
741 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000742 return false;
743
Douglas Gregor36d1b142009-10-06 17:59:45 +0000744 return DerivedRD->isDerivedFrom(BaseRD, Paths);
745}
746
Anders Carlssona70cff62010-04-24 19:06:50 +0000747void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000748 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000749 assert(BasePathArray.empty() && "Base path array must be empty!");
750 assert(Paths.isRecordingPaths() && "Must record paths!");
751
752 const CXXBasePath &Path = Paths.front();
753
754 // We first go backward and check if we have a virtual base.
755 // FIXME: It would be better if CXXBasePath had the base specifier for
756 // the nearest virtual base.
757 unsigned Start = 0;
758 for (unsigned I = Path.size(); I != 0; --I) {
759 if (Path[I - 1].Base->isVirtual()) {
760 Start = I - 1;
761 break;
762 }
763 }
764
765 // Now add all bases.
766 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000767 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000768}
769
Douglas Gregor88d292c2010-05-13 16:44:06 +0000770/// \brief Determine whether the given base path includes a virtual
771/// base class.
John McCallcf142162010-08-07 06:22:56 +0000772bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
773 for (CXXCastPath::const_iterator B = BasePath.begin(),
774 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000775 B != BEnd; ++B)
776 if ((*B)->isVirtual())
777 return true;
778
779 return false;
780}
781
Douglas Gregor36d1b142009-10-06 17:59:45 +0000782/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
783/// conversion (where Derived and Base are class types) is
784/// well-formed, meaning that the conversion is unambiguous (and
785/// that all of the base classes are accessible). Returns true
786/// and emits a diagnostic if the code is ill-formed, returns false
787/// otherwise. Loc is the location where this routine should point to
788/// if there is an error, and Range is the source range to highlight
789/// if there is an error.
790bool
791Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000792 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000793 unsigned AmbigiousBaseConvID,
794 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000795 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000796 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000797 // First, determine whether the path from Derived to Base is
798 // ambiguous. This is slightly more expensive than checking whether
799 // the Derived to Base conversion exists, because here we need to
800 // explore multiple paths to determine if there is an ambiguity.
801 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
802 /*DetectVirtual=*/false);
803 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
804 assert(DerivationOkay &&
805 "Can only be used with a derived-to-base conversion");
806 (void)DerivationOkay;
807
808 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000809 if (InaccessibleBaseID) {
810 // Check that the base class can be accessed.
811 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
812 InaccessibleBaseID)) {
813 case AR_inaccessible:
814 return true;
815 case AR_accessible:
816 case AR_dependent:
817 case AR_delayed:
818 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000819 }
John McCall5b0829a2010-02-10 09:31:12 +0000820 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000821
822 // Build a base path if necessary.
823 if (BasePath)
824 BuildBasePathArray(Paths, *BasePath);
825 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000826 }
827
828 // We know that the derived-to-base conversion is ambiguous, and
829 // we're going to produce a diagnostic. Perform the derived-to-base
830 // search just one more time to compute all of the possible paths so
831 // that we can print them out. This is more expensive than any of
832 // the previous derived-to-base checks we've done, but at this point
833 // performance isn't as much of an issue.
834 Paths.clear();
835 Paths.setRecordingPaths(true);
836 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
837 assert(StillOkay && "Can only be used with a derived-to-base conversion");
838 (void)StillOkay;
839
840 // Build up a textual representation of the ambiguous paths, e.g.,
841 // D -> B -> A, that will be used to illustrate the ambiguous
842 // conversions in the diagnostic. We only print one of the paths
843 // to each base class subobject.
844 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
845
846 Diag(Loc, AmbigiousBaseConvID)
847 << Derived << Base << PathDisplayStr << Range << Name;
848 return true;
849}
850
851bool
852Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000853 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000854 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000855 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000856 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000857 IgnoreAccess ? 0
858 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000859 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000860 Loc, Range, DeclarationName(),
861 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000862}
863
864
865/// @brief Builds a string representing ambiguous paths from a
866/// specific derived class to different subobjects of the same base
867/// class.
868///
869/// This function builds a string that can be used in error messages
870/// to show the different paths that one can take through the
871/// inheritance hierarchy to go from the derived class to different
872/// subobjects of a base class. The result looks something like this:
873/// @code
874/// struct D -> struct B -> struct A
875/// struct D -> struct C -> struct A
876/// @endcode
877std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
878 std::string PathDisplayStr;
879 std::set<unsigned> DisplayedPaths;
880 for (CXXBasePaths::paths_iterator Path = Paths.begin();
881 Path != Paths.end(); ++Path) {
882 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
883 // We haven't displayed a path to this particular base
884 // class subobject yet.
885 PathDisplayStr += "\n ";
886 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
887 for (CXXBasePath::const_iterator Element = Path->begin();
888 Element != Path->end(); ++Element)
889 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
890 }
891 }
892
893 return PathDisplayStr;
894}
895
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000896//===----------------------------------------------------------------------===//
897// C++ class member Handling
898//===----------------------------------------------------------------------===//
899
Abramo Bagnarad7340582010-06-05 05:09:32 +0000900/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000901Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
902 SourceLocation ASLoc,
903 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000904 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000905 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000906 ASLoc, ColonLoc);
907 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000908 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000909}
910
Anders Carlssonfd835532011-01-20 05:57:14 +0000911/// CheckOverrideControl - Check C++0x override control semantics.
Anders Carlssonc87f8612011-01-20 06:29:02 +0000912void Sema::CheckOverrideControl(const Decl *D) {
Anders Carlssonfd835532011-01-20 05:57:14 +0000913 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
914 if (!MD || !MD->isVirtual())
915 return;
916
Anders Carlssonfa8e5d32011-01-20 06:33:26 +0000917 if (MD->isDependentContext())
918 return;
919
Anders Carlssonfd835532011-01-20 05:57:14 +0000920 // C++0x [class.virtual]p3:
921 // If a virtual function is marked with the virt-specifier override and does
922 // not override a member function of a base class,
923 // the program is ill-formed.
924 bool HasOverriddenMethods =
925 MD->begin_overridden_methods() != MD->end_overridden_methods();
Anders Carlsson1eb95962011-01-24 16:26:15 +0000926 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
Anders Carlssonc87f8612011-01-20 06:29:02 +0000927 Diag(MD->getLocation(),
Anders Carlssonfd835532011-01-20 05:57:14 +0000928 diag::err_function_marked_override_not_overriding)
929 << MD->getDeclName();
930 return;
931 }
932}
933
Anders Carlsson3f610c72011-01-20 16:25:36 +0000934/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
935/// function overrides a virtual member function marked 'final', according to
936/// C++0x [class.virtual]p3.
937bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
938 const CXXMethodDecl *Old) {
Anders Carlsson1eb95962011-01-24 16:26:15 +0000939 if (!Old->hasAttr<FinalAttr>())
Anders Carlsson19588aa2011-01-23 21:07:30 +0000940 return false;
941
942 Diag(New->getLocation(), diag::err_final_function_overridden)
943 << New->getDeclName();
944 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
945 return true;
Anders Carlsson3f610c72011-01-20 16:25:36 +0000946}
947
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000948/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
949/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
950/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000951/// any.
John McCall48871652010-08-21 09:40:31 +0000952Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000953Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000954 MultiTemplateParamsArg TemplateParameterLists,
Anders Carlssondb36b802011-01-20 03:57:25 +0000955 ExprTy *BW, const VirtSpecifiers &VS,
956 ExprTy *InitExpr, bool IsDefinition,
Sebastian Redld6f78502009-11-24 23:38:44 +0000957 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000958 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000959 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
960 DeclarationName Name = NameInfo.getName();
961 SourceLocation Loc = NameInfo.getLoc();
Douglas Gregor23ab7452010-11-09 03:31:16 +0000962
963 // For anonymous bitfields, the location should point to the type.
964 if (Loc.isInvalid())
965 Loc = D.getSourceRange().getBegin();
966
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000967 Expr *BitWidth = static_cast<Expr*>(BW);
968 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000969
John McCallb1cd7da2010-06-04 08:34:12 +0000970 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000971 assert(!DS.isFriendSpecified());
972
John McCallb1cd7da2010-06-04 08:34:12 +0000973 bool isFunc = false;
974 if (D.isFunctionDeclarator())
975 isFunc = true;
976 else if (D.getNumTypeObjects() == 0 &&
977 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000978 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000979 isFunc = TDType->isFunctionType();
980 }
981
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000982 // C++ 9.2p6: A member shall not be declared to have automatic storage
983 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000984 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
985 // data members and cannot be applied to names declared const or static,
986 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000987 switch (DS.getStorageClassSpec()) {
988 case DeclSpec::SCS_unspecified:
989 case DeclSpec::SCS_typedef:
990 case DeclSpec::SCS_static:
991 // FALL THROUGH.
992 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000993 case DeclSpec::SCS_mutable:
994 if (isFunc) {
995 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000996 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000997 else
Chris Lattner3b054132008-11-19 05:08:23 +0000998 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000999
Sebastian Redl8071edb2008-11-17 23:24:37 +00001000 // FIXME: It would be nicer if the keyword was ignored only for this
1001 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001002 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001003 }
1004 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001005 default:
1006 if (DS.getStorageClassSpecLoc().isValid())
1007 Diag(DS.getStorageClassSpecLoc(),
1008 diag::err_storageclass_invalid_for_member);
1009 else
1010 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1011 D.getMutableDeclSpec().ClearStorageClassSpecs();
1012 }
1013
Sebastian Redlccdfaba2008-11-14 23:42:31 +00001014 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1015 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +00001016 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001017
1018 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +00001019 if (isInstField) {
Douglas Gregora007d362010-10-13 22:19:53 +00001020 CXXScopeSpec &SS = D.getCXXScopeSpec();
1021
1022
1023 if (SS.isSet() && !SS.isInvalid()) {
1024 // The user provided a superfluous scope specifier inside a class
1025 // definition:
1026 //
1027 // class X {
1028 // int X::member;
1029 // };
1030 DeclContext *DC = 0;
1031 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1032 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1033 << Name << FixItHint::CreateRemoval(SS.getRange());
1034 else
1035 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1036 << Name << SS.getRange();
1037
1038 SS.clear();
1039 }
1040
Douglas Gregor3447e762009-08-20 22:52:58 +00001041 // FIXME: Check for template parameters!
Douglas Gregorc4356532010-12-16 00:46:58 +00001042 // FIXME: Check that the name is an identifier!
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001043 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1044 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +00001045 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +00001046 } else {
John McCall48871652010-08-21 09:40:31 +00001047 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +00001048 if (!Member) {
John McCall48871652010-08-21 09:40:31 +00001049 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +00001050 }
Chris Lattnerd26760a2009-03-05 23:01:03 +00001051
1052 // Non-instance-fields can't have a bitfield.
1053 if (BitWidth) {
1054 if (Member->isInvalidDecl()) {
1055 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +00001056 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +00001057 // C++ 9.6p3: A bit-field shall not be a static member.
1058 // "static member 'A' cannot be a bit-field"
1059 Diag(Loc, diag::err_static_not_bitfield)
1060 << Name << BitWidth->getSourceRange();
1061 } else if (isa<TypedefDecl>(Member)) {
1062 // "typedef member 'x' cannot be a bit-field"
1063 Diag(Loc, diag::err_typedef_not_bitfield)
1064 << Name << BitWidth->getSourceRange();
1065 } else {
1066 // A function typedef ("typedef int f(); f a;").
1067 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1068 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +00001069 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +00001070 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +00001071 }
Mike Stump11289f42009-09-09 15:08:12 +00001072
Chris Lattnerd26760a2009-03-05 23:01:03 +00001073 BitWidth = 0;
1074 Member->setInvalidDecl();
1075 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +00001076
1077 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +00001078
Douglas Gregor3447e762009-08-20 22:52:58 +00001079 // If we have declared a member function template, set the access of the
1080 // templated declaration as well.
1081 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1082 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +00001083 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001084
Anders Carlsson13a69102011-01-20 04:34:22 +00001085 if (VS.isOverrideSpecified()) {
1086 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1087 if (!MD || !MD->isVirtual()) {
1088 Diag(Member->getLocStart(),
1089 diag::override_keyword_only_allowed_on_virtual_member_functions)
1090 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001091 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001092 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001093 }
1094 if (VS.isFinalSpecified()) {
1095 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1096 if (!MD || !MD->isVirtual()) {
1097 Diag(Member->getLocStart(),
1098 diag::override_keyword_only_allowed_on_virtual_member_functions)
1099 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
Anders Carlssonfd835532011-01-20 05:57:14 +00001100 } else
Anders Carlsson1eb95962011-01-24 16:26:15 +00001101 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
Anders Carlsson13a69102011-01-20 04:34:22 +00001102 }
Anders Carlssonfd835532011-01-20 05:57:14 +00001103
Douglas Gregorf2f08062011-03-08 17:10:18 +00001104 if (VS.getLastLocation().isValid()) {
1105 // Update the end location of a method that has a virt-specifiers.
1106 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1107 MD->setRangeEnd(VS.getLastLocation());
1108 }
1109
Anders Carlssonc87f8612011-01-20 06:29:02 +00001110 CheckOverrideControl(Member);
Anders Carlssonfd835532011-01-20 05:57:14 +00001111
Douglas Gregor92751d42008-11-17 22:58:34 +00001112 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001113
Douglas Gregor0c880302009-03-11 23:00:04 +00001114 if (Init)
Richard Smith30482bc2011-02-20 03:19:35 +00001115 AddInitializerToDecl(Member, Init, false,
1116 DS.getTypeSpecType() == DeclSpec::TST_auto);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001117 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +00001118 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001119
Richard Smithb2bc2e62011-02-21 20:05:19 +00001120 FinalizeDeclaration(Member);
1121
John McCall25849ca2011-02-15 07:12:36 +00001122 if (isInstField)
Douglas Gregor91f84212008-12-11 16:49:14 +00001123 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +00001124 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001125}
1126
Douglas Gregor15e77a22009-12-31 09:10:24 +00001127/// \brief Find the direct and/or virtual base specifiers that
1128/// correspond to the given base type, for use in base initialization
1129/// within a constructor.
1130static bool FindBaseInitializer(Sema &SemaRef,
1131 CXXRecordDecl *ClassDecl,
1132 QualType BaseType,
1133 const CXXBaseSpecifier *&DirectBaseSpec,
1134 const CXXBaseSpecifier *&VirtualBaseSpec) {
1135 // First, check for a direct base class.
1136 DirectBaseSpec = 0;
1137 for (CXXRecordDecl::base_class_const_iterator Base
1138 = ClassDecl->bases_begin();
1139 Base != ClassDecl->bases_end(); ++Base) {
1140 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1141 // We found a direct base of this type. That's what we're
1142 // initializing.
1143 DirectBaseSpec = &*Base;
1144 break;
1145 }
1146 }
1147
1148 // Check for a virtual base class.
1149 // FIXME: We might be able to short-circuit this if we know in advance that
1150 // there are no virtual bases.
1151 VirtualBaseSpec = 0;
1152 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1153 // We haven't found a base yet; search the class hierarchy for a
1154 // virtual base class.
1155 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1156 /*DetectVirtual=*/false);
1157 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1158 BaseType, Paths)) {
1159 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1160 Path != Paths.end(); ++Path) {
1161 if (Path->back().Base->isVirtual()) {
1162 VirtualBaseSpec = Path->back().Base;
1163 break;
1164 }
1165 }
1166 }
1167 }
1168
1169 return DirectBaseSpec || VirtualBaseSpec;
1170}
1171
Douglas Gregore8381c02008-11-05 04:29:56 +00001172/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +00001173MemInitResult
John McCall48871652010-08-21 09:40:31 +00001174Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001175 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001176 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001177 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +00001178 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001179 SourceLocation IdLoc,
1180 SourceLocation LParenLoc,
1181 ExprTy **Args, unsigned NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001182 SourceLocation RParenLoc,
1183 SourceLocation EllipsisLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001184 if (!ConstructorD)
1185 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001186
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001187 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001188
1189 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001190 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001191 if (!Constructor) {
1192 // The user wrote a constructor initializer on a function that is
1193 // not a C++ constructor. Ignore the error for now, because we may
1194 // have more member initializers coming; we'll diagnose it just
1195 // once in ActOnMemInitializers.
1196 return true;
1197 }
1198
1199 CXXRecordDecl *ClassDecl = Constructor->getParent();
1200
1201 // C++ [class.base.init]p2:
1202 // Names in a mem-initializer-id are looked up in the scope of the
Nick Lewycky9331ed82010-11-20 01:29:55 +00001203 // constructor's class and, if not found in that scope, are looked
1204 // up in the scope containing the constructor's definition.
1205 // [Note: if the constructor's class contains a member with the
1206 // same name as a direct or virtual base class of the class, a
1207 // mem-initializer-id naming the member or base class and composed
1208 // of a single identifier refers to the class member. A
Douglas Gregore8381c02008-11-05 04:29:56 +00001209 // mem-initializer-id for the hidden base class may be specified
1210 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001211 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001212 // Look for a member, first.
1213 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001214 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001215 = ClassDecl->lookup(MemberOrBase);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001216 if (Result.first != Result.second) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001217 Member = dyn_cast<FieldDecl>(*Result.first);
Francois Pichet783dd6e2010-11-21 06:08:52 +00001218
Douglas Gregor44e7df62011-01-04 00:32:56 +00001219 if (Member) {
1220 if (EllipsisLoc.isValid())
1221 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1222 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1223
Francois Pichetd583da02010-12-04 09:14:42 +00001224 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001225 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001226 }
1227
Francois Pichetd583da02010-12-04 09:14:42 +00001228 // Handle anonymous union case.
1229 if (IndirectFieldDecl* IndirectField
Douglas Gregor44e7df62011-01-04 00:32:56 +00001230 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1231 if (EllipsisLoc.isValid())
1232 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1233 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1234
Francois Pichetd583da02010-12-04 09:14:42 +00001235 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1236 NumArgs, IdLoc,
1237 LParenLoc, RParenLoc);
Douglas Gregor44e7df62011-01-04 00:32:56 +00001238 }
Francois Pichetd583da02010-12-04 09:14:42 +00001239 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001240 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001241 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001242 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001243 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001244
1245 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001246 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001247 } else {
1248 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1249 LookupParsedName(R, S, &SS);
1250
1251 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1252 if (!TyD) {
1253 if (R.isAmbiguous()) return true;
1254
John McCallda6841b2010-04-09 19:01:14 +00001255 // We don't want access-control diagnostics here.
1256 R.suppressDiagnostics();
1257
Douglas Gregora3b624a2010-01-19 06:46:48 +00001258 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1259 bool NotUnknownSpecialization = false;
1260 DeclContext *DC = computeDeclContext(SS, false);
1261 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1262 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1263
1264 if (!NotUnknownSpecialization) {
1265 // When the scope specifier can refer to a member of an unknown
1266 // specialization, we take it as a type name.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00001267 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1268 SS.getWithLocInContext(Context),
1269 *MemberOrBase, IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001270 if (BaseType.isNull())
1271 return true;
1272
Douglas Gregora3b624a2010-01-19 06:46:48 +00001273 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001274 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001275 }
1276 }
1277
Douglas Gregor15e77a22009-12-31 09:10:24 +00001278 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001279 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001280 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1281 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001282 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001283 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001284 // We have found a non-static data member with a similar
1285 // name to what was typed; complain and initialize that
1286 // member.
1287 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1288 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001289 << FixItHint::CreateReplacement(R.getNameLoc(),
1290 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001291 Diag(Member->getLocation(), diag::note_previous_decl)
1292 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001293
1294 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1295 LParenLoc, RParenLoc);
1296 }
1297 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1298 const CXXBaseSpecifier *DirectBaseSpec;
1299 const CXXBaseSpecifier *VirtualBaseSpec;
1300 if (FindBaseInitializer(*this, ClassDecl,
1301 Context.getTypeDeclType(Type),
1302 DirectBaseSpec, VirtualBaseSpec)) {
1303 // We have found a direct or virtual base class with a
1304 // similar name to what was typed; complain and initialize
1305 // that base class.
1306 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1307 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001308 << FixItHint::CreateReplacement(R.getNameLoc(),
1309 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001310
1311 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1312 : VirtualBaseSpec;
1313 Diag(BaseSpec->getSourceRange().getBegin(),
1314 diag::note_base_class_specified_here)
1315 << BaseSpec->getType()
1316 << BaseSpec->getSourceRange();
1317
Douglas Gregor15e77a22009-12-31 09:10:24 +00001318 TyD = Type;
1319 }
1320 }
1321 }
1322
Douglas Gregora3b624a2010-01-19 06:46:48 +00001323 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001324 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1325 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1326 return true;
1327 }
John McCallb5a0d312009-12-21 10:41:20 +00001328 }
1329
Douglas Gregora3b624a2010-01-19 06:46:48 +00001330 if (BaseType.isNull()) {
1331 BaseType = Context.getTypeDeclType(TyD);
1332 if (SS.isSet()) {
1333 NestedNameSpecifier *Qualifier =
1334 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001335
Douglas Gregora3b624a2010-01-19 06:46:48 +00001336 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001337 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001338 }
John McCallb5a0d312009-12-21 10:41:20 +00001339 }
1340 }
Mike Stump11289f42009-09-09 15:08:12 +00001341
John McCallbcd03502009-12-07 02:54:59 +00001342 if (!TInfo)
1343 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001344
John McCallbcd03502009-12-07 02:54:59 +00001345 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001346 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001347}
1348
John McCalle22a04a2009-11-04 23:02:40 +00001349/// Checks an initializer expression for use of uninitialized fields, such as
1350/// containing the field that is being initialized. Returns true if there is an
1351/// uninitialized field was used an updates the SourceLocation parameter; false
1352/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001353static bool InitExprContainsUninitializedFields(const Stmt *S,
Francois Pichetd583da02010-12-04 09:14:42 +00001354 const ValueDecl *LhsField,
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001355 SourceLocation *L) {
Francois Pichetd583da02010-12-04 09:14:42 +00001356 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1357
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001358 if (isa<CallExpr>(S)) {
1359 // Do not descend into function calls or constructors, as the use
1360 // of an uninitialized field may be valid. One would have to inspect
1361 // the contents of the function/ctor to determine if it is safe or not.
1362 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1363 // may be safe, depending on what the function/ctor does.
1364 return false;
1365 }
1366 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1367 const NamedDecl *RhsField = ME->getMemberDecl();
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001368
1369 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1370 // The member expression points to a static data member.
1371 assert(VD->isStaticDataMember() &&
1372 "Member points to non-static data member!");
Nick Lewycky300524242010-10-06 18:37:39 +00001373 (void)VD;
Anders Carlsson0f7e94f2010-10-06 02:43:25 +00001374 return false;
1375 }
1376
1377 if (isa<EnumConstantDecl>(RhsField)) {
1378 // The member expression points to an enum.
1379 return false;
1380 }
1381
John McCalle22a04a2009-11-04 23:02:40 +00001382 if (RhsField == LhsField) {
1383 // Initializing a field with itself. Throw a warning.
1384 // But wait; there are exceptions!
1385 // Exception #1: The field may not belong to this record.
1386 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001387 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001388 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1389 // Even though the field matches, it does not belong to this record.
1390 return false;
1391 }
1392 // None of the exceptions triggered; return true to indicate an
1393 // uninitialized field was used.
1394 *L = ME->getMemberLoc();
1395 return true;
1396 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00001397 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001398 // sizeof/alignof doesn't reference contents, do not warn.
1399 return false;
1400 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1401 // address-of doesn't reference contents (the pointer may be dereferenced
1402 // in the same expression but it would be rare; and weird).
1403 if (UOE->getOpcode() == UO_AddrOf)
1404 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001405 }
John McCall8322c3a2011-02-13 04:07:26 +00001406 for (Stmt::const_child_range it = S->children(); it; ++it) {
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001407 if (!*it) {
1408 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001409 continue;
1410 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001411 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1412 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001413 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001414 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001415}
1416
John McCallfaf5fb42010-08-26 23:41:50 +00001417MemInitResult
Chandler Carruthd44c3102010-12-06 09:23:57 +00001418Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001419 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001420 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001421 SourceLocation RParenLoc) {
Chandler Carruthd44c3102010-12-06 09:23:57 +00001422 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1423 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1424 assert((DirectMember || IndirectMember) &&
Francois Pichetd583da02010-12-04 09:14:42 +00001425 "Member must be a FieldDecl or IndirectFieldDecl");
1426
Douglas Gregor266bb5f2010-11-05 22:21:31 +00001427 if (Member->isInvalidDecl())
1428 return true;
Chandler Carruthd44c3102010-12-06 09:23:57 +00001429
John McCalle22a04a2009-11-04 23:02:40 +00001430 // Diagnose value-uses of fields to initialize themselves, e.g.
1431 // foo(foo)
1432 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001433 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001434 for (unsigned i = 0; i < NumArgs; ++i) {
1435 SourceLocation L;
1436 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1437 // FIXME: Return true in the case when other fields are used before being
1438 // uninitialized. For example, let this field be the i'th field. When
1439 // initializing the i'th field, throw a warning if any of the >= i'th
1440 // fields are used, as they are not yet initialized.
1441 // Right now we are only handling the case where the i'th field uses
1442 // itself in its initializer.
1443 Diag(L, diag::warn_field_is_uninit);
1444 }
1445 }
1446
Eli Friedman8e1433b2009-07-29 19:44:27 +00001447 bool HasDependentArg = false;
1448 for (unsigned i = 0; i < NumArgs; i++)
1449 HasDependentArg |= Args[i]->isTypeDependent();
1450
Chandler Carruthd44c3102010-12-06 09:23:57 +00001451 Expr *Init;
Eli Friedman9255adf2010-07-24 21:19:15 +00001452 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001453 // Can't check initialization for a member of dependent type or when
1454 // any of the arguments are type-dependent expressions.
Chandler Carruthd44c3102010-12-06 09:23:57 +00001455 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1456 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001457
1458 // Erase any temporaries within this evaluation context; we're not
1459 // going to track them in the AST, since we'll be rebuilding the
1460 // ASTs during template instantiation.
1461 ExprTemporaries.erase(
1462 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1463 ExprTemporaries.end());
Chandler Carruthd44c3102010-12-06 09:23:57 +00001464 } else {
1465 // Initialize the member.
1466 InitializedEntity MemberEntity =
1467 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1468 : InitializedEntity::InitializeMember(IndirectMember, 0);
1469 InitializationKind Kind =
1470 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
John McCallacf0ee52010-10-08 02:01:28 +00001471
Chandler Carruthd44c3102010-12-06 09:23:57 +00001472 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1473
1474 ExprResult MemberInit =
1475 InitSeq.Perform(*this, MemberEntity, Kind,
1476 MultiExprArg(*this, Args, NumArgs), 0);
1477 if (MemberInit.isInvalid())
1478 return true;
1479
1480 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1481
1482 // C++0x [class.base.init]p7:
1483 // The initialization of each base and member constitutes a
1484 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001485 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Chandler Carruthd44c3102010-12-06 09:23:57 +00001486 if (MemberInit.isInvalid())
1487 return true;
1488
1489 // If we are in a dependent context, template instantiation will
1490 // perform this type-checking again. Just save the arguments that we
1491 // received in a ParenListExpr.
1492 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1493 // of the information that we have about the member
1494 // initializer. However, deconstructing the ASTs is a dicey process,
1495 // and this approach is far more likely to get the corner cases right.
1496 if (CurContext->isDependentContext())
1497 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1498 RParenLoc);
1499 else
1500 Init = MemberInit.get();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001501 }
1502
Chandler Carruthd44c3102010-12-06 09:23:57 +00001503 if (DirectMember) {
Alexis Hunt1d792652011-01-08 20:30:50 +00001504 return new (Context) CXXCtorInitializer(Context, DirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001505 IdLoc, LParenLoc, Init,
1506 RParenLoc);
1507 } else {
Alexis Hunt1d792652011-01-08 20:30:50 +00001508 return new (Context) CXXCtorInitializer(Context, IndirectMember,
Chandler Carruthd44c3102010-12-06 09:23:57 +00001509 IdLoc, LParenLoc, Init,
1510 RParenLoc);
1511 }
Eli Friedman8e1433b2009-07-29 19:44:27 +00001512}
1513
John McCallfaf5fb42010-08-26 23:41:50 +00001514MemInitResult
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001515Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1516 Expr **Args, unsigned NumArgs,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001517 SourceLocation NameLoc,
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001518 SourceLocation LParenLoc,
1519 SourceLocation RParenLoc,
Alexis Huntc5575cc2011-02-26 19:13:13 +00001520 CXXRecordDecl *ClassDecl) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001521 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1522 if (!LangOpts.CPlusPlus0x)
1523 return Diag(Loc, diag::err_delegation_0x_only)
1524 << TInfo->getTypeLoc().getLocalSourceRange();
Sebastian Redl9cb4be22011-03-12 13:53:51 +00001525
Alexis Huntc5575cc2011-02-26 19:13:13 +00001526 // Initialize the object.
1527 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1528 QualType(ClassDecl->getTypeForDecl(), 0));
1529 InitializationKind Kind =
1530 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1531
1532 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1533
1534 ExprResult DelegationInit =
1535 InitSeq.Perform(*this, DelegationEntity, Kind,
1536 MultiExprArg(*this, Args, NumArgs), 0);
1537 if (DelegationInit.isInvalid())
1538 return true;
1539
1540 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1541 CXXConstructorDecl *Constructor = ConExpr->getConstructor();
1542 assert(Constructor && "Delegating constructor with no target?");
1543
1544 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1545
1546 // C++0x [class.base.init]p7:
1547 // The initialization of each base and member constitutes a
1548 // full-expression.
1549 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1550 if (DelegationInit.isInvalid())
1551 return true;
1552
1553 // If we are in a dependent context, template instantiation will
1554 // perform this type-checking again. Just save the arguments that we
1555 // received in a ParenListExpr.
1556 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1557 // of the information that we have about the base
1558 // initializer. However, deconstructing the ASTs is a dicey process,
1559 // and this approach is far more likely to get the corner cases right.
1560 if (CurContext->isDependentContext()) {
1561 ExprResult Init
1562 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1563 NumArgs, RParenLoc));
1564 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1565 Constructor, Init.takeAs<Expr>(),
1566 RParenLoc);
1567 }
1568
1569 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1570 DelegationInit.takeAs<Expr>(),
1571 RParenLoc);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001572}
1573
1574MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001575Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001576 Expr **Args, unsigned NumArgs,
1577 SourceLocation LParenLoc, SourceLocation RParenLoc,
Douglas Gregor44e7df62011-01-04 00:32:56 +00001578 CXXRecordDecl *ClassDecl,
1579 SourceLocation EllipsisLoc) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001580 bool HasDependentArg = false;
1581 for (unsigned i = 0; i < NumArgs; i++)
1582 HasDependentArg |= Args[i]->isTypeDependent();
1583
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001584 SourceLocation BaseLoc
1585 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1586
1587 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1588 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1589 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1590
1591 // C++ [class.base.init]p2:
1592 // [...] Unless the mem-initializer-id names a nonstatic data
Nick Lewycky9331ed82010-11-20 01:29:55 +00001593 // member of the constructor's class or a direct or virtual base
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001594 // of that class, the mem-initializer is ill-formed. A
1595 // mem-initializer-list can initialize a base class using any
1596 // name that denotes that base class type.
1597 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1598
Douglas Gregor44e7df62011-01-04 00:32:56 +00001599 if (EllipsisLoc.isValid()) {
1600 // This is a pack expansion.
1601 if (!BaseType->containsUnexpandedParameterPack()) {
1602 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1603 << SourceRange(BaseLoc, RParenLoc);
1604
1605 EllipsisLoc = SourceLocation();
1606 }
1607 } else {
1608 // Check for any unexpanded parameter packs.
1609 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1610 return true;
1611
1612 for (unsigned I = 0; I != NumArgs; ++I)
1613 if (DiagnoseUnexpandedParameterPack(Args[I]))
1614 return true;
1615 }
1616
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001617 // Check for direct and virtual base classes.
1618 const CXXBaseSpecifier *DirectBaseSpec = 0;
1619 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1620 if (!Dependent) {
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001621 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1622 BaseType))
Alexis Huntc5575cc2011-02-26 19:13:13 +00001623 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1624 LParenLoc, RParenLoc, ClassDecl);
Alexis Hunt4049b8d2011-01-08 19:20:43 +00001625
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001626 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1627 VirtualBaseSpec);
1628
1629 // C++ [base.class.init]p2:
1630 // Unless the mem-initializer-id names a nonstatic data member of the
1631 // constructor's class or a direct or virtual base of that class, the
1632 // mem-initializer is ill-formed.
1633 if (!DirectBaseSpec && !VirtualBaseSpec) {
1634 // If the class has any dependent bases, then it's possible that
1635 // one of those types will resolve to the same type as
1636 // BaseType. Therefore, just treat this as a dependent base
1637 // class initialization. FIXME: Should we try to check the
1638 // initialization anyway? It seems odd.
1639 if (ClassDecl->hasAnyDependentBases())
1640 Dependent = true;
1641 else
1642 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1643 << BaseType << Context.getTypeDeclType(ClassDecl)
1644 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1645 }
1646 }
1647
1648 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001649 // Can't check initialization for a base of dependent type or when
1650 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001651 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001652 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1653 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001654
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001655 // Erase any temporaries within this evaluation context; we're not
1656 // going to track them in the AST, since we'll be rebuilding the
1657 // ASTs during template instantiation.
1658 ExprTemporaries.erase(
1659 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1660 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001661
Alexis Hunt1d792652011-01-08 20:30:50 +00001662 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001663 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001664 LParenLoc,
1665 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001666 RParenLoc,
1667 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001668 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001669
1670 // C++ [base.class.init]p2:
1671 // If a mem-initializer-id is ambiguous because it designates both
1672 // a direct non-virtual base class and an inherited virtual base
1673 // class, the mem-initializer is ill-formed.
1674 if (DirectBaseSpec && VirtualBaseSpec)
1675 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001676 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001677
1678 CXXBaseSpecifier *BaseSpec
1679 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1680 if (!BaseSpec)
1681 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1682
1683 // Initialize the base.
1684 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001685 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001686 InitializationKind Kind =
1687 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1688
1689 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1690
John McCalldadc5752010-08-24 06:29:42 +00001691 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001692 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001693 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001694 if (BaseInit.isInvalid())
1695 return true;
John McCallacf0ee52010-10-08 02:01:28 +00001696
1697 CheckImplicitConversions(BaseInit.get(), LParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001698
1699 // C++0x [class.base.init]p7:
1700 // The initialization of each base and member constitutes a
1701 // full-expression.
Douglas Gregora40433a2010-12-07 00:41:46 +00001702 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001703 if (BaseInit.isInvalid())
1704 return true;
1705
1706 // If we are in a dependent context, template instantiation will
1707 // perform this type-checking again. Just save the arguments that we
1708 // received in a ParenListExpr.
1709 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1710 // of the information that we have about the base
1711 // initializer. However, deconstructing the ASTs is a dicey process,
1712 // and this approach is far more likely to get the corner cases right.
1713 if (CurContext->isDependentContext()) {
John McCalldadc5752010-08-24 06:29:42 +00001714 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001715 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1716 RParenLoc));
Alexis Hunt1d792652011-01-08 20:30:50 +00001717 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001718 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001719 LParenLoc,
1720 Init.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001721 RParenLoc,
1722 EllipsisLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001723 }
1724
Alexis Hunt1d792652011-01-08 20:30:50 +00001725 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001726 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001727 LParenLoc,
1728 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001729 RParenLoc,
1730 EllipsisLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001731}
1732
Anders Carlsson1b00e242010-04-23 03:10:23 +00001733/// ImplicitInitializerKind - How an implicit base or member initializer should
1734/// initialize its base or member.
1735enum ImplicitInitializerKind {
1736 IIK_Default,
1737 IIK_Copy,
1738 IIK_Move
1739};
1740
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001741static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001742BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001743 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001744 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001745 bool IsInheritedVirtualBase,
Alexis Hunt1d792652011-01-08 20:30:50 +00001746 CXXCtorInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001747 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001748 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1749 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001750
John McCalldadc5752010-08-24 06:29:42 +00001751 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001752
1753 switch (ImplicitInitKind) {
1754 case IIK_Default: {
1755 InitializationKind InitKind
1756 = InitializationKind::CreateDefault(Constructor->getLocation());
1757 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1758 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001759 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001760 break;
1761 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001762
Anders Carlsson1b00e242010-04-23 03:10:23 +00001763 case IIK_Copy: {
1764 ParmVarDecl *Param = Constructor->getParamDecl(0);
1765 QualType ParamType = Param->getType().getNonReferenceType();
1766
1767 Expr *CopyCtorArg =
Douglas Gregorea972d32011-02-28 21:54:11 +00001768 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001769 Constructor->getLocation(), ParamType,
1770 VK_LValue, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001771
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001772 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001773 QualType ArgTy =
1774 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1775 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001776
1777 CXXCastPath BasePath;
1778 BasePath.push_back(BaseSpec);
John Wiegley01296292011-04-08 18:41:53 +00001779 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1780 CK_UncheckedDerivedToBase,
1781 VK_LValue, &BasePath).take();
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001782
Anders Carlsson1b00e242010-04-23 03:10:23 +00001783 InitializationKind InitKind
1784 = InitializationKind::CreateDirect(Constructor->getLocation(),
1785 SourceLocation(), SourceLocation());
1786 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1787 &CopyCtorArg, 1);
1788 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001789 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001790 break;
1791 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001792
Anders Carlsson1b00e242010-04-23 03:10:23 +00001793 case IIK_Move:
1794 assert(false && "Unhandled initializer kind!");
1795 }
John McCallb268a282010-08-23 23:25:46 +00001796
Douglas Gregora40433a2010-12-07 00:41:46 +00001797 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001798 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001799 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001800
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001801 CXXBaseInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001802 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001803 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1804 SourceLocation()),
1805 BaseSpec->isVirtual(),
1806 SourceLocation(),
1807 BaseInit.takeAs<Expr>(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00001808 SourceLocation(),
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001809 SourceLocation());
1810
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001811 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001812}
1813
Anders Carlsson3c1db572010-04-23 02:15:47 +00001814static bool
1815BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001816 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001817 FieldDecl *Field,
Alexis Hunt1d792652011-01-08 20:30:50 +00001818 CXXCtorInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001819 if (Field->isInvalidDecl())
1820 return true;
1821
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001822 SourceLocation Loc = Constructor->getLocation();
1823
Anders Carlsson423f5d82010-04-23 16:04:08 +00001824 if (ImplicitInitKind == IIK_Copy) {
1825 ParmVarDecl *Param = Constructor->getParamDecl(0);
1826 QualType ParamType = Param->getType().getNonReferenceType();
1827
1828 Expr *MemberExprBase =
Douglas Gregorea972d32011-02-28 21:54:11 +00001829 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
John McCall7decc9e2010-11-18 06:31:45 +00001830 Loc, ParamType, VK_LValue, 0);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001831
1832 // Build a reference to this field within the parameter.
1833 CXXScopeSpec SS;
1834 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1835 Sema::LookupMemberName);
1836 MemberLookup.addDecl(Field, AS_public);
1837 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001838 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001839 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001840 ParamType, Loc,
1841 /*IsArrow=*/false,
1842 SS,
1843 /*FirstQualifierInScope=*/0,
1844 MemberLookup,
1845 /*TemplateArgs=*/0);
1846 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001847 return true;
1848
Douglas Gregor94f9a482010-05-05 05:51:00 +00001849 // When the field we are copying is an array, create index variables for
1850 // each dimension of the array. We use these index variables to subscript
1851 // the source array, and other clients (e.g., CodeGen) will perform the
1852 // necessary iteration with these index variables.
1853 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1854 QualType BaseType = Field->getType();
1855 QualType SizeType = SemaRef.Context.getSizeType();
1856 while (const ConstantArrayType *Array
1857 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1858 // Create the iteration variable for this array index.
1859 IdentifierInfo *IterationVarName = 0;
1860 {
1861 llvm::SmallString<8> Str;
1862 llvm::raw_svector_ostream OS(Str);
1863 OS << "__i" << IndexVariables.size();
1864 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1865 }
1866 VarDecl *IterationVar
Abramo Bagnaradff19302011-03-08 08:55:46 +00001867 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001868 IterationVarName, SizeType,
1869 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001870 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001871 IndexVariables.push_back(IterationVar);
1872
1873 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001874 ExprResult IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00001875 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001876 assert(!IterationVarRef.isInvalid() &&
1877 "Reference to invented variable cannot fail!");
1878
1879 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001880 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001881 Loc,
John McCallb268a282010-08-23 23:25:46 +00001882 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001883 Loc);
1884 if (CopyCtorArg.isInvalid())
1885 return true;
1886
1887 BaseType = Array->getElementType();
1888 }
1889
1890 // Construct the entity that we will be initializing. For an array, this
1891 // will be first element in the array, which may require several levels
1892 // of array-subscript entities.
1893 llvm::SmallVector<InitializedEntity, 4> Entities;
1894 Entities.reserve(1 + IndexVariables.size());
1895 Entities.push_back(InitializedEntity::InitializeMember(Field));
1896 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1897 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1898 0,
1899 Entities.back()));
1900
1901 // Direct-initialize to use the copy constructor.
1902 InitializationKind InitKind =
1903 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1904
1905 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1906 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1907 &CopyCtorArgE, 1);
1908
John McCalldadc5752010-08-24 06:29:42 +00001909 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001910 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001911 MultiExprArg(&CopyCtorArgE, 1));
Douglas Gregora40433a2010-12-07 00:41:46 +00001912 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001913 if (MemberInit.isInvalid())
1914 return true;
1915
1916 CXXMemberInit
Alexis Hunt1d792652011-01-08 20:30:50 +00001917 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001918 MemberInit.takeAs<Expr>(), Loc,
1919 IndexVariables.data(),
1920 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001921 return false;
1922 }
1923
Anders Carlsson423f5d82010-04-23 16:04:08 +00001924 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1925
Anders Carlsson3c1db572010-04-23 02:15:47 +00001926 QualType FieldBaseElementType =
1927 SemaRef.Context.getBaseElementType(Field->getType());
1928
Anders Carlsson3c1db572010-04-23 02:15:47 +00001929 if (FieldBaseElementType->isRecordType()) {
1930 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001931 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001932 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001933
1934 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001935 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001936 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001937
Douglas Gregora40433a2010-12-07 00:41:46 +00001938 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001939 if (MemberInit.isInvalid())
1940 return true;
1941
1942 CXXMemberInit =
Alexis Hunt1d792652011-01-08 20:30:50 +00001943 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001944 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001945 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001946 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001947 return false;
1948 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001949
1950 if (FieldBaseElementType->isReferenceType()) {
1951 SemaRef.Diag(Constructor->getLocation(),
1952 diag::err_uninitialized_member_in_ctor)
1953 << (int)Constructor->isImplicit()
1954 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1955 << 0 << Field->getDeclName();
1956 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1957 return true;
1958 }
1959
1960 if (FieldBaseElementType.isConstQualified()) {
1961 SemaRef.Diag(Constructor->getLocation(),
1962 diag::err_uninitialized_member_in_ctor)
1963 << (int)Constructor->isImplicit()
1964 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1965 << 1 << Field->getDeclName();
1966 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1967 return true;
1968 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001969
1970 // Nothing to initialize.
1971 CXXMemberInit = 0;
1972 return false;
1973}
John McCallbc83b3f2010-05-20 23:23:51 +00001974
1975namespace {
1976struct BaseAndFieldInfo {
1977 Sema &S;
1978 CXXConstructorDecl *Ctor;
1979 bool AnyErrorsInInits;
1980 ImplicitInitializerKind IIK;
Alexis Hunt1d792652011-01-08 20:30:50 +00001981 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
1982 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001983
1984 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1985 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1986 // FIXME: Handle implicit move constructors.
1987 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1988 IIK = IIK_Copy;
1989 else
1990 IIK = IIK_Default;
1991 }
1992};
1993}
1994
1995static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1996 FieldDecl *Top, FieldDecl *Field) {
1997
Chandler Carruth139e9622010-06-30 02:59:29 +00001998 // Overwhelmingly common case: we have a direct initializer for this field.
Alexis Hunt1d792652011-01-08 20:30:50 +00001999 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002000 Info.AllToInit.push_back(Init);
John McCallbc83b3f2010-05-20 23:23:51 +00002001 return false;
2002 }
2003
2004 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2005 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2006 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00002007 CXXRecordDecl *FieldClassDecl
2008 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00002009
2010 // Even though union members never have non-trivial default
2011 // constructions in C++03, we still build member initializers for aggregate
2012 // record types which can be union members, and C++0x allows non-trivial
2013 // default constructors for union members, so we ensure that only one
2014 // member is initialized for these.
2015 if (FieldClassDecl->isUnion()) {
2016 // First check for an explicit initializer for one field.
2017 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2018 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002019 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
Francois Pichetd583da02010-12-04 09:14:42 +00002020 Info.AllToInit.push_back(Init);
Chandler Carruth139e9622010-06-30 02:59:29 +00002021
2022 // Once we've initialized a field of an anonymous union, the union
2023 // field in the class is also initialized, so exit immediately.
2024 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00002025 } else if ((*FA)->isAnonymousStructOrUnion()) {
2026 if (CollectFieldInitializer(Info, Top, *FA))
2027 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00002028 }
2029 }
2030
2031 // Fallthrough and construct a default initializer for the union as
2032 // a whole, which can call its default constructor if such a thing exists
2033 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2034 // behavior going forward with C++0x, when anonymous unions there are
2035 // finalized, we should revisit this.
2036 } else {
2037 // For structs, we simply descend through to initialize all members where
2038 // necessary.
2039 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2040 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2041 if (CollectFieldInitializer(Info, Top, *FA))
2042 return true;
2043 }
2044 }
John McCallbc83b3f2010-05-20 23:23:51 +00002045 }
2046
2047 // Don't try to build an implicit initializer if there were semantic
2048 // errors in any of the initializers (and therefore we might be
2049 // missing some that the user actually wrote).
2050 if (Info.AnyErrorsInInits)
2051 return false;
2052
Alexis Hunt1d792652011-01-08 20:30:50 +00002053 CXXCtorInitializer *Init = 0;
John McCallbc83b3f2010-05-20 23:23:51 +00002054 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2055 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00002056
Francois Pichetd583da02010-12-04 09:14:42 +00002057 if (Init)
2058 Info.AllToInit.push_back(Init);
2059
John McCallbc83b3f2010-05-20 23:23:51 +00002060 return false;
2061}
Anders Carlsson3c1db572010-04-23 02:15:47 +00002062
Eli Friedman9cf6b592009-11-09 19:20:36 +00002063bool
Alexis Hunt1d792652011-01-08 20:30:50 +00002064Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2065 CXXCtorInitializer **Initializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002066 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002067 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00002068 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002069 // Just store the initializers as written, they will be checked during
2070 // instantiation.
2071 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002072 Constructor->setNumCtorInitializers(NumInitializers);
2073 CXXCtorInitializer **baseOrMemberInitializers =
2074 new (Context) CXXCtorInitializer*[NumInitializers];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002075 memcpy(baseOrMemberInitializers, Initializers,
Alexis Hunt1d792652011-01-08 20:30:50 +00002076 NumInitializers * sizeof(CXXCtorInitializer*));
2077 Constructor->setCtorInitializers(baseOrMemberInitializers);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002078 }
2079
2080 return false;
2081 }
2082
John McCallbc83b3f2010-05-20 23:23:51 +00002083 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00002084
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002085 // We need to build the initializer AST according to order of construction
2086 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002087 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00002088 if (!ClassDecl)
2089 return true;
2090
Eli Friedman9cf6b592009-11-09 19:20:36 +00002091 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00002092
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002093 for (unsigned i = 0; i < NumInitializers; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002094 CXXCtorInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00002095
2096 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00002097 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002098 else
Francois Pichetd583da02010-12-04 09:14:42 +00002099 Info.AllBaseFields[Member->getAnyMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002100 }
2101
Anders Carlsson43c64af2010-04-21 19:52:01 +00002102 // Keep track of the direct virtual bases.
2103 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2104 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2105 E = ClassDecl->bases_end(); I != E; ++I) {
2106 if (I->isVirtual())
2107 DirectVBases.insert(I);
2108 }
2109
Anders Carlssondb0a9652010-04-02 06:26:44 +00002110 // Push virtual bases before others.
2111 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2112 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2113
Alexis Hunt1d792652011-01-08 20:30:50 +00002114 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002115 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2116 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002117 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00002118 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Alexis Hunt1d792652011-01-08 20:30:50 +00002119 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002120 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002121 VBase, IsInheritedVirtualBase,
2122 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002123 HadError = true;
2124 continue;
2125 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00002126
John McCallbc83b3f2010-05-20 23:23:51 +00002127 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002128 }
2129 }
Mike Stump11289f42009-09-09 15:08:12 +00002130
John McCallbc83b3f2010-05-20 23:23:51 +00002131 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00002132 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2133 E = ClassDecl->bases_end(); Base != E; ++Base) {
2134 // Virtuals are in the virtual base list and already constructed.
2135 if (Base->isVirtual())
2136 continue;
Mike Stump11289f42009-09-09 15:08:12 +00002137
Alexis Hunt1d792652011-01-08 20:30:50 +00002138 if (CXXCtorInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00002139 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2140 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00002141 } else if (!AnyErrors) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002142 CXXCtorInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00002143 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00002144 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00002145 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00002146 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002147 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00002148 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00002149
John McCallbc83b3f2010-05-20 23:23:51 +00002150 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002151 }
2152 }
Mike Stump11289f42009-09-09 15:08:12 +00002153
John McCallbc83b3f2010-05-20 23:23:51 +00002154 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002155 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002156 E = ClassDecl->field_end(); Field != E; ++Field) {
2157 if ((*Field)->getType()->isIncompleteArrayType()) {
2158 assert(ClassDecl->hasFlexibleArrayMember() &&
2159 "Incomplete array type is not valid");
2160 continue;
2161 }
John McCallbc83b3f2010-05-20 23:23:51 +00002162 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00002163 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00002164 }
Mike Stump11289f42009-09-09 15:08:12 +00002165
John McCallbc83b3f2010-05-20 23:23:51 +00002166 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002167 if (NumInitializers > 0) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002168 Constructor->setNumCtorInitializers(NumInitializers);
2169 CXXCtorInitializer **baseOrMemberInitializers =
2170 new (Context) CXXCtorInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00002171 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
Alexis Hunt1d792652011-01-08 20:30:50 +00002172 NumInitializers * sizeof(CXXCtorInitializer*));
2173 Constructor->setCtorInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00002174
John McCalla6309952010-03-16 21:39:52 +00002175 // Constructors implicitly reference the base and member
2176 // destructors.
2177 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2178 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002179 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00002180
2181 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00002182}
2183
Eli Friedman952c15d2009-07-21 19:28:10 +00002184static void *GetKeyForTopLevelField(FieldDecl *Field) {
2185 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002186 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00002187 if (RT->getDecl()->isAnonymousStructOrUnion())
2188 return static_cast<void *>(RT->getDecl());
2189 }
2190 return static_cast<void *>(Field);
2191}
2192
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002193static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
John McCall424cec92011-01-19 06:33:43 +00002194 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
Anders Carlssonbcec05c2009-09-01 06:22:14 +00002195}
2196
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002197static void *GetKeyForMember(ASTContext &Context,
Alexis Hunt1d792652011-01-08 20:30:50 +00002198 CXXCtorInitializer *Member) {
Francois Pichetd583da02010-12-04 09:14:42 +00002199 if (!Member->isAnyMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002200 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00002201
Eli Friedman952c15d2009-07-21 19:28:10 +00002202 // For fields injected into the class via declaration of an anonymous union,
2203 // use its anonymous union class declaration as the unique key.
Francois Pichetd583da02010-12-04 09:14:42 +00002204 FieldDecl *Field = Member->getAnyMember();
2205
John McCall23eebd92010-04-10 09:28:51 +00002206 // If the field is a member of an anonymous struct or union, our key
2207 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00002208 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00002209 if (RD->isAnonymousStructOrUnion()) {
2210 while (true) {
2211 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2212 if (Parent->isAnonymousStructOrUnion())
2213 RD = Parent;
2214 else
2215 break;
2216 }
2217
Anders Carlsson83ac3122010-03-30 16:19:37 +00002218 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002219 }
Mike Stump11289f42009-09-09 15:08:12 +00002220
Anders Carlssona942dcd2010-03-30 15:39:27 +00002221 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002222}
2223
Anders Carlssone857b292010-04-02 03:37:03 +00002224static void
2225DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002226 const CXXConstructorDecl *Constructor,
Alexis Hunt1d792652011-01-08 20:30:50 +00002227 CXXCtorInitializer **Inits,
John McCallbb7b6582010-04-10 07:37:23 +00002228 unsigned NumInits) {
2229 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002230 return;
Mike Stump11289f42009-09-09 15:08:12 +00002231
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002232 // Don't check initializers order unless the warning is enabled at the
2233 // location of at least one initializer.
2234 bool ShouldCheckOrder = false;
2235 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002236 CXXCtorInitializer *Init = Inits[InitIndex];
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002237 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2238 Init->getSourceLocation())
2239 != Diagnostic::Ignored) {
2240 ShouldCheckOrder = true;
2241 break;
2242 }
2243 }
2244 if (!ShouldCheckOrder)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002245 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002246
John McCallbb7b6582010-04-10 07:37:23 +00002247 // Build the list of bases and members in the order that they'll
2248 // actually be initialized. The explicit initializers should be in
2249 // this same order but may be missing things.
2250 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002251
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002252 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2253
John McCallbb7b6582010-04-10 07:37:23 +00002254 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002255 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002256 ClassDecl->vbases_begin(),
2257 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002258 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002259
John McCallbb7b6582010-04-10 07:37:23 +00002260 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002261 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002262 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002263 if (Base->isVirtual())
2264 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002265 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002266 }
Mike Stump11289f42009-09-09 15:08:12 +00002267
John McCallbb7b6582010-04-10 07:37:23 +00002268 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002269 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2270 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002271 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002272
John McCallbb7b6582010-04-10 07:37:23 +00002273 unsigned NumIdealInits = IdealInitKeys.size();
2274 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002275
Alexis Hunt1d792652011-01-08 20:30:50 +00002276 CXXCtorInitializer *PrevInit = 0;
John McCallbb7b6582010-04-10 07:37:23 +00002277 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002278 CXXCtorInitializer *Init = Inits[InitIndex];
Francois Pichetd583da02010-12-04 09:14:42 +00002279 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
John McCallbb7b6582010-04-10 07:37:23 +00002280
2281 // Scan forward to try to find this initializer in the idealized
2282 // initializers list.
2283 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2284 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002285 break;
John McCallbb7b6582010-04-10 07:37:23 +00002286
2287 // If we didn't find this initializer, it must be because we
2288 // scanned past it on a previous iteration. That can only
2289 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002290 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002291 Sema::SemaDiagnosticBuilder D =
2292 SemaRef.Diag(PrevInit->getSourceLocation(),
2293 diag::warn_initializer_out_of_order);
2294
Francois Pichetd583da02010-12-04 09:14:42 +00002295 if (PrevInit->isAnyMemberInitializer())
2296 D << 0 << PrevInit->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002297 else
2298 D << 1 << PrevInit->getBaseClassInfo()->getType();
2299
Francois Pichetd583da02010-12-04 09:14:42 +00002300 if (Init->isAnyMemberInitializer())
2301 D << 0 << Init->getAnyMember()->getDeclName();
John McCallbb7b6582010-04-10 07:37:23 +00002302 else
2303 D << 1 << Init->getBaseClassInfo()->getType();
2304
2305 // Move back to the initializer's location in the ideal list.
2306 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2307 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002308 break;
John McCallbb7b6582010-04-10 07:37:23 +00002309
2310 assert(IdealIndex != NumIdealInits &&
2311 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002312 }
John McCallbb7b6582010-04-10 07:37:23 +00002313
2314 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002315 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002316}
2317
John McCall23eebd92010-04-10 09:28:51 +00002318namespace {
2319bool CheckRedundantInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002320 CXXCtorInitializer *Init,
2321 CXXCtorInitializer *&PrevInit) {
John McCall23eebd92010-04-10 09:28:51 +00002322 if (!PrevInit) {
2323 PrevInit = Init;
2324 return false;
2325 }
2326
2327 if (FieldDecl *Field = Init->getMember())
2328 S.Diag(Init->getSourceLocation(),
2329 diag::err_multiple_mem_initialization)
2330 << Field->getDeclName()
2331 << Init->getSourceRange();
2332 else {
John McCall424cec92011-01-19 06:33:43 +00002333 const Type *BaseClass = Init->getBaseClass();
John McCall23eebd92010-04-10 09:28:51 +00002334 assert(BaseClass && "neither field nor base");
2335 S.Diag(Init->getSourceLocation(),
2336 diag::err_multiple_base_initialization)
2337 << QualType(BaseClass, 0)
2338 << Init->getSourceRange();
2339 }
2340 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2341 << 0 << PrevInit->getSourceRange();
2342
2343 return true;
2344}
2345
Alexis Hunt1d792652011-01-08 20:30:50 +00002346typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
John McCall23eebd92010-04-10 09:28:51 +00002347typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2348
2349bool CheckRedundantUnionInit(Sema &S,
Alexis Hunt1d792652011-01-08 20:30:50 +00002350 CXXCtorInitializer *Init,
John McCall23eebd92010-04-10 09:28:51 +00002351 RedundantUnionMap &Unions) {
Francois Pichetd583da02010-12-04 09:14:42 +00002352 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002353 RecordDecl *Parent = Field->getParent();
2354 if (!Parent->isAnonymousStructOrUnion())
2355 return false;
2356
2357 NamedDecl *Child = Field;
2358 do {
2359 if (Parent->isUnion()) {
2360 UnionEntry &En = Unions[Parent];
2361 if (En.first && En.first != Child) {
2362 S.Diag(Init->getSourceLocation(),
2363 diag::err_multiple_mem_union_initialization)
2364 << Field->getDeclName()
2365 << Init->getSourceRange();
2366 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2367 << 0 << En.second->getSourceRange();
2368 return true;
2369 } else if (!En.first) {
2370 En.first = Child;
2371 En.second = Init;
2372 }
2373 }
2374
2375 Child = Parent;
2376 Parent = cast<RecordDecl>(Parent->getDeclContext());
2377 } while (Parent->isAnonymousStructOrUnion());
2378
2379 return false;
2380}
2381}
2382
Anders Carlssone857b292010-04-02 03:37:03 +00002383/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002384void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002385 SourceLocation ColonLoc,
2386 MemInitTy **meminits, unsigned NumMemInits,
2387 bool AnyErrors) {
2388 if (!ConstructorDecl)
2389 return;
2390
2391 AdjustDeclIfTemplate(ConstructorDecl);
2392
2393 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002394 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002395
2396 if (!Constructor) {
2397 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2398 return;
2399 }
2400
Alexis Hunt1d792652011-01-08 20:30:50 +00002401 CXXCtorInitializer **MemInits =
2402 reinterpret_cast<CXXCtorInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002403
2404 // Mapping for the duplicate initializers check.
2405 // For member initializers, this is keyed with a FieldDecl*.
2406 // For base initializers, this is keyed with a Type*.
Alexis Hunt1d792652011-01-08 20:30:50 +00002407 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002408
2409 // Mapping for the inconsistent anonymous-union initializers check.
2410 RedundantUnionMap MemberUnions;
2411
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002412 bool HadError = false;
2413 for (unsigned i = 0; i < NumMemInits; i++) {
Alexis Hunt1d792652011-01-08 20:30:50 +00002414 CXXCtorInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002415
Abramo Bagnara341d7832010-05-26 18:09:23 +00002416 // Set the source order index.
2417 Init->setSourceOrder(i);
2418
Francois Pichetd583da02010-12-04 09:14:42 +00002419 if (Init->isAnyMemberInitializer()) {
2420 FieldDecl *Field = Init->getAnyMember();
John McCall23eebd92010-04-10 09:28:51 +00002421 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2422 CheckRedundantUnionInit(*this, Init, MemberUnions))
2423 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002424 } else if (Init->isBaseInitializer()) {
John McCall23eebd92010-04-10 09:28:51 +00002425 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2426 if (CheckRedundantInit(*this, Init, Members[Key]))
2427 HadError = true;
Alexis Huntc5575cc2011-02-26 19:13:13 +00002428 } else {
2429 assert(Init->isDelegatingInitializer());
2430 // This must be the only initializer
2431 if (i != 0 || NumMemInits > 1) {
2432 Diag(MemInits[0]->getSourceLocation(),
2433 diag::err_delegating_initializer_alone)
2434 << MemInits[0]->getSourceRange();
2435 HadError = true;
2436 }
Anders Carlssone857b292010-04-02 03:37:03 +00002437 }
Anders Carlssone857b292010-04-02 03:37:03 +00002438 }
2439
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002440 if (HadError)
2441 return;
2442
Anders Carlssone857b292010-04-02 03:37:03 +00002443 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002444
Alexis Hunt1d792652011-01-08 20:30:50 +00002445 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002446}
2447
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002448void
John McCalla6309952010-03-16 21:39:52 +00002449Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2450 CXXRecordDecl *ClassDecl) {
2451 // Ignore dependent contexts.
2452 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002453 return;
John McCall1064d7e2010-03-16 05:22:47 +00002454
2455 // FIXME: all the access-control diagnostics are positioned on the
2456 // field/base declaration. That's probably good; that said, the
2457 // user might reasonably want to know why the destructor is being
2458 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002459
Anders Carlssondee9a302009-11-17 04:44:12 +00002460 // Non-static data members.
2461 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2462 E = ClassDecl->field_end(); I != E; ++I) {
2463 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002464 if (Field->isInvalidDecl())
2465 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002466 QualType FieldType = Context.getBaseElementType(Field->getType());
2467
2468 const RecordType* RT = FieldType->getAs<RecordType>();
2469 if (!RT)
2470 continue;
2471
2472 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002473 if (FieldClassDecl->isInvalidDecl())
2474 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002475 if (FieldClassDecl->hasTrivialDestructor())
2476 continue;
2477
Douglas Gregore71edda2010-07-01 22:47:18 +00002478 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002479 assert(Dtor && "No dtor found for FieldClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002480 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002481 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002482 << Field->getDeclName()
2483 << FieldType);
2484
John McCalla6309952010-03-16 21:39:52 +00002485 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002486 }
2487
John McCall1064d7e2010-03-16 05:22:47 +00002488 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2489
Anders Carlssondee9a302009-11-17 04:44:12 +00002490 // Bases.
2491 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2492 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002493 // Bases are always records in a well-formed non-dependent class.
2494 const RecordType *RT = Base->getType()->getAs<RecordType>();
2495
2496 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002497 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002498 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002499
John McCall1064d7e2010-03-16 05:22:47 +00002500 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002501 // If our base class is invalid, we probably can't get its dtor anyway.
2502 if (BaseClassDecl->isInvalidDecl())
2503 continue;
2504 // Ignore trivial destructors.
Anders Carlssondee9a302009-11-17 04:44:12 +00002505 if (BaseClassDecl->hasTrivialDestructor())
2506 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002507
Douglas Gregore71edda2010-07-01 22:47:18 +00002508 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002509 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002510
2511 // FIXME: caret should be on the start of the class name
2512 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002513 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002514 << Base->getType()
2515 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002516
John McCalla6309952010-03-16 21:39:52 +00002517 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002518 }
2519
2520 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002521 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2522 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002523
2524 // Bases are always records in a well-formed non-dependent class.
2525 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2526
2527 // Ignore direct virtual bases.
2528 if (DirectVirtualBases.count(RT))
2529 continue;
2530
John McCall1064d7e2010-03-16 05:22:47 +00002531 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002532 // If our base class is invalid, we probably can't get its dtor anyway.
2533 if (BaseClassDecl->isInvalidDecl())
2534 continue;
2535 // Ignore trivial destructors.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002536 if (BaseClassDecl->hasTrivialDestructor())
2537 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002538
Douglas Gregore71edda2010-07-01 22:47:18 +00002539 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
Matt Beaumont-Gay93615d92011-03-28 01:39:13 +00002540 assert(Dtor && "No dtor found for BaseClassDecl!");
John McCall1064d7e2010-03-16 05:22:47 +00002541 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002542 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002543 << VBase->getType());
2544
John McCalla6309952010-03-16 21:39:52 +00002545 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002546 }
2547}
2548
John McCall48871652010-08-21 09:40:31 +00002549void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002550 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002551 return;
Mike Stump11289f42009-09-09 15:08:12 +00002552
Mike Stump11289f42009-09-09 15:08:12 +00002553 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002554 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Alexis Hunt1d792652011-01-08 20:30:50 +00002555 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002556}
2557
Mike Stump11289f42009-09-09 15:08:12 +00002558bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002559 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002560 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002561 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002562 else
John McCall02db245d2010-08-18 09:41:07 +00002563 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002564}
2565
Anders Carlssoneabf7702009-08-27 00:13:57 +00002566bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002567 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002568 if (!getLangOptions().CPlusPlus)
2569 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002570
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002571 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002572 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002573
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002574 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002575 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002576 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002577 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002578
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002579 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002580 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002581 }
Mike Stump11289f42009-09-09 15:08:12 +00002582
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002583 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002584 if (!RT)
2585 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002586
John McCall67da35c2010-02-04 22:26:26 +00002587 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002588
John McCall02db245d2010-08-18 09:41:07 +00002589 // We can't answer whether something is abstract until it has a
2590 // definition. If it's currently being defined, we'll walk back
2591 // over all the declarations when we have a full definition.
2592 const CXXRecordDecl *Def = RD->getDefinition();
2593 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002594 return false;
2595
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002596 if (!RD->isAbstract())
2597 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002598
Anders Carlssoneabf7702009-08-27 00:13:57 +00002599 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002600 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002601
John McCall02db245d2010-08-18 09:41:07 +00002602 return true;
2603}
2604
2605void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2606 // Check if we've already emitted the list of pure virtual functions
2607 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002608 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002609 return;
Mike Stump11289f42009-09-09 15:08:12 +00002610
Douglas Gregor4165bd62010-03-23 23:47:56 +00002611 CXXFinalOverriderMap FinalOverriders;
2612 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002613
Anders Carlssona2f74f32010-06-03 01:00:02 +00002614 // Keep a set of seen pure methods so we won't diagnose the same method
2615 // more than once.
2616 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2617
Douglas Gregor4165bd62010-03-23 23:47:56 +00002618 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2619 MEnd = FinalOverriders.end();
2620 M != MEnd;
2621 ++M) {
2622 for (OverridingMethods::iterator SO = M->second.begin(),
2623 SOEnd = M->second.end();
2624 SO != SOEnd; ++SO) {
2625 // C++ [class.abstract]p4:
2626 // A class is abstract if it contains or inherits at least one
2627 // pure virtual function for which the final overrider is pure
2628 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002629
Douglas Gregor4165bd62010-03-23 23:47:56 +00002630 //
2631 if (SO->second.size() != 1)
2632 continue;
2633
2634 if (!SO->second.front().Method->isPure())
2635 continue;
2636
Anders Carlssona2f74f32010-06-03 01:00:02 +00002637 if (!SeenPureMethods.insert(SO->second.front().Method))
2638 continue;
2639
Douglas Gregor4165bd62010-03-23 23:47:56 +00002640 Diag(SO->second.front().Method->getLocation(),
2641 diag::note_pure_virtual_function)
Chandler Carruth98e3c562011-02-18 23:59:51 +00002642 << SO->second.front().Method->getDeclName() << RD->getDeclName();
Douglas Gregor4165bd62010-03-23 23:47:56 +00002643 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002644 }
2645
2646 if (!PureVirtualClassDiagSet)
2647 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2648 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002649}
2650
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002651namespace {
John McCall02db245d2010-08-18 09:41:07 +00002652struct AbstractUsageInfo {
2653 Sema &S;
2654 CXXRecordDecl *Record;
2655 CanQualType AbstractType;
2656 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002657
John McCall02db245d2010-08-18 09:41:07 +00002658 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2659 : S(S), Record(Record),
2660 AbstractType(S.Context.getCanonicalType(
2661 S.Context.getTypeDeclType(Record))),
2662 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002663
John McCall02db245d2010-08-18 09:41:07 +00002664 void DiagnoseAbstractType() {
2665 if (Invalid) return;
2666 S.DiagnoseAbstractType(Record);
2667 Invalid = true;
2668 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002669
John McCall02db245d2010-08-18 09:41:07 +00002670 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2671};
2672
2673struct CheckAbstractUsage {
2674 AbstractUsageInfo &Info;
2675 const NamedDecl *Ctx;
2676
2677 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2678 : Info(Info), Ctx(Ctx) {}
2679
2680 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2681 switch (TL.getTypeLocClass()) {
2682#define ABSTRACT_TYPELOC(CLASS, PARENT)
2683#define TYPELOC(CLASS, PARENT) \
2684 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2685#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002686 }
John McCall02db245d2010-08-18 09:41:07 +00002687 }
Mike Stump11289f42009-09-09 15:08:12 +00002688
John McCall02db245d2010-08-18 09:41:07 +00002689 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2690 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2691 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
Douglas Gregor385d3fd2011-02-22 23:21:06 +00002692 if (!TL.getArg(I))
2693 continue;
2694
John McCall02db245d2010-08-18 09:41:07 +00002695 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2696 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002697 }
John McCall02db245d2010-08-18 09:41:07 +00002698 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002699
John McCall02db245d2010-08-18 09:41:07 +00002700 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2701 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2702 }
Mike Stump11289f42009-09-09 15:08:12 +00002703
John McCall02db245d2010-08-18 09:41:07 +00002704 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2705 // Visit the type parameters from a permissive context.
2706 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2707 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2708 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2709 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2710 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2711 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002712 }
John McCall02db245d2010-08-18 09:41:07 +00002713 }
Mike Stump11289f42009-09-09 15:08:12 +00002714
John McCall02db245d2010-08-18 09:41:07 +00002715 // Visit pointee types from a permissive context.
2716#define CheckPolymorphic(Type) \
2717 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2718 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2719 }
2720 CheckPolymorphic(PointerTypeLoc)
2721 CheckPolymorphic(ReferenceTypeLoc)
2722 CheckPolymorphic(MemberPointerTypeLoc)
2723 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002724
John McCall02db245d2010-08-18 09:41:07 +00002725 /// Handle all the types we haven't given a more specific
2726 /// implementation for above.
2727 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2728 // Every other kind of type that we haven't called out already
2729 // that has an inner type is either (1) sugar or (2) contains that
2730 // inner type in some way as a subobject.
2731 if (TypeLoc Next = TL.getNextTypeLoc())
2732 return Visit(Next, Sel);
2733
2734 // If there's no inner type and we're in a permissive context,
2735 // don't diagnose.
2736 if (Sel == Sema::AbstractNone) return;
2737
2738 // Check whether the type matches the abstract type.
2739 QualType T = TL.getType();
2740 if (T->isArrayType()) {
2741 Sel = Sema::AbstractArrayType;
2742 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002743 }
John McCall02db245d2010-08-18 09:41:07 +00002744 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2745 if (CT != Info.AbstractType) return;
2746
2747 // It matched; do some magic.
2748 if (Sel == Sema::AbstractArrayType) {
2749 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2750 << T << TL.getSourceRange();
2751 } else {
2752 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2753 << Sel << T << TL.getSourceRange();
2754 }
2755 Info.DiagnoseAbstractType();
2756 }
2757};
2758
2759void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2760 Sema::AbstractDiagSelID Sel) {
2761 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2762}
2763
2764}
2765
2766/// Check for invalid uses of an abstract type in a method declaration.
2767static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2768 CXXMethodDecl *MD) {
2769 // No need to do the check on definitions, which require that
2770 // the return/param types be complete.
2771 if (MD->isThisDeclarationADefinition())
2772 return;
2773
2774 // For safety's sake, just ignore it if we don't have type source
2775 // information. This should never happen for non-implicit methods,
2776 // but...
2777 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2778 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2779}
2780
2781/// Check for invalid uses of an abstract type within a class definition.
2782static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2783 CXXRecordDecl *RD) {
2784 for (CXXRecordDecl::decl_iterator
2785 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2786 Decl *D = *I;
2787 if (D->isImplicit()) continue;
2788
2789 // Methods and method templates.
2790 if (isa<CXXMethodDecl>(D)) {
2791 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2792 } else if (isa<FunctionTemplateDecl>(D)) {
2793 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2794 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2795
2796 // Fields and static variables.
2797 } else if (isa<FieldDecl>(D)) {
2798 FieldDecl *FD = cast<FieldDecl>(D);
2799 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2800 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2801 } else if (isa<VarDecl>(D)) {
2802 VarDecl *VD = cast<VarDecl>(D);
2803 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2804 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2805
2806 // Nested classes and class templates.
2807 } else if (isa<CXXRecordDecl>(D)) {
2808 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2809 } else if (isa<ClassTemplateDecl>(D)) {
2810 CheckAbstractClassUsage(Info,
2811 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2812 }
2813 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002814}
2815
Douglas Gregorc99f1552009-12-03 18:33:45 +00002816/// \brief Perform semantic checks on a class definition that has been
2817/// completing, introducing implicitly-declared members, checking for
2818/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002819void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002820 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002821 return;
2822
John McCall02db245d2010-08-18 09:41:07 +00002823 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2824 AbstractUsageInfo Info(*this, Record);
2825 CheckAbstractClassUsage(Info, Record);
2826 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002827
2828 // If this is not an aggregate type and has no user-declared constructor,
2829 // complain about any non-static data members of reference or const scalar
2830 // type, since they will never get initializers.
2831 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2832 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2833 bool Complained = false;
2834 for (RecordDecl::field_iterator F = Record->field_begin(),
2835 FEnd = Record->field_end();
2836 F != FEnd; ++F) {
2837 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002838 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002839 if (!Complained) {
2840 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2841 << Record->getTagKind() << Record;
2842 Complained = true;
2843 }
2844
2845 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2846 << F->getType()->isReferenceType()
2847 << F->getDeclName();
2848 }
2849 }
2850 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002851
Anders Carlssone771e762011-01-25 18:08:22 +00002852 if (Record->isDynamicClass() && !Record->isDependentType())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002853 DynamicClasses.push_back(Record);
Douglas Gregor36c22a22010-10-15 13:21:21 +00002854
2855 if (Record->getIdentifier()) {
2856 // C++ [class.mem]p13:
2857 // If T is the name of a class, then each of the following shall have a
2858 // name different from T:
2859 // - every member of every anonymous union that is a member of class T.
2860 //
2861 // C++ [class.mem]p14:
2862 // In addition, if class T has a user-declared constructor (12.1), every
2863 // non-static data member of class T shall have a name different from T.
2864 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
Francois Pichet783dd6e2010-11-21 06:08:52 +00002865 R.first != R.second; ++R.first) {
2866 NamedDecl *D = *R.first;
2867 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
2868 isa<IndirectFieldDecl>(D)) {
2869 Diag(D->getLocation(), diag::err_member_name_of_class)
2870 << D->getDeclName();
Douglas Gregor36c22a22010-10-15 13:21:21 +00002871 break;
2872 }
Francois Pichet783dd6e2010-11-21 06:08:52 +00002873 }
Douglas Gregor36c22a22010-10-15 13:21:21 +00002874 }
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002875
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002876 // Warn if the class has virtual methods but non-virtual public destructor.
Douglas Gregor0cf82f62011-02-19 19:14:36 +00002877 if (Record->isPolymorphic() && !Record->isDependentType()) {
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002878 CXXDestructorDecl *dtor = Record->getDestructor();
Argyrios Kyrtzidis33799ca2011-01-31 17:10:25 +00002879 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
Argyrios Kyrtzidis7f3986d2011-01-31 07:05:00 +00002880 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
2881 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
2882 }
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002883
2884 // See if a method overloads virtual methods in a base
2885 /// class without overriding any.
2886 if (!Record->isDependentType()) {
2887 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
2888 MEnd = Record->method_end();
2889 M != MEnd; ++M) {
Argyrios Kyrtzidis7a1778e2011-03-03 22:58:57 +00002890 if (!(*M)->isStatic())
2891 DiagnoseHiddenVirtualMethods(Record, *M);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002892 }
2893 }
Sebastian Redl08905022011-02-05 19:23:19 +00002894
2895 // Declare inherited constructors. We do this eagerly here because:
2896 // - The standard requires an eager diagnostic for conflicting inherited
2897 // constructors from different classes.
2898 // - The lazy declaration of the other implicit constructors is so as to not
2899 // waste space and performance on classes that are not meant to be
2900 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2901 // have inherited constructors.
Sebastian Redlc1f8e492011-03-12 13:44:32 +00002902 DeclareInheritedConstructors(Record);
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002903}
2904
2905/// \brief Data used with FindHiddenVirtualMethod
Benjamin Kramer024e6192011-03-04 13:12:48 +00002906namespace {
2907 struct FindHiddenVirtualMethodData {
2908 Sema *S;
2909 CXXMethodDecl *Method;
2910 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
2911 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2912 };
2913}
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002914
2915/// \brief Member lookup function that determines whether a given C++
2916/// method overloads virtual methods in a base class without overriding any,
2917/// to be used with CXXRecordDecl::lookupInBases().
2918static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
2919 CXXBasePath &Path,
2920 void *UserData) {
2921 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2922
2923 FindHiddenVirtualMethodData &Data
2924 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
2925
2926 DeclarationName Name = Data.Method->getDeclName();
2927 assert(Name.getNameKind() == DeclarationName::Identifier);
2928
2929 bool foundSameNameMethod = false;
2930 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
2931 for (Path.Decls = BaseRecord->lookup(Name);
2932 Path.Decls.first != Path.Decls.second;
2933 ++Path.Decls.first) {
2934 NamedDecl *D = *Path.Decls.first;
2935 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002936 MD = MD->getCanonicalDecl();
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002937 foundSameNameMethod = true;
2938 // Interested only in hidden virtual methods.
2939 if (!MD->isVirtual())
2940 continue;
2941 // If the method we are checking overrides a method from its base
2942 // don't warn about the other overloaded methods.
2943 if (!Data.S->IsOverload(Data.Method, MD, false))
2944 return true;
2945 // Collect the overload only if its hidden.
2946 if (!Data.OverridenAndUsingBaseMethods.count(MD))
2947 overloadedMethods.push_back(MD);
2948 }
2949 }
2950
2951 if (foundSameNameMethod)
2952 Data.OverloadedMethods.append(overloadedMethods.begin(),
2953 overloadedMethods.end());
2954 return foundSameNameMethod;
2955}
2956
2957/// \brief See if a method overloads virtual methods in a base class without
2958/// overriding any.
2959void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
2960 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
2961 MD->getLocation()) == Diagnostic::Ignored)
2962 return;
2963 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
2964 return;
2965
2966 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2967 /*bool RecordPaths=*/false,
2968 /*bool DetectVirtual=*/false);
2969 FindHiddenVirtualMethodData Data;
2970 Data.Method = MD;
2971 Data.S = this;
2972
2973 // Keep the base methods that were overriden or introduced in the subclass
2974 // by 'using' in a set. A base method not in this set is hidden.
2975 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
2976 res.first != res.second; ++res.first) {
2977 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
2978 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
2979 E = MD->end_overridden_methods();
2980 I != E; ++I)
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002981 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002982 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
2983 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
Argyrios Kyrtzidis7dd856a2011-02-10 18:13:41 +00002984 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
Argyrios Kyrtzidis7272d9c2011-02-03 18:01:15 +00002985 }
2986
2987 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
2988 !Data.OverloadedMethods.empty()) {
2989 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
2990 << MD << (Data.OverloadedMethods.size() > 1);
2991
2992 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
2993 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
2994 Diag(overloadedMD->getLocation(),
2995 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
2996 }
2997 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002998}
2999
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003000void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00003001 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003002 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00003003 SourceLocation RBrac,
3004 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003005 if (!TagDecl)
3006 return;
Mike Stump11289f42009-09-09 15:08:12 +00003007
Douglas Gregorc9f9b862009-05-11 19:58:34 +00003008 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00003009
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003010 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00003011 // strict aliasing violation!
3012 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00003013 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00003014
Douglas Gregor0be31a22010-07-02 17:43:08 +00003015 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00003016 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003017}
3018
Douglas Gregor95755162010-07-01 05:10:53 +00003019namespace {
3020 /// \brief Helper class that collects exception specifications for
3021 /// implicitly-declared special member functions.
3022 class ImplicitExceptionSpecification {
3023 ASTContext &Context;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003024 // We order exception specifications thus:
3025 // noexcept is the most restrictive, but is only used in C++0x.
3026 // throw() comes next.
3027 // Then a throw(collected exceptions)
3028 // Finally no specification.
3029 // throw(...) is used instead if any called function uses it.
3030 ExceptionSpecificationType ComputedEST;
Douglas Gregor95755162010-07-01 05:10:53 +00003031 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
3032 llvm::SmallVector<QualType, 4> Exceptions;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003033
3034 void ClearExceptions() {
3035 ExceptionsSeen.clear();
3036 Exceptions.clear();
3037 }
3038
Douglas Gregor95755162010-07-01 05:10:53 +00003039 public:
3040 explicit ImplicitExceptionSpecification(ASTContext &Context)
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003041 : Context(Context), ComputedEST(EST_BasicNoexcept) {
3042 if (!Context.getLangOptions().CPlusPlus0x)
3043 ComputedEST = EST_DynamicNone;
Douglas Gregor95755162010-07-01 05:10:53 +00003044 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003045
3046 /// \brief Get the computed exception specification type.
3047 ExceptionSpecificationType getExceptionSpecType() const {
3048 assert(ComputedEST != EST_ComputedNoexcept &&
3049 "noexcept(expr) should not be a possible result");
3050 return ComputedEST;
Douglas Gregor95755162010-07-01 05:10:53 +00003051 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003052
Douglas Gregor95755162010-07-01 05:10:53 +00003053 /// \brief The number of exceptions in the exception specification.
3054 unsigned size() const { return Exceptions.size(); }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003055
Douglas Gregor95755162010-07-01 05:10:53 +00003056 /// \brief The set of exceptions in the exception specification.
3057 const QualType *data() const { return Exceptions.data(); }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003058
3059 /// \brief Integrate another called method into the collected data.
Douglas Gregor95755162010-07-01 05:10:53 +00003060 void CalledDecl(CXXMethodDecl *Method) {
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003061 // If we have an MSAny spec already, don't bother.
3062 if (!Method || ComputedEST == EST_MSAny)
Douglas Gregor95755162010-07-01 05:10:53 +00003063 return;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003064
Douglas Gregor95755162010-07-01 05:10:53 +00003065 const FunctionProtoType *Proto
3066 = Method->getType()->getAs<FunctionProtoType>();
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003067
3068 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
3069
Douglas Gregor95755162010-07-01 05:10:53 +00003070 // If this function can throw any exceptions, make a note of that.
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003071 if (EST == EST_MSAny || EST == EST_None) {
3072 ClearExceptions();
3073 ComputedEST = EST;
Douglas Gregor95755162010-07-01 05:10:53 +00003074 return;
3075 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003076
3077 // If this function has a basic noexcept, it doesn't affect the outcome.
3078 if (EST == EST_BasicNoexcept)
3079 return;
3080
3081 // If we have a throw-all spec at this point, ignore the function.
3082 if (ComputedEST == EST_None)
3083 return;
3084
3085 // If we're still at noexcept(true) and there's a nothrow() callee,
3086 // change to that specification.
3087 if (EST == EST_DynamicNone) {
3088 if (ComputedEST == EST_BasicNoexcept)
3089 ComputedEST = EST_DynamicNone;
3090 return;
3091 }
3092
3093 // Check out noexcept specs.
3094 if (EST == EST_ComputedNoexcept) {
Sebastian Redl31ad7542011-03-13 17:09:40 +00003095 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(Context);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003096 assert(NR != FunctionProtoType::NR_NoNoexcept &&
3097 "Must have noexcept result for EST_ComputedNoexcept.");
3098 assert(NR != FunctionProtoType::NR_Dependent &&
3099 "Should not generate implicit declarations for dependent cases, "
3100 "and don't know how to handle them anyway.");
3101
3102 // noexcept(false) -> no spec on the new function
3103 if (NR == FunctionProtoType::NR_Throw) {
3104 ClearExceptions();
3105 ComputedEST = EST_None;
3106 }
3107 // noexcept(true) won't change anything either.
3108 return;
3109 }
3110
3111 assert(EST == EST_Dynamic && "EST case not considered earlier.");
3112 assert(ComputedEST != EST_None &&
3113 "Shouldn't collect exceptions when throw-all is guaranteed.");
3114 ComputedEST = EST_Dynamic;
Douglas Gregor95755162010-07-01 05:10:53 +00003115 // Record the exceptions in this function's exception specification.
3116 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
3117 EEnd = Proto->exception_end();
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003118 E != EEnd; ++E)
Douglas Gregor95755162010-07-01 05:10:53 +00003119 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
3120 Exceptions.push_back(*E);
3121 }
3122 };
3123}
3124
3125
Douglas Gregor05379422008-11-03 17:51:48 +00003126/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
3127/// special functions, such as the default constructor, copy
3128/// constructor, or destructor, to the given C++ class (C++
3129/// [special]p1). This routine can only be executed just before the
3130/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00003131void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00003132 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00003133 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003134
Douglas Gregor54be3392010-07-01 17:57:27 +00003135 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00003136 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00003137
Douglas Gregor330b9cf2010-07-02 21:50:04 +00003138 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
3139 ++ASTContext::NumImplicitCopyAssignmentOperators;
3140
3141 // If we have a dynamic class, then the copy assignment operator may be
3142 // virtual, so we have to declare it immediately. This ensures that, e.g.,
3143 // it shows up in the right place in the vtable and that we diagnose
3144 // problems with the implicit exception specification.
3145 if (ClassDecl->isDynamicClass())
3146 DeclareImplicitCopyAssignment(ClassDecl);
3147 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003148
Douglas Gregor7454c562010-07-02 20:37:36 +00003149 if (!ClassDecl->hasUserDeclaredDestructor()) {
3150 ++ASTContext::NumImplicitDestructors;
3151
3152 // If we have a dynamic class, then the destructor may be virtual, so we
3153 // have to declare the destructor immediately. This ensures that, e.g., it
3154 // shows up in the right place in the vtable and that we diagnose problems
3155 // with the implicit exception specification.
3156 if (ClassDecl->isDynamicClass())
3157 DeclareImplicitDestructor(ClassDecl);
3158 }
Douglas Gregor05379422008-11-03 17:51:48 +00003159}
3160
John McCall48871652010-08-21 09:40:31 +00003161void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00003162 if (!D)
3163 return;
3164
3165 TemplateParameterList *Params = 0;
3166 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
3167 Params = Template->getTemplateParameters();
3168 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3169 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
3170 Params = PartialSpec->getTemplateParameters();
3171 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003172 return;
3173
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003174 for (TemplateParameterList::iterator Param = Params->begin(),
3175 ParamEnd = Params->end();
3176 Param != ParamEnd; ++Param) {
3177 NamedDecl *Named = cast<NamedDecl>(*Param);
3178 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00003179 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00003180 IdResolver.AddDecl(Named);
3181 }
3182 }
3183}
3184
John McCall48871652010-08-21 09:40:31 +00003185void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003186 if (!RecordD) return;
3187 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00003188 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00003189 PushDeclContext(S, Record);
3190}
3191
John McCall48871652010-08-21 09:40:31 +00003192void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00003193 if (!RecordD) return;
3194 PopDeclContext();
3195}
3196
Douglas Gregor4d87df52008-12-16 21:30:33 +00003197/// ActOnStartDelayedCXXMethodDeclaration - We have completed
3198/// parsing a top-level (non-nested) C++ class, and we are now
3199/// parsing those parts of the given Method declaration that could
3200/// not be parsed earlier (C++ [class.mem]p2), such as default
3201/// arguments. This action should enter the scope of the given
3202/// Method declaration as if we had just parsed the qualified method
3203/// name. However, it should not bring the parameters into scope;
3204/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00003205void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003206}
3207
3208/// ActOnDelayedCXXMethodParameter - We've already started a delayed
3209/// C++ method declaration. We're (re-)introducing the given
3210/// function parameter into scope for use in parsing later parts of
3211/// the method declaration. For example, we could see an
3212/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00003213void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003214 if (!ParamD)
3215 return;
Mike Stump11289f42009-09-09 15:08:12 +00003216
John McCall48871652010-08-21 09:40:31 +00003217 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00003218
3219 // If this parameter has an unparsed default argument, clear it out
3220 // to make way for the parsed default argument.
3221 if (Param->hasUnparsedDefaultArg())
3222 Param->setDefaultArg(0);
3223
John McCall48871652010-08-21 09:40:31 +00003224 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003225 if (Param->getDeclName())
3226 IdResolver.AddDecl(Param);
3227}
3228
3229/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3230/// processing the delayed method declaration for Method. The method
3231/// declaration is now considered finished. There may be a separate
3232/// ActOnStartOfFunctionDef action later (not necessarily
3233/// immediately!) for this method, if it was also defined inside the
3234/// class body.
John McCall48871652010-08-21 09:40:31 +00003235void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00003236 if (!MethodD)
3237 return;
Mike Stump11289f42009-09-09 15:08:12 +00003238
Douglas Gregorc8c277a2009-08-24 11:57:43 +00003239 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00003240
John McCall48871652010-08-21 09:40:31 +00003241 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003242
3243 // Now that we have our default arguments, check the constructor
3244 // again. It could produce additional diagnostics or affect whether
3245 // the class has implicitly-declared destructors, among other
3246 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003247 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
3248 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003249
3250 // Check the default arguments, which we may have added.
3251 if (!Method->isInvalidDecl())
3252 CheckCXXDefaultArguments(Method);
3253}
3254
Douglas Gregor831c93f2008-11-05 20:51:48 +00003255/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00003256/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00003257/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003258/// emit diagnostics and set the invalid bit to true. In any case, the type
3259/// will be updated to reflect a well-formed type for the constructor and
3260/// returned.
3261QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003262 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003263 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003264
3265 // C++ [class.ctor]p3:
3266 // A constructor shall not be virtual (10.3) or static (9.4). A
3267 // constructor can be invoked for a const, volatile or const
3268 // volatile object. A constructor shall not be declared const,
3269 // volatile, or const volatile (9.3.2).
3270 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003271 if (!D.isInvalidType())
3272 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3273 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
3274 << SourceRange(D.getIdentifierLoc());
3275 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003276 }
John McCall8e7d6562010-08-26 03:08:43 +00003277 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003278 if (!D.isInvalidType())
3279 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
3280 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3281 << SourceRange(D.getIdentifierLoc());
3282 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003283 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003284 }
Mike Stump11289f42009-09-09 15:08:12 +00003285
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003286 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003287 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00003288 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003289 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3290 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003291 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003292 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3293 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003294 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003295 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
3296 << "restrict" << SourceRange(D.getIdentifierLoc());
John McCalldb40c7f2010-12-14 08:05:40 +00003297 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003298 }
Mike Stump11289f42009-09-09 15:08:12 +00003299
Douglas Gregordb9d6642011-01-26 05:01:58 +00003300 // C++0x [class.ctor]p4:
3301 // A constructor shall not be declared with a ref-qualifier.
3302 if (FTI.hasRefQualifier()) {
3303 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
3304 << FTI.RefQualifierIsLValueRef
3305 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3306 D.setInvalidType();
3307 }
3308
Douglas Gregor831c93f2008-11-05 20:51:48 +00003309 // Rebuild the function type "R" without any type qualifiers (in
3310 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00003311 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00003312 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003313 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
3314 return R;
3315
3316 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3317 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003318 EPI.RefQualifier = RQ_None;
3319
Chris Lattner38378bf2009-04-25 08:28:21 +00003320 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
John McCalldb40c7f2010-12-14 08:05:40 +00003321 Proto->getNumArgs(), EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003322}
3323
Douglas Gregor4d87df52008-12-16 21:30:33 +00003324/// CheckConstructor - Checks a fully-formed constructor for
3325/// well-formedness, issuing any diagnostics required. Returns true if
3326/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003327void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00003328 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003329 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
3330 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003331 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003332
3333 // C++ [class.copy]p3:
3334 // A declaration of a constructor for a class X is ill-formed if
3335 // its first parameter is of type (optionally cv-qualified) X and
3336 // either there are no other parameters or else all other
3337 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00003338 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00003339 ((Constructor->getNumParams() == 1) ||
3340 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00003341 Constructor->getParamDecl(1)->hasDefaultArg())) &&
3342 Constructor->getTemplateSpecializationKind()
3343 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003344 QualType ParamType = Constructor->getParamDecl(0)->getType();
3345 QualType ClassTy = Context.getTagDeclType(ClassDecl);
3346 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00003347 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00003348 const char *ConstRef
3349 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
3350 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00003351 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00003352 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00003353
3354 // FIXME: Rather that making the constructor invalid, we should endeavor
3355 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003356 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003357 }
3358 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003359}
3360
John McCalldeb646e2010-08-04 01:04:25 +00003361/// CheckDestructor - Checks a fully-formed destructor definition for
3362/// well-formedness, issuing any diagnostics required. Returns true
3363/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003364bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003365 CXXRecordDecl *RD = Destructor->getParent();
3366
3367 if (Destructor->isVirtual()) {
3368 SourceLocation Loc;
3369
3370 if (!Destructor->isImplicit())
3371 Loc = Destructor->getLocation();
3372 else
3373 Loc = RD->getLocation();
3374
3375 // If we have a virtual destructor, look up the deallocation function
3376 FunctionDecl *OperatorDelete = 0;
3377 DeclarationName Name =
3378 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003379 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003380 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00003381
3382 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00003383
3384 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003385 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003386
3387 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003388}
3389
Mike Stump11289f42009-09-09 15:08:12 +00003390static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003391FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3392 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3393 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00003394 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00003395}
3396
Douglas Gregor831c93f2008-11-05 20:51:48 +00003397/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3398/// the well-formednes of the destructor declarator @p D with type @p
3399/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003400/// emit diagnostics and set the declarator to invalid. Even if this happens,
3401/// will be updated to reflect a well-formed type for the destructor and
3402/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00003403QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00003404 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003405 // C++ [class.dtor]p1:
3406 // [...] A typedef-name that names a class is a class-name
3407 // (7.1.3); however, a typedef-name that names a class shall not
3408 // be used as the identifier in the declarator for a destructor
3409 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003410 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00003411 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00003412 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003413 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003414
3415 // C++ [class.dtor]p2:
3416 // A destructor is used to destroy objects of its class type. A
3417 // destructor takes no parameters, and no return type can be
3418 // specified for it (not even void). The address of a destructor
3419 // shall not be taken. A destructor shall not be static. A
3420 // destructor can be invoked for a const, volatile or const
3421 // volatile object. A destructor shall not be declared const,
3422 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00003423 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003424 if (!D.isInvalidType())
3425 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3426 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00003427 << SourceRange(D.getIdentifierLoc())
3428 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
3429
John McCall8e7d6562010-08-26 03:08:43 +00003430 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00003431 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003432 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003433 // Destructors don't have return types, but the parser will
3434 // happily parse something like:
3435 //
3436 // class X {
3437 // float ~X();
3438 // };
3439 //
3440 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003441 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3442 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3443 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003444 }
Mike Stump11289f42009-09-09 15:08:12 +00003445
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003446 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
Chris Lattner38378bf2009-04-25 08:28:21 +00003447 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003448 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003449 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3450 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003451 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003452 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3453 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003454 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003455 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3456 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003457 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003458 }
3459
Douglas Gregordb9d6642011-01-26 05:01:58 +00003460 // C++0x [class.dtor]p2:
3461 // A destructor shall not be declared with a ref-qualifier.
3462 if (FTI.hasRefQualifier()) {
3463 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
3464 << FTI.RefQualifierIsLValueRef
3465 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
3466 D.setInvalidType();
3467 }
3468
Douglas Gregor831c93f2008-11-05 20:51:48 +00003469 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003470 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003471 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3472
3473 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003474 FTI.freeArgs();
3475 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003476 }
3477
Mike Stump11289f42009-09-09 15:08:12 +00003478 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003479 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003480 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003481 D.setInvalidType();
3482 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003483
3484 // Rebuild the function type "R" without any type qualifiers or
3485 // parameters (in case any of the errors above fired) and with
3486 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003487 // types.
John McCalldb40c7f2010-12-14 08:05:40 +00003488 if (!D.isInvalidType())
3489 return R;
3490
Douglas Gregor95755162010-07-01 05:10:53 +00003491 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00003492 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3493 EPI.Variadic = false;
3494 EPI.TypeQuals = 0;
Douglas Gregordb9d6642011-01-26 05:01:58 +00003495 EPI.RefQualifier = RQ_None;
John McCalldb40c7f2010-12-14 08:05:40 +00003496 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Douglas Gregor831c93f2008-11-05 20:51:48 +00003497}
3498
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003499/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3500/// well-formednes of the conversion function declarator @p D with
3501/// type @p R. If there are any errors in the declarator, this routine
3502/// will emit diagnostics and return true. Otherwise, it will return
3503/// false. Either way, the type @p R will be updated to reflect a
3504/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003505void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00003506 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003507 // C++ [class.conv.fct]p1:
3508 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003509 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003510 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00003511 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003512 if (!D.isInvalidType())
3513 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3514 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3515 << SourceRange(D.getIdentifierLoc());
3516 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00003517 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003518 }
John McCall212fa2e2010-04-13 00:04:31 +00003519
3520 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3521
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003522 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003523 // Conversion functions don't have return types, but the parser will
3524 // happily parse something like:
3525 //
3526 // class X {
3527 // float operator bool();
3528 // };
3529 //
3530 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003531 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3532 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3533 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003534 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003535 }
3536
John McCall212fa2e2010-04-13 00:04:31 +00003537 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3538
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003539 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003540 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003541 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3542
3543 // Delete the parameters.
Abramo Bagnara924a8f32010-12-10 16:29:40 +00003544 D.getFunctionTypeInfo().freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003545 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003546 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003547 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003548 D.setInvalidType();
3549 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003550
John McCall212fa2e2010-04-13 00:04:31 +00003551 // Diagnose "&operator bool()" and other such nonsense. This
3552 // is actually a gcc extension which we don't support.
3553 if (Proto->getResultType() != ConvType) {
3554 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3555 << Proto->getResultType();
3556 D.setInvalidType();
3557 ConvType = Proto->getResultType();
3558 }
3559
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003560 // C++ [class.conv.fct]p4:
3561 // The conversion-type-id shall not represent a function type nor
3562 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003563 if (ConvType->isArrayType()) {
3564 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3565 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003566 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003567 } else if (ConvType->isFunctionType()) {
3568 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3569 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003570 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003571 }
3572
3573 // Rebuild the function type "R" without any parameters (in case any
3574 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003575 // return type.
John McCalldb40c7f2010-12-14 08:05:40 +00003576 if (D.isInvalidType())
3577 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003578
Douglas Gregor5fb53972009-01-14 15:45:31 +00003579 // C++0x explicit conversion operators.
3580 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003581 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003582 diag::warn_explicit_conversion_functions)
3583 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003584}
3585
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003586/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3587/// the declaration of the given C++ conversion function. This routine
3588/// is responsible for recording the conversion function in the C++
3589/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003590Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003591 assert(Conversion && "Expected to receive a conversion function declaration");
3592
Douglas Gregor4287b372008-12-12 08:25:50 +00003593 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003594
3595 // Make sure we aren't redeclaring the conversion function.
3596 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003597
3598 // C++ [class.conv.fct]p1:
3599 // [...] A conversion function is never used to convert a
3600 // (possibly cv-qualified) object to the (possibly cv-qualified)
3601 // same object type (or a reference to it), to a (possibly
3602 // cv-qualified) base class of that type (or a reference to it),
3603 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003604 // FIXME: Suppress this warning if the conversion function ends up being a
3605 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003606 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003607 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003608 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003609 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003610 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3611 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003612 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003613 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003614 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3615 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003616 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003617 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003618 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003619 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003620 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003621 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003622 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003623 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003624 }
3625
Douglas Gregor457104e2010-09-29 04:25:11 +00003626 if (FunctionTemplateDecl *ConversionTemplate
3627 = Conversion->getDescribedFunctionTemplate())
3628 return ConversionTemplate;
3629
John McCall48871652010-08-21 09:40:31 +00003630 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003631}
3632
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003633//===----------------------------------------------------------------------===//
3634// Namespace Handling
3635//===----------------------------------------------------------------------===//
3636
John McCallb1be5232010-08-26 09:15:37 +00003637
3638
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003639/// ActOnStartNamespaceDef - This is called at the start of a namespace
3640/// definition.
John McCall48871652010-08-21 09:40:31 +00003641Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003642 SourceLocation InlineLoc,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003643 SourceLocation NamespaceLoc,
John McCallb1be5232010-08-26 09:15:37 +00003644 SourceLocation IdentLoc,
3645 IdentifierInfo *II,
3646 SourceLocation LBrace,
3647 AttributeList *AttrList) {
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003648 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
3649 // For anonymous namespace, take the location of the left brace.
3650 SourceLocation Loc = II ? IdentLoc : LBrace;
Douglas Gregor086cae62010-08-19 20:55:47 +00003651 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003652 StartLoc, Loc, II);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003653 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003654
3655 Scope *DeclRegionScope = NamespcScope->getParent();
3656
Anders Carlssona7bcade2010-02-07 01:09:23 +00003657 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3658
John McCall2faf32c2010-12-10 02:59:44 +00003659 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
3660 PushNamespaceVisibilityAttr(Attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003661
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003662 if (II) {
3663 // C++ [namespace.def]p2:
Douglas Gregor412c3622010-10-22 15:24:46 +00003664 // The identifier in an original-namespace-definition shall not
3665 // have been previously defined in the declarative region in
3666 // which the original-namespace-definition appears. The
3667 // identifier in an original-namespace-definition is the name of
3668 // the namespace. Subsequently in that declarative region, it is
3669 // treated as an original-namespace-name.
3670 //
3671 // Since namespace names are unique in their scope, and we don't
3672 // look through using directives, just
3673 DeclContext::lookup_result R = CurContext->getRedeclContext()->lookup(II);
3674 NamedDecl *PrevDecl = R.first == R.second? 0 : *R.first;
Mike Stump11289f42009-09-09 15:08:12 +00003675
Douglas Gregor91f84212008-12-11 16:49:14 +00003676 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3677 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003678 if (Namespc->isInline() != OrigNS->isInline()) {
3679 // inline-ness must match
3680 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3681 << Namespc->isInline();
3682 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3683 Namespc->setInvalidDecl();
3684 // Recover by ignoring the new namespace's inline status.
3685 Namespc->setInline(OrigNS->isInline());
3686 }
3687
Douglas Gregor91f84212008-12-11 16:49:14 +00003688 // Attach this namespace decl to the chain of extended namespace
3689 // definitions.
3690 OrigNS->setNextNamespace(Namespc);
3691 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003692
Mike Stump11289f42009-09-09 15:08:12 +00003693 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003694 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003695 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003696 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003697 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003698 } else if (PrevDecl) {
3699 // This is an invalid name redefinition.
3700 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3701 << Namespc->getDeclName();
3702 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3703 Namespc->setInvalidDecl();
3704 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003705 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003706 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003707 // This is the first "real" definition of the namespace "std", so update
3708 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003709 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003710 // We had already defined a dummy namespace "std". Link this new
3711 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003712 StdNS->setNextNamespace(Namespc);
3713 StdNS->setLocation(IdentLoc);
3714 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003715 }
3716
3717 // Make our StdNamespace cache point at the first real definition of the
3718 // "std" namespace.
3719 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003720 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003721
3722 PushOnScopeChains(Namespc, DeclRegionScope);
3723 } else {
John McCall4fa53422009-10-01 00:25:31 +00003724 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003725 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003726
3727 // Link the anonymous namespace into its parent.
3728 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003729 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003730 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3731 PrevDecl = TU->getAnonymousNamespace();
3732 TU->setAnonymousNamespace(Namespc);
3733 } else {
3734 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3735 PrevDecl = ND->getAnonymousNamespace();
3736 ND->setAnonymousNamespace(Namespc);
3737 }
3738
3739 // Link the anonymous namespace with its previous declaration.
3740 if (PrevDecl) {
3741 assert(PrevDecl->isAnonymousNamespace());
3742 assert(!PrevDecl->getNextNamespace());
3743 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3744 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003745
3746 if (Namespc->isInline() != PrevDecl->isInline()) {
3747 // inline-ness must match
3748 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3749 << Namespc->isInline();
3750 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3751 Namespc->setInvalidDecl();
3752 // Recover by ignoring the new namespace's inline status.
3753 Namespc->setInline(PrevDecl->isInline());
3754 }
John McCall0db42252009-12-16 02:06:49 +00003755 }
John McCall4fa53422009-10-01 00:25:31 +00003756
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003757 CurContext->addDecl(Namespc);
3758
John McCall4fa53422009-10-01 00:25:31 +00003759 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3760 // behaves as if it were replaced by
3761 // namespace unique { /* empty body */ }
3762 // using namespace unique;
3763 // namespace unique { namespace-body }
3764 // where all occurrences of 'unique' in a translation unit are
3765 // replaced by the same identifier and this identifier differs
3766 // from all other identifiers in the entire program.
3767
3768 // We just create the namespace with an empty name and then add an
3769 // implicit using declaration, just like the standard suggests.
3770 //
3771 // CodeGen enforces the "universally unique" aspect by giving all
3772 // declarations semantically contained within an anonymous
3773 // namespace internal linkage.
3774
John McCall0db42252009-12-16 02:06:49 +00003775 if (!PrevDecl) {
3776 UsingDirectiveDecl* UD
3777 = UsingDirectiveDecl::Create(Context, CurContext,
3778 /* 'using' */ LBrace,
3779 /* 'namespace' */ SourceLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00003780 /* qualifier */ NestedNameSpecifierLoc(),
John McCall0db42252009-12-16 02:06:49 +00003781 /* identifier */ SourceLocation(),
3782 Namespc,
3783 /* Ancestor */ CurContext);
3784 UD->setImplicit();
3785 CurContext->addDecl(UD);
3786 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003787 }
3788
3789 // Although we could have an invalid decl (i.e. the namespace name is a
3790 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003791 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3792 // for the namespace has the declarations that showed up in that particular
3793 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003794 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003795 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003796}
3797
Sebastian Redla6602e92009-11-23 15:34:23 +00003798/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3799/// is a namespace alias, returns the namespace it points to.
3800static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3801 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3802 return AD->getNamespace();
3803 return dyn_cast_or_null<NamespaceDecl>(D);
3804}
3805
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003806/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3807/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003808void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003809 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3810 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003811 Namespc->setRBraceLoc(RBrace);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003812 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003813 if (Namespc->hasAttr<VisibilityAttr>())
3814 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003815}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003816
John McCall28a0cf72010-08-25 07:42:41 +00003817CXXRecordDecl *Sema::getStdBadAlloc() const {
3818 return cast_or_null<CXXRecordDecl>(
3819 StdBadAlloc.get(Context.getExternalSource()));
3820}
3821
3822NamespaceDecl *Sema::getStdNamespace() const {
3823 return cast_or_null<NamespaceDecl>(
3824 StdNamespace.get(Context.getExternalSource()));
3825}
3826
Douglas Gregorcdf87022010-06-29 17:53:46 +00003827/// \brief Retrieve the special "std" namespace, which may require us to
3828/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003829NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003830 if (!StdNamespace) {
3831 // The "std" namespace has not yet been defined, so build one implicitly.
3832 StdNamespace = NamespaceDecl::Create(Context,
3833 Context.getTranslationUnitDecl(),
Abramo Bagnarab5545be2011-03-08 12:38:20 +00003834 SourceLocation(), SourceLocation(),
Douglas Gregorcdf87022010-06-29 17:53:46 +00003835 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003836 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003837 }
3838
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003839 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003840}
3841
Douglas Gregora172e082011-03-26 22:25:30 +00003842/// \brief Determine whether a using statement is in a context where it will be
3843/// apply in all contexts.
3844static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
3845 switch (CurContext->getDeclKind()) {
3846 case Decl::TranslationUnit:
3847 return true;
3848 case Decl::LinkageSpec:
3849 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
3850 default:
3851 return false;
3852 }
3853}
3854
John McCall48871652010-08-21 09:40:31 +00003855Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003856 SourceLocation UsingLoc,
3857 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003858 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003859 SourceLocation IdentLoc,
3860 IdentifierInfo *NamespcName,
3861 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003862 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3863 assert(NamespcName && "Invalid NamespcName.");
3864 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
John McCall9b72f892010-11-10 02:40:36 +00003865
3866 // This can only happen along a recovery path.
3867 while (S->getFlags() & Scope::TemplateParamScope)
3868 S = S->getParent();
Douglas Gregor889ceb72009-02-03 19:21:40 +00003869 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003870
Douglas Gregor889ceb72009-02-03 19:21:40 +00003871 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003872 NestedNameSpecifier *Qualifier = 0;
3873 if (SS.isSet())
3874 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3875
Douglas Gregor34074322009-01-14 22:20:51 +00003876 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003877 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3878 LookupParsedName(R, S, &SS);
3879 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003880 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003881
Douglas Gregorcdf87022010-06-29 17:53:46 +00003882 if (R.empty()) {
3883 // Allow "using namespace std;" or "using namespace ::std;" even if
3884 // "std" hasn't been defined yet, for GCC compatibility.
3885 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3886 NamespcName->isStr("std")) {
3887 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003888 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003889 R.resolveKind();
3890 }
3891 // Otherwise, attempt typo correction.
3892 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3893 CTC_NoKeywords, 0)) {
3894 if (R.getAsSingle<NamespaceDecl>() ||
3895 R.getAsSingle<NamespaceAliasDecl>()) {
3896 if (DeclContext *DC = computeDeclContext(SS, false))
3897 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3898 << NamespcName << DC << Corrected << SS.getRange()
3899 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3900 else
3901 Diag(IdentLoc, diag::err_using_directive_suggest)
3902 << NamespcName << Corrected
3903 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3904 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3905 << Corrected;
3906
3907 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003908 } else {
3909 R.clear();
3910 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003911 }
3912 }
3913 }
3914
John McCall9f3059a2009-10-09 21:13:30 +00003915 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003916 NamedDecl *Named = R.getFoundDecl();
3917 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3918 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003919 // C++ [namespace.udir]p1:
3920 // A using-directive specifies that the names in the nominated
3921 // namespace can be used in the scope in which the
3922 // using-directive appears after the using-directive. During
3923 // unqualified name lookup (3.4.1), the names appear as if they
3924 // were declared in the nearest enclosing namespace which
3925 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003926 // namespace. [Note: in this context, "contains" means "contains
3927 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003928
3929 // Find enclosing context containing both using-directive and
3930 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003931 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003932 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3933 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3934 CommonAncestor = CommonAncestor->getParent();
3935
Sebastian Redla6602e92009-11-23 15:34:23 +00003936 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor12441b32011-02-25 16:33:46 +00003937 SS.getWithLocInContext(Context),
Sebastian Redla6602e92009-11-23 15:34:23 +00003938 IdentLoc, Named, CommonAncestor);
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00003939
Douglas Gregora172e082011-03-26 22:25:30 +00003940 if (IsUsingDirectiveInToplevelContext(CurContext) &&
Nico Webercc2b8712011-04-02 19:45:15 +00003941 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
Douglas Gregor96a4bdd2011-03-18 16:10:52 +00003942 Diag(IdentLoc, diag::warn_using_directive_in_header);
3943 }
3944
Douglas Gregor889ceb72009-02-03 19:21:40 +00003945 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003946 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003947 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003948 }
3949
Douglas Gregor889ceb72009-02-03 19:21:40 +00003950 // FIXME: We ignore attributes for now.
John McCall48871652010-08-21 09:40:31 +00003951 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003952}
3953
3954void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3955 // If scope has associated entity, then using directive is at namespace
3956 // or translation unit scope. We add UsingDirectiveDecls, into
3957 // it's lookup structure.
3958 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003959 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003960 else
3961 // Otherwise it is block-sope. using-directives will affect lookup
3962 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003963 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003964}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003965
Douglas Gregorfec52632009-06-20 00:51:54 +00003966
John McCall48871652010-08-21 09:40:31 +00003967Decl *Sema::ActOnUsingDeclaration(Scope *S,
John McCall9b72f892010-11-10 02:40:36 +00003968 AccessSpecifier AS,
3969 bool HasUsingKeyword,
3970 SourceLocation UsingLoc,
3971 CXXScopeSpec &SS,
3972 UnqualifiedId &Name,
3973 AttributeList *AttrList,
3974 bool IsTypeName,
3975 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003976 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003977
Douglas Gregor220f4272009-11-04 16:30:06 +00003978 switch (Name.getKind()) {
3979 case UnqualifiedId::IK_Identifier:
3980 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003981 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003982 case UnqualifiedId::IK_ConversionFunctionId:
3983 break;
3984
3985 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003986 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003987 // C++0x inherited constructors.
3988 if (getLangOptions().CPlusPlus0x) break;
3989
Douglas Gregor220f4272009-11-04 16:30:06 +00003990 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3991 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003992 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003993
3994 case UnqualifiedId::IK_DestructorName:
3995 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3996 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003997 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003998
3999 case UnqualifiedId::IK_TemplateId:
4000 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
4001 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00004002 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00004003 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004004
4005 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
4006 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00004007 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00004008 return 0;
John McCall3969e302009-12-08 07:46:18 +00004009
John McCalla0097262009-12-11 02:10:03 +00004010 // Warn about using declarations.
4011 // TODO: store that the declaration was written without 'using' and
4012 // talk about access decls instead of using decls in the
4013 // diagnostics.
4014 if (!HasUsingKeyword) {
4015 UsingLoc = Name.getSourceRange().getBegin();
4016
4017 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00004018 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00004019 }
4020
Douglas Gregorc4356532010-12-16 00:46:58 +00004021 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
4022 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
4023 return 0;
4024
John McCall3f746822009-11-17 05:59:44 +00004025 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004026 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004027 /* IsInstantiation */ false,
4028 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00004029 if (UD)
4030 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00004031
John McCall48871652010-08-21 09:40:31 +00004032 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00004033}
4034
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004035/// \brief Determine whether a using declaration considers the given
4036/// declarations as "equivalent", e.g., if they are redeclarations of
4037/// the same entity or are both typedefs of the same type.
4038static bool
4039IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
4040 bool &SuppressRedeclaration) {
4041 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
4042 SuppressRedeclaration = false;
4043 return true;
4044 }
4045
4046 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
4047 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
4048 SuppressRedeclaration = true;
4049 return Context.hasSameType(TD1->getUnderlyingType(),
4050 TD2->getUnderlyingType());
4051 }
4052
4053 return false;
4054}
4055
4056
John McCall84d87672009-12-10 09:41:52 +00004057/// Determines whether to create a using shadow decl for a particular
4058/// decl, given the set of decls existing prior to this using lookup.
4059bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
4060 const LookupResult &Previous) {
4061 // Diagnose finding a decl which is not from a base class of the
4062 // current class. We do this now because there are cases where this
4063 // function will silently decide not to build a shadow decl, which
4064 // will pre-empt further diagnostics.
4065 //
4066 // We don't need to do this in C++0x because we do the check once on
4067 // the qualifier.
4068 //
4069 // FIXME: diagnose the following if we care enough:
4070 // struct A { int foo; };
4071 // struct B : A { using A::foo; };
4072 // template <class T> struct C : A {};
4073 // template <class T> struct D : C<T> { using B::foo; } // <---
4074 // This is invalid (during instantiation) in C++03 because B::foo
4075 // resolves to the using decl in B, which is not a base class of D<T>.
4076 // We can't diagnose it immediately because C<T> is an unknown
4077 // specialization. The UsingShadowDecl in D<T> then points directly
4078 // to A::foo, which will look well-formed when we instantiate.
4079 // The right solution is to not collapse the shadow-decl chain.
4080 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
4081 DeclContext *OrigDC = Orig->getDeclContext();
4082
4083 // Handle enums and anonymous structs.
4084 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
4085 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
4086 while (OrigRec->isAnonymousStructOrUnion())
4087 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
4088
4089 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
4090 if (OrigDC == CurContext) {
4091 Diag(Using->getLocation(),
4092 diag::err_using_decl_nested_name_specifier_is_current_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004093 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00004094 Diag(Orig->getLocation(), diag::note_using_decl_target);
4095 return true;
4096 }
4097
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004098 Diag(Using->getQualifierLoc().getBeginLoc(),
John McCall84d87672009-12-10 09:41:52 +00004099 diag::err_using_decl_nested_name_specifier_is_not_base_class)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004100 << Using->getQualifier()
John McCall84d87672009-12-10 09:41:52 +00004101 << cast<CXXRecordDecl>(CurContext)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004102 << Using->getQualifierLoc().getSourceRange();
John McCall84d87672009-12-10 09:41:52 +00004103 Diag(Orig->getLocation(), diag::note_using_decl_target);
4104 return true;
4105 }
4106 }
4107
4108 if (Previous.empty()) return false;
4109
4110 NamedDecl *Target = Orig;
4111 if (isa<UsingShadowDecl>(Target))
4112 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4113
John McCalla17e83e2009-12-11 02:33:26 +00004114 // If the target happens to be one of the previous declarations, we
4115 // don't have a conflict.
4116 //
4117 // FIXME: but we might be increasing its access, in which case we
4118 // should redeclare it.
4119 NamedDecl *NonTag = 0, *Tag = 0;
4120 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4121 I != E; ++I) {
4122 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00004123 bool Result;
4124 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
4125 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00004126
4127 (isa<TagDecl>(D) ? Tag : NonTag) = D;
4128 }
4129
John McCall84d87672009-12-10 09:41:52 +00004130 if (Target->isFunctionOrFunctionTemplate()) {
4131 FunctionDecl *FD;
4132 if (isa<FunctionTemplateDecl>(Target))
4133 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
4134 else
4135 FD = cast<FunctionDecl>(Target);
4136
4137 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00004138 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00004139 case Ovl_Overload:
4140 return false;
4141
4142 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00004143 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004144 break;
4145
4146 // We found a decl with the exact signature.
4147 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00004148 // If we're in a record, we want to hide the target, so we
4149 // return true (without a diagnostic) to tell the caller not to
4150 // build a shadow decl.
4151 if (CurContext->isRecord())
4152 return true;
4153
4154 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00004155 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004156 break;
4157 }
4158
4159 Diag(Target->getLocation(), diag::note_using_decl_target);
4160 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
4161 return true;
4162 }
4163
4164 // Target is not a function.
4165
John McCall84d87672009-12-10 09:41:52 +00004166 if (isa<TagDecl>(Target)) {
4167 // No conflict between a tag and a non-tag.
4168 if (!Tag) return false;
4169
John McCalle29c5cd2009-12-10 19:51:03 +00004170 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004171 Diag(Target->getLocation(), diag::note_using_decl_target);
4172 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
4173 return true;
4174 }
4175
4176 // No conflict between a tag and a non-tag.
4177 if (!NonTag) return false;
4178
John McCalle29c5cd2009-12-10 19:51:03 +00004179 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00004180 Diag(Target->getLocation(), diag::note_using_decl_target);
4181 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
4182 return true;
4183}
4184
John McCall3f746822009-11-17 05:59:44 +00004185/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00004186UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00004187 UsingDecl *UD,
4188 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00004189
4190 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00004191 NamedDecl *Target = Orig;
4192 if (isa<UsingShadowDecl>(Target)) {
4193 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
4194 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00004195 }
4196
4197 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00004198 = UsingShadowDecl::Create(Context, CurContext,
4199 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00004200 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00004201
4202 Shadow->setAccess(UD->getAccess());
4203 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
4204 Shadow->setInvalidDecl();
4205
John McCall3f746822009-11-17 05:59:44 +00004206 if (S)
John McCall3969e302009-12-08 07:46:18 +00004207 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00004208 else
John McCall3969e302009-12-08 07:46:18 +00004209 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00004210
John McCall3969e302009-12-08 07:46:18 +00004211
John McCall84d87672009-12-10 09:41:52 +00004212 return Shadow;
4213}
John McCall3969e302009-12-08 07:46:18 +00004214
John McCall84d87672009-12-10 09:41:52 +00004215/// Hides a using shadow declaration. This is required by the current
4216/// using-decl implementation when a resolvable using declaration in a
4217/// class is followed by a declaration which would hide or override
4218/// one or more of the using decl's targets; for example:
4219///
4220/// struct Base { void foo(int); };
4221/// struct Derived : Base {
4222/// using Base::foo;
4223/// void foo(int);
4224/// };
4225///
4226/// The governing language is C++03 [namespace.udecl]p12:
4227///
4228/// When a using-declaration brings names from a base class into a
4229/// derived class scope, member functions in the derived class
4230/// override and/or hide member functions with the same name and
4231/// parameter types in a base class (rather than conflicting).
4232///
4233/// There are two ways to implement this:
4234/// (1) optimistically create shadow decls when they're not hidden
4235/// by existing declarations, or
4236/// (2) don't create any shadow decls (or at least don't make them
4237/// visible) until we've fully parsed/instantiated the class.
4238/// The problem with (1) is that we might have to retroactively remove
4239/// a shadow decl, which requires several O(n) operations because the
4240/// decl structures are (very reasonably) not designed for removal.
4241/// (2) avoids this but is very fiddly and phase-dependent.
4242void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00004243 if (Shadow->getDeclName().getNameKind() ==
4244 DeclarationName::CXXConversionFunctionName)
4245 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
4246
John McCall84d87672009-12-10 09:41:52 +00004247 // Remove it from the DeclContext...
4248 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004249
John McCall84d87672009-12-10 09:41:52 +00004250 // ...and the scope, if applicable...
4251 if (S) {
John McCall48871652010-08-21 09:40:31 +00004252 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00004253 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00004254 }
4255
John McCall84d87672009-12-10 09:41:52 +00004256 // ...and the using decl.
4257 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
4258
4259 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00004260 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00004261}
4262
John McCalle61f2ba2009-11-18 02:36:19 +00004263/// Builds a using declaration.
4264///
4265/// \param IsInstantiation - Whether this call arises from an
4266/// instantiation of an unresolved using declaration. We treat
4267/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00004268NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
4269 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004270 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004271 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00004272 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00004273 bool IsInstantiation,
4274 bool IsTypeName,
4275 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00004276 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004277 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00004278 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00004279
Anders Carlssonf038fc22009-08-28 05:49:21 +00004280 // FIXME: We ignore attributes for now.
Mike Stump11289f42009-09-09 15:08:12 +00004281
Anders Carlsson59140b32009-08-28 03:16:11 +00004282 if (SS.isEmpty()) {
4283 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00004284 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00004285 }
Mike Stump11289f42009-09-09 15:08:12 +00004286
John McCall84d87672009-12-10 09:41:52 +00004287 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004288 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00004289 ForRedeclaration);
4290 Previous.setHideTags(false);
4291 if (S) {
4292 LookupName(Previous, S);
4293
4294 // It is really dumb that we have to do this.
4295 LookupResult::Filter F = Previous.makeFilter();
4296 while (F.hasNext()) {
4297 NamedDecl *D = F.next();
4298 if (!isDeclInScope(D, CurContext, S))
4299 F.erase();
4300 }
4301 F.done();
4302 } else {
4303 assert(IsInstantiation && "no scope in non-instantiation");
4304 assert(CurContext->isRecord() && "scope not record in instantiation");
4305 LookupQualifiedName(Previous, CurContext);
4306 }
4307
John McCall84d87672009-12-10 09:41:52 +00004308 // Check for invalid redeclarations.
4309 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
4310 return 0;
4311
4312 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00004313 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
4314 return 0;
4315
John McCall84c16cf2009-11-12 03:15:40 +00004316 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004317 NamedDecl *D;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004318 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCall84c16cf2009-11-12 03:15:40 +00004319 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00004320 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00004321 // FIXME: not all declaration name kinds are legal here
4322 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
4323 UsingLoc, TypenameLoc,
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004324 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004325 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00004326 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004327 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
4328 QualifierLoc, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00004329 }
John McCallb96ec562009-12-04 22:46:56 +00004330 } else {
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004331 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
4332 NameInfo, IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00004333 }
John McCallb96ec562009-12-04 22:46:56 +00004334 D->setAccess(AS);
4335 CurContext->addDecl(D);
4336
4337 if (!LookupContext) return D;
4338 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00004339
John McCall0b66eb32010-05-01 00:40:08 +00004340 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00004341 UD->setInvalidDecl();
4342 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00004343 }
4344
Sebastian Redl08905022011-02-05 19:23:19 +00004345 // Constructor inheriting using decls get special treatment.
4346 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Sebastian Redlc1f8e492011-03-12 13:44:32 +00004347 if (CheckInheritedConstructorUsingDecl(UD))
4348 UD->setInvalidDecl();
Sebastian Redl08905022011-02-05 19:23:19 +00004349 return UD;
4350 }
4351
4352 // Otherwise, look up the target name.
John McCall3969e302009-12-08 07:46:18 +00004353
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004354 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00004355
John McCall3969e302009-12-08 07:46:18 +00004356 // Unlike most lookups, we don't always want to hide tag
4357 // declarations: tag names are visible through the using declaration
4358 // even if hidden by ordinary names, *except* in a dependent context
4359 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00004360 if (!IsInstantiation)
4361 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00004362
John McCall27b18f82009-11-17 02:14:36 +00004363 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00004364
John McCall9f3059a2009-10-09 21:13:30 +00004365 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00004366 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00004367 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004368 UD->setInvalidDecl();
4369 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004370 }
4371
John McCallb96ec562009-12-04 22:46:56 +00004372 if (R.isAmbiguous()) {
4373 UD->setInvalidDecl();
4374 return UD;
4375 }
Mike Stump11289f42009-09-09 15:08:12 +00004376
John McCalle61f2ba2009-11-18 02:36:19 +00004377 if (IsTypeName) {
4378 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00004379 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004380 Diag(IdentLoc, diag::err_using_typename_non_type);
4381 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
4382 Diag((*I)->getUnderlyingDecl()->getLocation(),
4383 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004384 UD->setInvalidDecl();
4385 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004386 }
4387 } else {
4388 // If we asked for a non-typename and we got a type, error out,
4389 // but only if this is an instantiation of an unresolved using
4390 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00004391 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004392 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
4393 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00004394 UD->setInvalidDecl();
4395 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00004396 }
Anders Carlsson59140b32009-08-28 03:16:11 +00004397 }
4398
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004399 // C++0x N2914 [namespace.udecl]p6:
4400 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00004401 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004402 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
4403 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00004404 UD->setInvalidDecl();
4405 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00004406 }
Mike Stump11289f42009-09-09 15:08:12 +00004407
John McCall84d87672009-12-10 09:41:52 +00004408 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4409 if (!CheckUsingShadowDecl(UD, *I, Previous))
4410 BuildUsingShadowDecl(S, UD, *I);
4411 }
John McCall3f746822009-11-17 05:59:44 +00004412
4413 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00004414}
4415
Sebastian Redl08905022011-02-05 19:23:19 +00004416/// Additional checks for a using declaration referring to a constructor name.
4417bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
4418 if (UD->isTypeName()) {
4419 // FIXME: Cannot specify typename when specifying constructor
4420 return true;
4421 }
4422
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004423 const Type *SourceType = UD->getQualifier()->getAsType();
Sebastian Redl08905022011-02-05 19:23:19 +00004424 assert(SourceType &&
4425 "Using decl naming constructor doesn't have type in scope spec.");
4426 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
4427
4428 // Check whether the named type is a direct base class.
4429 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
4430 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
4431 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
4432 BaseIt != BaseE; ++BaseIt) {
4433 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
4434 if (CanonicalSourceType == BaseType)
4435 break;
4436 }
4437
4438 if (BaseIt == BaseE) {
4439 // Did not find SourceType in the bases.
4440 Diag(UD->getUsingLocation(),
4441 diag::err_using_decl_constructor_not_in_direct_base)
4442 << UD->getNameInfo().getSourceRange()
4443 << QualType(SourceType, 0) << TargetClass;
4444 return true;
4445 }
4446
4447 BaseIt->setInheritConstructors();
4448
4449 return false;
4450}
4451
John McCall84d87672009-12-10 09:41:52 +00004452/// Checks that the given using declaration is not an invalid
4453/// redeclaration. Note that this is checking only for the using decl
4454/// itself, not for any ill-formedness among the UsingShadowDecls.
4455bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
4456 bool isTypeName,
4457 const CXXScopeSpec &SS,
4458 SourceLocation NameLoc,
4459 const LookupResult &Prev) {
4460 // C++03 [namespace.udecl]p8:
4461 // C++0x [namespace.udecl]p10:
4462 // A using-declaration is a declaration and can therefore be used
4463 // repeatedly where (and only where) multiple declarations are
4464 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00004465 //
John McCall032092f2010-11-29 18:01:58 +00004466 // That's in non-member contexts.
4467 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00004468 return false;
4469
4470 NestedNameSpecifier *Qual
4471 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
4472
4473 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
4474 NamedDecl *D = *I;
4475
4476 bool DTypename;
4477 NestedNameSpecifier *DQual;
4478 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
4479 DTypename = UD->isTypeName();
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004480 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004481 } else if (UnresolvedUsingValueDecl *UD
4482 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4483 DTypename = false;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004484 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004485 } else if (UnresolvedUsingTypenameDecl *UD
4486 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4487 DTypename = true;
Douglas Gregora9d87bc2011-02-25 00:36:19 +00004488 DQual = UD->getQualifier();
John McCall84d87672009-12-10 09:41:52 +00004489 } else continue;
4490
4491 // using decls differ if one says 'typename' and the other doesn't.
4492 // FIXME: non-dependent using decls?
4493 if (isTypeName != DTypename) continue;
4494
4495 // using decls differ if they name different scopes (but note that
4496 // template instantiation can cause this check to trigger when it
4497 // didn't before instantiation).
4498 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
4499 Context.getCanonicalNestedNameSpecifier(DQual))
4500 continue;
4501
4502 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00004503 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00004504 return true;
4505 }
4506
4507 return false;
4508}
4509
John McCall3969e302009-12-08 07:46:18 +00004510
John McCallb96ec562009-12-04 22:46:56 +00004511/// Checks that the given nested-name qualifier used in a using decl
4512/// in the current context is appropriately related to the current
4513/// scope. If an error is found, diagnoses it and returns true.
4514bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
4515 const CXXScopeSpec &SS,
4516 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004517 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004518
John McCall3969e302009-12-08 07:46:18 +00004519 if (!CurContext->isRecord()) {
4520 // C++03 [namespace.udecl]p3:
4521 // C++0x [namespace.udecl]p8:
4522 // A using-declaration for a class member shall be a member-declaration.
4523
4524 // If we weren't able to compute a valid scope, it must be a
4525 // dependent class scope.
4526 if (!NamedContext || NamedContext->isRecord()) {
4527 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4528 << SS.getRange();
4529 return true;
4530 }
4531
4532 // Otherwise, everything is known to be fine.
4533 return false;
4534 }
4535
4536 // The current scope is a record.
4537
4538 // If the named context is dependent, we can't decide much.
4539 if (!NamedContext) {
4540 // FIXME: in C++0x, we can diagnose if we can prove that the
4541 // nested-name-specifier does not refer to a base class, which is
4542 // still possible in some cases.
4543
4544 // Otherwise we have to conservatively report that things might be
4545 // okay.
4546 return false;
4547 }
4548
4549 if (!NamedContext->isRecord()) {
4550 // Ideally this would point at the last name in the specifier,
4551 // but we don't have that level of source info.
4552 Diag(SS.getRange().getBegin(),
4553 diag::err_using_decl_nested_name_specifier_is_not_class)
4554 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4555 return true;
4556 }
4557
Douglas Gregor7c842292010-12-21 07:41:49 +00004558 if (!NamedContext->isDependentContext() &&
4559 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
4560 return true;
4561
John McCall3969e302009-12-08 07:46:18 +00004562 if (getLangOptions().CPlusPlus0x) {
4563 // C++0x [namespace.udecl]p3:
4564 // In a using-declaration used as a member-declaration, the
4565 // nested-name-specifier shall name a base class of the class
4566 // being defined.
4567
4568 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4569 cast<CXXRecordDecl>(NamedContext))) {
4570 if (CurContext == NamedContext) {
4571 Diag(NameLoc,
4572 diag::err_using_decl_nested_name_specifier_is_current_class)
4573 << SS.getRange();
4574 return true;
4575 }
4576
4577 Diag(SS.getRange().getBegin(),
4578 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4579 << (NestedNameSpecifier*) SS.getScopeRep()
4580 << cast<CXXRecordDecl>(CurContext)
4581 << SS.getRange();
4582 return true;
4583 }
4584
4585 return false;
4586 }
4587
4588 // C++03 [namespace.udecl]p4:
4589 // A using-declaration used as a member-declaration shall refer
4590 // to a member of a base class of the class being defined [etc.].
4591
4592 // Salient point: SS doesn't have to name a base class as long as
4593 // lookup only finds members from base classes. Therefore we can
4594 // diagnose here only if we can prove that that can't happen,
4595 // i.e. if the class hierarchies provably don't intersect.
4596
4597 // TODO: it would be nice if "definitely valid" results were cached
4598 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4599 // need to be repeated.
4600
4601 struct UserData {
4602 llvm::DenseSet<const CXXRecordDecl*> Bases;
4603
4604 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4605 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4606 Data->Bases.insert(Base);
4607 return true;
4608 }
4609
4610 bool hasDependentBases(const CXXRecordDecl *Class) {
4611 return !Class->forallBases(collect, this);
4612 }
4613
4614 /// Returns true if the base is dependent or is one of the
4615 /// accumulated base classes.
4616 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4617 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4618 return !Data->Bases.count(Base);
4619 }
4620
4621 bool mightShareBases(const CXXRecordDecl *Class) {
4622 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4623 }
4624 };
4625
4626 UserData Data;
4627
4628 // Returns false if we find a dependent base.
4629 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4630 return false;
4631
4632 // Returns false if the class has a dependent base or if it or one
4633 // of its bases is present in the base set of the current context.
4634 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4635 return false;
4636
4637 Diag(SS.getRange().getBegin(),
4638 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4639 << (NestedNameSpecifier*) SS.getScopeRep()
4640 << cast<CXXRecordDecl>(CurContext)
4641 << SS.getRange();
4642
4643 return true;
John McCallb96ec562009-12-04 22:46:56 +00004644}
4645
John McCall48871652010-08-21 09:40:31 +00004646Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004647 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004648 SourceLocation AliasLoc,
4649 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004650 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004651 SourceLocation IdentLoc,
4652 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004653
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004654 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004655 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4656 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004657
Anders Carlssondca83c42009-03-28 06:23:46 +00004658 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004659 NamedDecl *PrevDecl
4660 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4661 ForRedeclaration);
4662 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4663 PrevDecl = 0;
4664
4665 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004666 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004667 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004668 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004669 // FIXME: At some point, we'll want to create the (redundant)
4670 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004671 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004672 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004673 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004674 }
Mike Stump11289f42009-09-09 15:08:12 +00004675
Anders Carlssondca83c42009-03-28 06:23:46 +00004676 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4677 diag::err_redefinition_different_kind;
4678 Diag(AliasLoc, DiagID) << Alias;
4679 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004680 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004681 }
4682
John McCall27b18f82009-11-17 02:14:36 +00004683 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004684 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004685
John McCall9f3059a2009-10-09 21:13:30 +00004686 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004687 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4688 CTC_NoKeywords, 0)) {
4689 if (R.getAsSingle<NamespaceDecl>() ||
4690 R.getAsSingle<NamespaceAliasDecl>()) {
4691 if (DeclContext *DC = computeDeclContext(SS, false))
4692 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4693 << Ident << DC << Corrected << SS.getRange()
4694 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4695 else
4696 Diag(IdentLoc, diag::err_using_directive_suggest)
4697 << Ident << Corrected
4698 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4699
4700 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4701 << Corrected;
4702
4703 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004704 } else {
4705 R.clear();
4706 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004707 }
4708 }
4709
4710 if (R.empty()) {
4711 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004712 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004713 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004714 }
Mike Stump11289f42009-09-09 15:08:12 +00004715
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004716 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004717 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
Douglas Gregorc05ba2e2011-02-25 17:08:07 +00004718 Alias, SS.getWithLocInContext(Context),
John McCall9f3059a2009-10-09 21:13:30 +00004719 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004720
John McCalld8d0d432010-02-16 06:53:13 +00004721 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004722 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004723}
4724
Douglas Gregora57478e2010-05-01 15:04:51 +00004725namespace {
4726 /// \brief Scoped object used to handle the state changes required in Sema
4727 /// to implicitly define the body of a C++ member function;
4728 class ImplicitlyDefinedFunctionScope {
4729 Sema &S;
John McCallc1465822011-02-14 07:13:47 +00004730 Sema::ContextRAII SavedContext;
Douglas Gregora57478e2010-05-01 15:04:51 +00004731
4732 public:
4733 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
John McCallc1465822011-02-14 07:13:47 +00004734 : S(S), SavedContext(S, Method)
Douglas Gregora57478e2010-05-01 15:04:51 +00004735 {
Douglas Gregora57478e2010-05-01 15:04:51 +00004736 S.PushFunctionScope();
4737 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4738 }
4739
4740 ~ImplicitlyDefinedFunctionScope() {
4741 S.PopExpressionEvaluationContext();
4742 S.PopFunctionOrBlockScope();
Douglas Gregora57478e2010-05-01 15:04:51 +00004743 }
4744 };
4745}
4746
Sebastian Redlc15c3262010-09-13 22:02:47 +00004747static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4748 CXXRecordDecl *D) {
4749 ASTContext &Context = Self.Context;
4750 QualType ClassType = Context.getTypeDeclType(D);
4751 DeclarationName ConstructorName
4752 = Context.DeclarationNames.getCXXConstructorName(
4753 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4754
4755 DeclContext::lookup_const_iterator Con, ConEnd;
4756 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4757 Con != ConEnd; ++Con) {
4758 // FIXME: In C++0x, a constructor template can be a default constructor.
4759 if (isa<FunctionTemplateDecl>(*Con))
4760 continue;
4761
4762 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4763 if (Constructor->isDefaultConstructor())
4764 return Constructor;
4765 }
4766 return 0;
4767}
4768
Douglas Gregor0be31a22010-07-02 17:43:08 +00004769CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4770 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004771 // C++ [class.ctor]p5:
4772 // A default constructor for a class X is a constructor of class X
4773 // that can be called without an argument. If there is no
4774 // user-declared constructor for class X, a default constructor is
4775 // implicitly declared. An implicitly-declared default constructor
4776 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004777 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4778 "Should not build implicit default constructor!");
4779
Douglas Gregor6d880b12010-07-01 22:31:05 +00004780 // C++ [except.spec]p14:
4781 // An implicitly declared special member function (Clause 12) shall have an
4782 // exception-specification. [...]
4783 ImplicitExceptionSpecification ExceptSpec(Context);
4784
Sebastian Redlfa453cf2011-03-12 11:50:43 +00004785 // Direct base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00004786 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4787 BEnd = ClassDecl->bases_end();
4788 B != BEnd; ++B) {
4789 if (B->isVirtual()) // Handled below.
4790 continue;
4791
Douglas Gregor9672f922010-07-03 00:47:00 +00004792 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4793 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4794 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4795 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004796 else if (CXXConstructorDecl *Constructor
4797 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004798 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004799 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004800 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00004801
4802 // Virtual base-class constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00004803 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4804 BEnd = ClassDecl->vbases_end();
4805 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004806 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4807 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4808 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4809 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4810 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004811 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004812 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004813 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004814 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00004815
4816 // Field constructors.
Douglas Gregor6d880b12010-07-01 22:31:05 +00004817 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4818 FEnd = ClassDecl->field_end();
4819 F != FEnd; ++F) {
4820 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004821 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4822 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4823 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4824 ExceptSpec.CalledDecl(
4825 DeclareImplicitDefaultConstructor(FieldClassDecl));
4826 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004827 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004828 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004829 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004830 }
John McCalldb40c7f2010-12-14 08:05:40 +00004831
4832 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00004833 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00004834 EPI.NumExceptions = ExceptSpec.size();
4835 EPI.Exceptions = ExceptSpec.data();
Sebastian Redl7c6c9e92011-03-06 10:52:04 +00004836
Douglas Gregor6d880b12010-07-01 22:31:05 +00004837 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004838 CanQualType ClassType
4839 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00004840 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004841 DeclarationName Name
4842 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004843 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004844 CXXConstructorDecl *DefaultCon
Abramo Bagnaradff19302011-03-08 08:55:46 +00004845 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004846 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00004847 0, 0, EPI),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004848 /*TInfo=*/0,
4849 /*isExplicit=*/false,
4850 /*isInline=*/true,
4851 /*isImplicitlyDeclared=*/true);
4852 DefaultCon->setAccess(AS_public);
4853 DefaultCon->setImplicit();
4854 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004855
4856 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004857 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4858
Douglas Gregor0be31a22010-07-02 17:43:08 +00004859 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004860 PushOnScopeChains(DefaultCon, S, false);
4861 ClassDecl->addDecl(DefaultCon);
4862
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004863 return DefaultCon;
4864}
4865
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004866void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4867 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004868 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004869 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004870 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004871
Anders Carlsson423f5d82010-04-23 16:04:08 +00004872 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004873 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004874
Douglas Gregora57478e2010-05-01 15:04:51 +00004875 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00004876 DiagnosticErrorTrap Trap(Diags);
Alexis Hunt1d792652011-01-08 20:30:50 +00004877 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00004878 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004879 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004880 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004881 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004882 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004883 }
Douglas Gregor73193272010-09-20 16:48:21 +00004884
4885 SourceLocation Loc = Constructor->getLocation();
4886 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4887
4888 Constructor->setUsed();
4889 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004890}
4891
Sebastian Redl08905022011-02-05 19:23:19 +00004892void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
4893 // We start with an initial pass over the base classes to collect those that
4894 // inherit constructors from. If there are none, we can forgo all further
4895 // processing.
4896 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
4897 BasesVector BasesToInheritFrom;
4898 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
4899 BaseE = ClassDecl->bases_end();
4900 BaseIt != BaseE; ++BaseIt) {
4901 if (BaseIt->getInheritConstructors()) {
4902 QualType Base = BaseIt->getType();
4903 if (Base->isDependentType()) {
4904 // If we inherit constructors from anything that is dependent, just
4905 // abort processing altogether. We'll get another chance for the
4906 // instantiations.
4907 return;
4908 }
4909 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
4910 }
4911 }
4912 if (BasesToInheritFrom.empty())
4913 return;
4914
4915 // Now collect the constructors that we already have in the current class.
4916 // Those take precedence over inherited constructors.
4917 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
4918 // unless there is a user-declared constructor with the same signature in
4919 // the class where the using-declaration appears.
4920 llvm::SmallSet<const Type *, 8> ExistingConstructors;
4921 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
4922 CtorE = ClassDecl->ctor_end();
4923 CtorIt != CtorE; ++CtorIt) {
4924 ExistingConstructors.insert(
4925 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
4926 }
4927
4928 Scope *S = getScopeForContext(ClassDecl);
4929 DeclarationName CreatedCtorName =
4930 Context.DeclarationNames.getCXXConstructorName(
4931 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
4932
4933 // Now comes the true work.
4934 // First, we keep a map from constructor types to the base that introduced
4935 // them. Needed for finding conflicting constructors. We also keep the
4936 // actually inserted declarations in there, for pretty diagnostics.
4937 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
4938 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
4939 ConstructorToSourceMap InheritedConstructors;
4940 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
4941 BaseE = BasesToInheritFrom.end();
4942 BaseIt != BaseE; ++BaseIt) {
4943 const RecordType *Base = *BaseIt;
4944 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
4945 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
4946 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
4947 CtorE = BaseDecl->ctor_end();
4948 CtorIt != CtorE; ++CtorIt) {
4949 // Find the using declaration for inheriting this base's constructors.
4950 DeclarationName Name =
4951 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
4952 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
4953 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
4954 SourceLocation UsingLoc = UD ? UD->getLocation() :
4955 ClassDecl->getLocation();
4956
4957 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
4958 // from the class X named in the using-declaration consists of actual
4959 // constructors and notional constructors that result from the
4960 // transformation of defaulted parameters as follows:
4961 // - all non-template default constructors of X, and
4962 // - for each non-template constructor of X that has at least one
4963 // parameter with a default argument, the set of constructors that
4964 // results from omitting any ellipsis parameter specification and
4965 // successively omitting parameters with a default argument from the
4966 // end of the parameter-type-list.
4967 CXXConstructorDecl *BaseCtor = *CtorIt;
4968 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
4969 const FunctionProtoType *BaseCtorType =
4970 BaseCtor->getType()->getAs<FunctionProtoType>();
4971
4972 for (unsigned params = BaseCtor->getMinRequiredArguments(),
4973 maxParams = BaseCtor->getNumParams();
4974 params <= maxParams; ++params) {
4975 // Skip default constructors. They're never inherited.
4976 if (params == 0)
4977 continue;
4978 // Skip copy and move constructors for the same reason.
4979 if (CanBeCopyOrMove && params == 1)
4980 continue;
4981
4982 // Build up a function type for this particular constructor.
4983 // FIXME: The working paper does not consider that the exception spec
4984 // for the inheriting constructor might be larger than that of the
4985 // source. This code doesn't yet, either.
4986 const Type *NewCtorType;
4987 if (params == maxParams)
4988 NewCtorType = BaseCtorType;
4989 else {
4990 llvm::SmallVector<QualType, 16> Args;
4991 for (unsigned i = 0; i < params; ++i) {
4992 Args.push_back(BaseCtorType->getArgType(i));
4993 }
4994 FunctionProtoType::ExtProtoInfo ExtInfo =
4995 BaseCtorType->getExtProtoInfo();
4996 ExtInfo.Variadic = false;
4997 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
4998 Args.data(), params, ExtInfo)
4999 .getTypePtr();
5000 }
5001 const Type *CanonicalNewCtorType =
5002 Context.getCanonicalType(NewCtorType);
5003
5004 // Now that we have the type, first check if the class already has a
5005 // constructor with this signature.
5006 if (ExistingConstructors.count(CanonicalNewCtorType))
5007 continue;
5008
5009 // Then we check if we have already declared an inherited constructor
5010 // with this signature.
5011 std::pair<ConstructorToSourceMap::iterator, bool> result =
5012 InheritedConstructors.insert(std::make_pair(
5013 CanonicalNewCtorType,
5014 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
5015 if (!result.second) {
5016 // Already in the map. If it came from a different class, that's an
5017 // error. Not if it's from the same.
5018 CanQualType PreviousBase = result.first->second.first;
5019 if (CanonicalBase != PreviousBase) {
5020 const CXXConstructorDecl *PrevCtor = result.first->second.second;
5021 const CXXConstructorDecl *PrevBaseCtor =
5022 PrevCtor->getInheritedConstructor();
5023 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
5024
5025 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
5026 Diag(BaseCtor->getLocation(),
5027 diag::note_using_decl_constructor_conflict_current_ctor);
5028 Diag(PrevBaseCtor->getLocation(),
5029 diag::note_using_decl_constructor_conflict_previous_ctor);
5030 Diag(PrevCtor->getLocation(),
5031 diag::note_using_decl_constructor_conflict_previous_using);
5032 }
5033 continue;
5034 }
5035
5036 // OK, we're there, now add the constructor.
5037 // C++0x [class.inhctor]p8: [...] that would be performed by a
5038 // user-writtern inline constructor [...]
5039 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
5040 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
Abramo Bagnaradff19302011-03-08 08:55:46 +00005041 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
5042 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
Sebastian Redl08905022011-02-05 19:23:19 +00005043 /*ImplicitlyDeclared=*/true);
5044 NewCtor->setAccess(BaseCtor->getAccess());
5045
5046 // Build up the parameter decls and add them.
5047 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
5048 for (unsigned i = 0; i < params; ++i) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00005049 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
5050 UsingLoc, UsingLoc,
Sebastian Redl08905022011-02-05 19:23:19 +00005051 /*IdentifierInfo=*/0,
5052 BaseCtorType->getArgType(i),
5053 /*TInfo=*/0, SC_None,
5054 SC_None, /*DefaultArg=*/0));
5055 }
5056 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
5057 NewCtor->setInheritedConstructor(BaseCtor);
5058
5059 PushOnScopeChains(NewCtor, S, false);
5060 ClassDecl->addDecl(NewCtor);
5061 result.first->second.second = NewCtor;
5062 }
5063 }
5064 }
5065}
5066
Douglas Gregor0be31a22010-07-02 17:43:08 +00005067CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00005068 // C++ [class.dtor]p2:
5069 // If a class has no user-declared destructor, a destructor is
5070 // declared implicitly. An implicitly-declared destructor is an
5071 // inline public member of its class.
5072
5073 // C++ [except.spec]p14:
5074 // An implicitly declared special member function (Clause 12) shall have
5075 // an exception-specification.
5076 ImplicitExceptionSpecification ExceptSpec(Context);
5077
5078 // Direct base-class destructors.
5079 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5080 BEnd = ClassDecl->bases_end();
5081 B != BEnd; ++B) {
5082 if (B->isVirtual()) // Handled below.
5083 continue;
5084
5085 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5086 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005087 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005088 }
5089
5090 // Virtual base-class destructors.
5091 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
5092 BEnd = ClassDecl->vbases_end();
5093 B != BEnd; ++B) {
5094 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
5095 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005096 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005097 }
5098
5099 // Field destructors.
5100 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
5101 FEnd = ClassDecl->field_end();
5102 F != FEnd; ++F) {
5103 if (const RecordType *RecordTy
5104 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
5105 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00005106 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00005107 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005108
Douglas Gregor7454c562010-07-02 20:37:36 +00005109 // Create the actual destructor declaration.
John McCalldb40c7f2010-12-14 08:05:40 +00005110 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005111 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00005112 EPI.NumExceptions = ExceptSpec.size();
5113 EPI.Exceptions = ExceptSpec.data();
5114 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005115
Douglas Gregorf1203042010-07-01 19:09:28 +00005116 CanQualType ClassType
5117 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005118 SourceLocation ClassLoc = ClassDecl->getLocation();
Douglas Gregorf1203042010-07-01 19:09:28 +00005119 DeclarationName Name
5120 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005121 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf1203042010-07-01 19:09:28 +00005122 CXXDestructorDecl *Destructor
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005123 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
5124 /*isInline=*/true,
5125 /*isImplicitlyDeclared=*/true);
Douglas Gregorf1203042010-07-01 19:09:28 +00005126 Destructor->setAccess(AS_public);
5127 Destructor->setImplicit();
5128 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00005129
5130 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00005131 ++ASTContext::NumImplicitDestructorsDeclared;
5132
5133 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00005134 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00005135 PushOnScopeChains(Destructor, S, false);
5136 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00005137
5138 // This could be uniqued if it ever proves significant.
5139 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
5140
5141 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00005142
Douglas Gregorf1203042010-07-01 19:09:28 +00005143 return Destructor;
5144}
5145
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005146void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00005147 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00005148 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005149 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00005150 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005151 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005152
Douglas Gregor54818f02010-05-12 16:39:35 +00005153 if (Destructor->isInvalidDecl())
5154 return;
5155
Douglas Gregora57478e2010-05-01 15:04:51 +00005156 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005157
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005158 DiagnosticErrorTrap Trap(Diags);
John McCalla6309952010-03-16 21:39:52 +00005159 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
5160 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00005161
Douglas Gregor54818f02010-05-12 16:39:35 +00005162 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00005163 Diag(CurrentLocation, diag::note_member_synthesized_at)
5164 << CXXDestructor << Context.getTagDeclType(ClassDecl);
5165
5166 Destructor->setInvalidDecl();
5167 return;
5168 }
5169
Douglas Gregor73193272010-09-20 16:48:21 +00005170 SourceLocation Loc = Destructor->getLocation();
5171 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
5172
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005173 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00005174 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005175}
5176
Douglas Gregorb139cd52010-05-01 20:49:11 +00005177/// \brief Builds a statement that copies the given entity from \p From to
5178/// \c To.
5179///
5180/// This routine is used to copy the members of a class with an
5181/// implicitly-declared copy assignment operator. When the entities being
5182/// copied are arrays, this routine builds for loops to copy them.
5183///
5184/// \param S The Sema object used for type-checking.
5185///
5186/// \param Loc The location where the implicit copy is being generated.
5187///
5188/// \param T The type of the expressions being copied. Both expressions must
5189/// have this type.
5190///
5191/// \param To The expression we are copying to.
5192///
5193/// \param From The expression we are copying from.
5194///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005195/// \param CopyingBaseSubobject Whether we're copying a base subobject.
5196/// Otherwise, it's a non-static member subobject.
5197///
Douglas Gregorb139cd52010-05-01 20:49:11 +00005198/// \param Depth Internal parameter recording the depth of the recursion.
5199///
5200/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00005201static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00005202BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00005203 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005204 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005205 // C++0x [class.copy]p30:
5206 // Each subobject is assigned in the manner appropriate to its type:
5207 //
5208 // - if the subobject is of class type, the copy assignment operator
5209 // for the class is used (as if by explicit qualification; that is,
5210 // ignoring any possible virtual overriding functions in more derived
5211 // classes);
5212 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
5213 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
5214
5215 // Look for operator=.
5216 DeclarationName Name
5217 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5218 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
5219 S.LookupQualifiedName(OpLookup, ClassDecl, false);
5220
5221 // Filter out any result that isn't a copy-assignment operator.
5222 LookupResult::Filter F = OpLookup.makeFilter();
5223 while (F.hasNext()) {
5224 NamedDecl *D = F.next();
5225 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
5226 if (Method->isCopyAssignmentOperator())
5227 continue;
5228
5229 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00005230 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005231 F.done();
5232
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005233 // Suppress the protected check (C++ [class.protected]) for each of the
5234 // assignment operators we found. This strange dance is required when
5235 // we're assigning via a base classes's copy-assignment operator. To
5236 // ensure that we're getting the right base class subobject (without
5237 // ambiguities), we need to cast "this" to that subobject type; to
5238 // ensure that we don't go through the virtual call mechanism, we need
5239 // to qualify the operator= name with the base class (see below). However,
5240 // this means that if the base class has a protected copy assignment
5241 // operator, the protected member access check will fail. So, we
5242 // rewrite "protected" access to "public" access in this case, since we
5243 // know by construction that we're calling from a derived class.
5244 if (CopyingBaseSubobject) {
5245 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
5246 L != LEnd; ++L) {
5247 if (L.getAccess() == AS_protected)
5248 L.setAccess(AS_public);
5249 }
5250 }
5251
Douglas Gregorb139cd52010-05-01 20:49:11 +00005252 // Create the nested-name-specifier that will be used to qualify the
5253 // reference to operator=; this is required to suppress the virtual
5254 // call mechanism.
5255 CXXScopeSpec SS;
Douglas Gregor869ad452011-02-24 17:54:50 +00005256 SS.MakeTrivial(S.Context,
5257 NestedNameSpecifier::Create(S.Context, 0, false,
5258 T.getTypePtr()),
5259 Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005260
5261 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00005262 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00005263 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005264 /*FirstQualifierInScope=*/0, OpLookup,
5265 /*TemplateArgs=*/0,
5266 /*SuppressQualifierCheck=*/true);
5267 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005268 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005269
5270 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00005271
John McCalldadc5752010-08-24 06:29:42 +00005272 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00005273 OpEqualRef.takeAs<Expr>(),
5274 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005275 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005276 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005277
5278 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005279 }
John McCallab8c2732010-03-16 06:11:48 +00005280
Douglas Gregorb139cd52010-05-01 20:49:11 +00005281 // - if the subobject is of scalar type, the built-in assignment
5282 // operator is used.
5283 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
5284 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00005285 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005286 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005287 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005288
5289 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005290 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005291
5292 // - if the subobject is an array, each element is assigned, in the
5293 // manner appropriate to the element type;
5294
5295 // Construct a loop over the array bounds, e.g.,
5296 //
5297 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5298 //
5299 // that will copy each of the array elements.
5300 QualType SizeType = S.Context.getSizeType();
5301
5302 // Create the iteration variable.
5303 IdentifierInfo *IterationVarName = 0;
5304 {
5305 llvm::SmallString<8> Str;
5306 llvm::raw_svector_ostream OS(Str);
5307 OS << "__i" << Depth;
5308 IterationVarName = &S.Context.Idents.get(OS.str());
5309 }
Abramo Bagnaradff19302011-03-08 08:55:46 +00005310 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005311 IterationVarName, SizeType,
5312 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00005313 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005314
5315 // Initialize the iteration variable to zero.
5316 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005317 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005318
5319 // Create a reference to the iteration variable; we'll use this several
5320 // times throughout.
5321 Expr *IterationVarRef
John McCall7decc9e2010-11-18 06:31:45 +00005322 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005323 assert(IterationVarRef && "Reference to invented variable cannot fail!");
5324
5325 // Create the DeclStmt that holds the iteration variable.
5326 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
5327
5328 // Create the comparison against the array bound.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005329 llvm::APInt Upper
5330 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00005331 Expr *Comparison
John McCallc3007a22010-10-26 07:05:15 +00005332 = new (S.Context) BinaryOperator(IterationVarRef,
John McCall7decc9e2010-11-18 06:31:45 +00005333 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
5334 BO_NE, S.Context.BoolTy,
5335 VK_RValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005336
5337 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005338 Expr *Increment
John McCall7decc9e2010-11-18 06:31:45 +00005339 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
5340 VK_LValue, OK_Ordinary, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005341
5342 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00005343 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
5344 IterationVarRef, Loc));
5345 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
5346 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00005347
5348 // Build the copy for an individual element of the array.
John McCall7decc9e2010-11-18 06:31:45 +00005349 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
5350 To, From, CopyingBaseSubobject,
5351 Depth + 1);
Douglas Gregorb412e172010-07-25 18:17:45 +00005352 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00005353 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005354
5355 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00005356 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00005357 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00005358 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00005359 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005360}
5361
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005362/// \brief Determine whether the given class has a copy assignment operator
5363/// that accepts a const-qualified argument.
5364static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
5365 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
5366
5367 if (!Class->hasDeclaredCopyAssignment())
5368 S.DeclareImplicitCopyAssignment(Class);
5369
5370 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
5371 DeclarationName OpName
5372 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
5373
5374 DeclContext::lookup_const_iterator Op, OpEnd;
5375 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
5376 // C++ [class.copy]p9:
5377 // A user-declared copy assignment operator is a non-static non-template
5378 // member function of class X with exactly one parameter of type X, X&,
5379 // const X&, volatile X& or const volatile X&.
5380 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
5381 if (!Method)
5382 continue;
5383
5384 if (Method->isStatic())
5385 continue;
5386 if (Method->getPrimaryTemplate())
5387 continue;
5388 const FunctionProtoType *FnType =
5389 Method->getType()->getAs<FunctionProtoType>();
5390 assert(FnType && "Overloaded operator has no prototype.");
5391 // Don't assert on this; an invalid decl might have been left in the AST.
5392 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
5393 continue;
5394 bool AcceptsConst = true;
5395 QualType ArgType = FnType->getArgType(0);
5396 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
5397 ArgType = Ref->getPointeeType();
5398 // Is it a non-const lvalue reference?
5399 if (!ArgType.isConstQualified())
5400 AcceptsConst = false;
5401 }
5402 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
5403 continue;
5404
5405 // We have a single argument of type cv X or cv X&, i.e. we've found the
5406 // copy assignment operator. Return whether it accepts const arguments.
5407 return AcceptsConst;
5408 }
5409 assert(Class->isInvalidDecl() &&
5410 "No copy assignment operator declared in valid code.");
5411 return false;
5412}
5413
Douglas Gregor0be31a22010-07-02 17:43:08 +00005414CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005415 // Note: The following rules are largely analoguous to the copy
5416 // constructor rules. Note that virtual bases are not taken into account
5417 // for determining the argument type of the operator. Note also that
5418 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00005419
5420
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005421 // C++ [class.copy]p10:
5422 // If the class definition does not explicitly declare a copy
5423 // assignment operator, one is declared implicitly.
5424 // The implicitly-defined copy assignment operator for a class X
5425 // will have the form
5426 //
5427 // X& X::operator=(const X&)
5428 //
5429 // if
5430 bool HasConstCopyAssignment = true;
5431
5432 // -- each direct base class B of X has a copy assignment operator
5433 // whose parameter is of type const B&, const volatile B& or B,
5434 // and
5435 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5436 BaseEnd = ClassDecl->bases_end();
5437 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
5438 assert(!Base->getType()->isDependentType() &&
5439 "Cannot generate implicit members for class with dependent bases.");
5440 const CXXRecordDecl *BaseClassDecl
5441 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005442 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005443 }
5444
5445 // -- for all the nonstatic data members of X that are of a class
5446 // type M (or array thereof), each such class type has a copy
5447 // assignment operator whose parameter is of type const M&,
5448 // const volatile M& or M.
5449 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5450 FieldEnd = ClassDecl->field_end();
5451 HasConstCopyAssignment && Field != FieldEnd;
5452 ++Field) {
5453 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5454 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
5455 const CXXRecordDecl *FieldClassDecl
5456 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005457 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005458 }
5459 }
5460
5461 // Otherwise, the implicitly declared copy assignment operator will
5462 // have the form
5463 //
5464 // X& X::operator=(X&)
5465 QualType ArgType = Context.getTypeDeclType(ClassDecl);
5466 QualType RetType = Context.getLValueReferenceType(ArgType);
5467 if (HasConstCopyAssignment)
5468 ArgType = ArgType.withConst();
5469 ArgType = Context.getLValueReferenceType(ArgType);
5470
Douglas Gregor68e11362010-07-01 17:48:08 +00005471 // C++ [except.spec]p14:
5472 // An implicitly declared special member function (Clause 12) shall have an
5473 // exception-specification. [...]
5474 ImplicitExceptionSpecification ExceptSpec(Context);
5475 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5476 BaseEnd = ClassDecl->bases_end();
5477 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005478 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005479 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005480
5481 if (!BaseClassDecl->hasDeclaredCopyAssignment())
5482 DeclareImplicitCopyAssignment(BaseClassDecl);
5483
Douglas Gregor68e11362010-07-01 17:48:08 +00005484 if (CXXMethodDecl *CopyAssign
5485 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5486 ExceptSpec.CalledDecl(CopyAssign);
5487 }
5488 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5489 FieldEnd = ClassDecl->field_end();
5490 Field != FieldEnd;
5491 ++Field) {
5492 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5493 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005494 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00005495 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005496
5497 if (!FieldClassDecl->hasDeclaredCopyAssignment())
5498 DeclareImplicitCopyAssignment(FieldClassDecl);
5499
Douglas Gregor68e11362010-07-01 17:48:08 +00005500 if (CXXMethodDecl *CopyAssign
5501 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
5502 ExceptSpec.CalledDecl(CopyAssign);
5503 }
5504 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005505
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005506 // An implicitly-declared copy assignment operator is an inline public
5507 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005508 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005509 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00005510 EPI.NumExceptions = ExceptSpec.size();
5511 EPI.Exceptions = ExceptSpec.data();
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005512 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnaradff19302011-03-08 08:55:46 +00005513 SourceLocation ClassLoc = ClassDecl->getLocation();
5514 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005515 CXXMethodDecl *CopyAssignment
Abramo Bagnaradff19302011-03-08 08:55:46 +00005516 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
John McCalldb40c7f2010-12-14 08:05:40 +00005517 Context.getFunctionType(RetType, &ArgType, 1, EPI),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005518 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00005519 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf2f08062011-03-08 17:10:18 +00005520 /*isInline=*/true,
5521 SourceLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005522 CopyAssignment->setAccess(AS_public);
5523 CopyAssignment->setImplicit();
5524 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005525
5526 // Add the parameter to the operator.
5527 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005528 ClassLoc, ClassLoc, /*Id=*/0,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005529 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005530 SC_None,
5531 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005532 CopyAssignment->setParams(&FromParam, 1);
5533
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005534 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005535 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
5536
Douglas Gregor0be31a22010-07-02 17:43:08 +00005537 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00005538 PushOnScopeChains(CopyAssignment, S, false);
5539 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00005540
5541 AddOverriddenMethods(ClassDecl, CopyAssignment);
5542 return CopyAssignment;
5543}
5544
Douglas Gregorb139cd52010-05-01 20:49:11 +00005545void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
5546 CXXMethodDecl *CopyAssignOperator) {
5547 assert((CopyAssignOperator->isImplicit() &&
5548 CopyAssignOperator->isOverloadedOperator() &&
5549 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005550 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00005551 "DefineImplicitCopyAssignment called for wrong function");
5552
5553 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
5554
5555 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
5556 CopyAssignOperator->setInvalidDecl();
5557 return;
5558 }
5559
5560 CopyAssignOperator->setUsed();
5561
5562 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00005563 DiagnosticErrorTrap Trap(Diags);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005564
5565 // C++0x [class.copy]p30:
5566 // The implicitly-defined or explicitly-defaulted copy assignment operator
5567 // for a non-union class X performs memberwise copy assignment of its
5568 // subobjects. The direct base classes of X are assigned first, in the
5569 // order of their declaration in the base-specifier-list, and then the
5570 // immediate non-static data members of X are assigned, in the order in
5571 // which they were declared in the class definition.
5572
5573 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00005574 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005575
5576 // The parameter for the "other" object, which we are copying from.
5577 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
5578 Qualifiers OtherQuals = Other->getType().getQualifiers();
5579 QualType OtherRefType = Other->getType();
5580 if (const LValueReferenceType *OtherRef
5581 = OtherRefType->getAs<LValueReferenceType>()) {
5582 OtherRefType = OtherRef->getPointeeType();
5583 OtherQuals = OtherRefType.getQualifiers();
5584 }
5585
5586 // Our location for everything implicitly-generated.
5587 SourceLocation Loc = CopyAssignOperator->getLocation();
5588
5589 // Construct a reference to the "other" object. We'll be using this
5590 // throughout the generated ASTs.
John McCall4bc41ae2010-11-18 19:01:18 +00005591 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005592 assert(OtherRef && "Reference to parameter cannot fail!");
5593
5594 // Construct the "this" pointer. We'll be using this throughout the generated
5595 // ASTs.
5596 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
5597 assert(This && "Reference to this cannot fail!");
5598
5599 // Assign base classes.
5600 bool Invalid = false;
5601 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5602 E = ClassDecl->bases_end(); Base != E; ++Base) {
5603 // Form the assignment:
5604 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5605 QualType BaseType = Base->getType().getUnqualifiedType();
Jeffrey Yasskin8dfa5f12011-01-18 02:00:16 +00005606 if (!BaseType->isRecordType()) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005607 Invalid = true;
5608 continue;
5609 }
5610
John McCallcf142162010-08-07 06:22:56 +00005611 CXXCastPath BasePath;
5612 BasePath.push_back(Base);
5613
Douglas Gregorb139cd52010-05-01 20:49:11 +00005614 // Construct the "from" expression, which is an implicit cast to the
5615 // appropriately-qualified base type.
John McCallc3007a22010-10-26 07:05:15 +00005616 Expr *From = OtherRef;
John Wiegley01296292011-04-08 18:41:53 +00005617 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
5618 CK_UncheckedDerivedToBase,
5619 VK_LValue, &BasePath).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005620
5621 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00005622 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005623
5624 // Implicitly cast "this" to the appropriately-qualified base type.
John Wiegley01296292011-04-08 18:41:53 +00005625 To = ImpCastExprToType(To.take(),
5626 Context.getCVRQualifiedType(BaseType,
5627 CopyAssignOperator->getTypeQualifiers()),
5628 CK_UncheckedDerivedToBase,
5629 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005630
5631 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00005632 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00005633 To.get(), From,
5634 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005635 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005636 Diag(CurrentLocation, diag::note_member_synthesized_at)
5637 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5638 CopyAssignOperator->setInvalidDecl();
5639 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005640 }
5641
5642 // Success! Record the copy.
5643 Statements.push_back(Copy.takeAs<Expr>());
5644 }
5645
5646 // \brief Reference to the __builtin_memcpy function.
5647 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005648 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005649 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005650
5651 // Assign non-static members.
5652 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5653 FieldEnd = ClassDecl->field_end();
5654 Field != FieldEnd; ++Field) {
5655 // Check for members of reference type; we can't copy those.
5656 if (Field->getType()->isReferenceType()) {
5657 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5658 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
5659 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005660 Diag(CurrentLocation, diag::note_member_synthesized_at)
5661 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005662 Invalid = true;
5663 continue;
5664 }
5665
5666 // Check for members of const-qualified, non-class type.
5667 QualType BaseType = Context.getBaseElementType(Field->getType());
5668 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
5669 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
5670 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
5671 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005672 Diag(CurrentLocation, diag::note_member_synthesized_at)
5673 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005674 Invalid = true;
5675 continue;
5676 }
5677
5678 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00005679 if (FieldType->isIncompleteArrayType()) {
5680 assert(ClassDecl->hasFlexibleArrayMember() &&
5681 "Incomplete array type is not valid");
5682 continue;
5683 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005684
5685 // Build references to the field in the object we're copying from and to.
5686 CXXScopeSpec SS; // Intentionally empty
5687 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
5688 LookupMemberName);
5689 MemberLookup.addDecl(*Field);
5690 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00005691 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
John McCall4bc41ae2010-11-18 19:01:18 +00005692 Loc, /*IsArrow=*/false,
5693 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00005694 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
John McCall4bc41ae2010-11-18 19:01:18 +00005695 Loc, /*IsArrow=*/true,
5696 SS, 0, MemberLookup, 0);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005697 assert(!From.isInvalid() && "Implicit field reference cannot fail");
5698 assert(!To.isInvalid() && "Implicit field reference cannot fail");
5699
5700 // If the field should be copied with __builtin_memcpy rather than via
5701 // explicit assignments, do so. This optimization only applies for arrays
5702 // of scalars and arrays of class type with trivial copy-assignment
5703 // operators.
5704 if (FieldType->isArrayType() &&
5705 (!BaseType->isRecordType() ||
5706 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
5707 ->hasTrivialCopyAssignment())) {
5708 // Compute the size of the memory buffer to be copied.
5709 QualType SizeType = Context.getSizeType();
5710 llvm::APInt Size(Context.getTypeSize(SizeType),
5711 Context.getTypeSizeInChars(BaseType).getQuantity());
5712 for (const ConstantArrayType *Array
5713 = Context.getAsConstantArrayType(FieldType);
5714 Array;
5715 Array = Context.getAsConstantArrayType(Array->getElementType())) {
Jay Foad6d4db0c2010-12-07 08:25:34 +00005716 llvm::APInt ArraySize
5717 = Array->getSize().zextOrTrunc(Size.getBitWidth());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005718 Size *= ArraySize;
5719 }
5720
5721 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00005722 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
5723 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005724
5725 bool NeedsCollectableMemCpy =
5726 (BaseType->isRecordType() &&
5727 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
5728
5729 if (NeedsCollectableMemCpy) {
5730 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00005731 // Create a reference to the __builtin_objc_memmove_collectable function.
5732 LookupResult R(*this,
5733 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005734 Loc, LookupOrdinaryName);
5735 LookupName(R, TUScope, true);
5736
5737 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
5738 if (!CollectableMemCpy) {
5739 // Something went horribly wrong earlier, and we will have
5740 // complained about it.
5741 Invalid = true;
5742 continue;
5743 }
5744
5745 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5746 CollectableMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005747 VK_LValue, Loc, 0).take();
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005748 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5749 }
5750 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005751 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005752 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005753 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5754 LookupOrdinaryName);
5755 LookupName(R, TUScope, true);
5756
5757 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5758 if (!BuiltinMemCpy) {
5759 // Something went horribly wrong earlier, and we will have complained
5760 // about it.
5761 Invalid = true;
5762 continue;
5763 }
5764
5765 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5766 BuiltinMemCpy->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005767 VK_LValue, Loc, 0).take();
Douglas Gregorb139cd52010-05-01 20:49:11 +00005768 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5769 }
5770
John McCall37ad5512010-08-23 06:44:23 +00005771 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005772 CallArgs.push_back(To.takeAs<Expr>());
5773 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005774 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005775 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005776 if (NeedsCollectableMemCpy)
5777 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005778 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005779 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005780 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005781 else
5782 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005783 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005784 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005785 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005786
Douglas Gregorb139cd52010-05-01 20:49:11 +00005787 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5788 Statements.push_back(Call.takeAs<Expr>());
5789 continue;
5790 }
5791
5792 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005793 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005794 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005795 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005796 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005797 Diag(CurrentLocation, diag::note_member_synthesized_at)
5798 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5799 CopyAssignOperator->setInvalidDecl();
5800 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005801 }
5802
5803 // Success! Record the copy.
5804 Statements.push_back(Copy.takeAs<Stmt>());
5805 }
5806
5807 if (!Invalid) {
5808 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005809 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005810
John McCalldadc5752010-08-24 06:29:42 +00005811 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005812 if (Return.isInvalid())
5813 Invalid = true;
5814 else {
5815 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005816
5817 if (Trap.hasErrorOccurred()) {
5818 Diag(CurrentLocation, diag::note_member_synthesized_at)
5819 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5820 Invalid = true;
5821 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005822 }
5823 }
5824
5825 if (Invalid) {
5826 CopyAssignOperator->setInvalidDecl();
5827 return;
5828 }
5829
John McCalldadc5752010-08-24 06:29:42 +00005830 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005831 /*isStmtExpr=*/false);
5832 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5833 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005834}
5835
Douglas Gregor0be31a22010-07-02 17:43:08 +00005836CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5837 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005838 // C++ [class.copy]p4:
5839 // If the class definition does not explicitly declare a copy
5840 // constructor, one is declared implicitly.
5841
Douglas Gregor54be3392010-07-01 17:57:27 +00005842 // C++ [class.copy]p5:
5843 // The implicitly-declared copy constructor for a class X will
5844 // have the form
5845 //
5846 // X::X(const X&)
5847 //
5848 // if
5849 bool HasConstCopyConstructor = true;
5850
5851 // -- each direct or virtual base class B of X has a copy
5852 // constructor whose first parameter is of type const B& or
5853 // const volatile B&, and
5854 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5855 BaseEnd = ClassDecl->bases_end();
5856 HasConstCopyConstructor && Base != BaseEnd;
5857 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005858 // Virtual bases are handled below.
5859 if (Base->isVirtual())
5860 continue;
5861
Douglas Gregora6d69502010-07-02 23:41:54 +00005862 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005863 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005864 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5865 DeclareImplicitCopyConstructor(BaseClassDecl);
5866
Douglas Gregorcfe68222010-07-01 18:27:03 +00005867 HasConstCopyConstructor
5868 = BaseClassDecl->hasConstCopyConstructor(Context);
5869 }
5870
5871 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5872 BaseEnd = ClassDecl->vbases_end();
5873 HasConstCopyConstructor && Base != BaseEnd;
5874 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005875 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005876 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005877 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5878 DeclareImplicitCopyConstructor(BaseClassDecl);
5879
Douglas Gregor54be3392010-07-01 17:57:27 +00005880 HasConstCopyConstructor
5881 = BaseClassDecl->hasConstCopyConstructor(Context);
5882 }
5883
5884 // -- for all the nonstatic data members of X that are of a
5885 // class type M (or array thereof), each such class type
5886 // has a copy constructor whose first parameter is of type
5887 // const M& or const volatile M&.
5888 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5889 FieldEnd = ClassDecl->field_end();
5890 HasConstCopyConstructor && Field != FieldEnd;
5891 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005892 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005893 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005894 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005895 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005896 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5897 DeclareImplicitCopyConstructor(FieldClassDecl);
5898
Douglas Gregor54be3392010-07-01 17:57:27 +00005899 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005900 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005901 }
5902 }
5903
5904 // Otherwise, the implicitly declared copy constructor will have
5905 // the form
5906 //
5907 // X::X(X&)
5908 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5909 QualType ArgType = ClassType;
5910 if (HasConstCopyConstructor)
5911 ArgType = ArgType.withConst();
5912 ArgType = Context.getLValueReferenceType(ArgType);
5913
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005914 // C++ [except.spec]p14:
5915 // An implicitly declared special member function (Clause 12) shall have an
5916 // exception-specification. [...]
5917 ImplicitExceptionSpecification ExceptSpec(Context);
5918 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5919 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5920 BaseEnd = ClassDecl->bases_end();
5921 Base != BaseEnd;
5922 ++Base) {
5923 // Virtual bases are handled below.
5924 if (Base->isVirtual())
5925 continue;
5926
Douglas Gregora6d69502010-07-02 23:41:54 +00005927 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005928 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005929 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5930 DeclareImplicitCopyConstructor(BaseClassDecl);
5931
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005932 if (CXXConstructorDecl *CopyConstructor
5933 = BaseClassDecl->getCopyConstructor(Context, Quals))
5934 ExceptSpec.CalledDecl(CopyConstructor);
5935 }
5936 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5937 BaseEnd = ClassDecl->vbases_end();
5938 Base != BaseEnd;
5939 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005940 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005941 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005942 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5943 DeclareImplicitCopyConstructor(BaseClassDecl);
5944
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005945 if (CXXConstructorDecl *CopyConstructor
5946 = BaseClassDecl->getCopyConstructor(Context, Quals))
5947 ExceptSpec.CalledDecl(CopyConstructor);
5948 }
5949 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5950 FieldEnd = ClassDecl->field_end();
5951 Field != FieldEnd;
5952 ++Field) {
5953 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5954 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005955 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005956 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005957 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5958 DeclareImplicitCopyConstructor(FieldClassDecl);
5959
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005960 if (CXXConstructorDecl *CopyConstructor
5961 = FieldClassDecl->getCopyConstructor(Context, Quals))
5962 ExceptSpec.CalledDecl(CopyConstructor);
5963 }
5964 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005965
Douglas Gregor54be3392010-07-01 17:57:27 +00005966 // An implicitly-declared copy constructor is an inline public
5967 // member of its class.
John McCalldb40c7f2010-12-14 08:05:40 +00005968 FunctionProtoType::ExtProtoInfo EPI;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00005969 EPI.ExceptionSpecType = ExceptSpec.getExceptionSpecType();
John McCalldb40c7f2010-12-14 08:05:40 +00005970 EPI.NumExceptions = ExceptSpec.size();
5971 EPI.Exceptions = ExceptSpec.data();
Douglas Gregor54be3392010-07-01 17:57:27 +00005972 DeclarationName Name
5973 = Context.DeclarationNames.getCXXConstructorName(
5974 Context.getCanonicalType(ClassType));
Abramo Bagnaradff19302011-03-08 08:55:46 +00005975 SourceLocation ClassLoc = ClassDecl->getLocation();
5976 DeclarationNameInfo NameInfo(Name, ClassLoc);
Douglas Gregor54be3392010-07-01 17:57:27 +00005977 CXXConstructorDecl *CopyConstructor
Abramo Bagnaradff19302011-03-08 08:55:46 +00005978 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005979 Context.getFunctionType(Context.VoidTy,
John McCalldb40c7f2010-12-14 08:05:40 +00005980 &ArgType, 1, EPI),
Douglas Gregor54be3392010-07-01 17:57:27 +00005981 /*TInfo=*/0,
5982 /*isExplicit=*/false,
5983 /*isInline=*/true,
5984 /*isImplicitlyDeclared=*/true);
5985 CopyConstructor->setAccess(AS_public);
Douglas Gregor54be3392010-07-01 17:57:27 +00005986 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5987
Douglas Gregora6d69502010-07-02 23:41:54 +00005988 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005989 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5990
Douglas Gregor54be3392010-07-01 17:57:27 +00005991 // Add the parameter to the constructor.
5992 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
Abramo Bagnaradff19302011-03-08 08:55:46 +00005993 ClassLoc, ClassLoc,
Douglas Gregor54be3392010-07-01 17:57:27 +00005994 /*IdentifierInfo=*/0,
5995 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005996 SC_None,
5997 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005998 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005999 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00006000 PushOnScopeChains(CopyConstructor, S, false);
6001 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00006002
6003 return CopyConstructor;
6004}
6005
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006006void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6007 CXXConstructorDecl *CopyConstructor,
6008 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00006009 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00006010 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00006011 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006012 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00006013
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00006014 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006015 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006016
Douglas Gregora57478e2010-05-01 15:04:51 +00006017 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Argyrios Kyrtzidis18653422010-11-19 00:19:12 +00006018 DiagnosticErrorTrap Trap(Diags);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006019
Alexis Hunt1d792652011-01-08 20:30:50 +00006020 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
Douglas Gregor54818f02010-05-12 16:39:35 +00006021 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00006022 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00006023 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00006024 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00006025 } else {
6026 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
6027 CopyConstructor->getLocation(),
6028 MultiStmtArg(*this, 0, 0),
6029 /*isStmtExpr=*/false)
6030 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00006031 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00006032
6033 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006034}
6035
John McCalldadc5752010-08-24 06:29:42 +00006036ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00006037Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00006038 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006039 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006040 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006041 unsigned ConstructKind,
6042 SourceRange ParenRange) {
Anders Carlsson250aada2009-08-16 05:13:48 +00006043 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00006044
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006045 // C++0x [class.copy]p34:
6046 // When certain criteria are met, an implementation is allowed to
6047 // omit the copy/move construction of a class object, even if the
6048 // copy/move constructor and/or destructor for the object have
6049 // side effects. [...]
6050 // - when a temporary class object that has not been bound to a
6051 // reference (12.2) would be copied/moved to a class object
6052 // with the same cv-unqualified type, the copy/move operation
6053 // can be omitted by constructing the temporary object
6054 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00006055 if (ConstructKind == CXXConstructExpr::CK_Complete &&
Douglas Gregor3fb22ba2011-01-27 23:24:55 +00006056 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00006057 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00006058 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00006059 }
Mike Stump11289f42009-09-09 15:08:12 +00006060
6061 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006062 Elidable, move(ExprArgs), RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006063 ConstructKind, ParenRange);
Anders Carlsson250aada2009-08-16 05:13:48 +00006064}
6065
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006066/// BuildCXXConstructExpr - Creates a complete call to a constructor,
6067/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00006068ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00006069Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
6070 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006071 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00006072 bool RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006073 unsigned ConstructKind,
6074 SourceRange ParenRange) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00006075 unsigned NumExprs = ExprArgs.size();
6076 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00006077
Nick Lewyckyd4693212011-03-25 01:44:32 +00006078 for (specific_attr_iterator<NonNullAttr>
6079 i = Constructor->specific_attr_begin<NonNullAttr>(),
6080 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
6081 const NonNullAttr *NonNull = *i;
6082 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
6083 }
6084
Douglas Gregor27381f32009-11-23 12:27:39 +00006085 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00006086 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00006087 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00006088 RequiresZeroInit,
Chandler Carruth01718152010-10-25 08:47:36 +00006089 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
6090 ParenRange));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006091}
6092
Mike Stump11289f42009-09-09 15:08:12 +00006093bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00006094 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00006095 MultiExprArg Exprs) {
Chandler Carruth01718152010-10-25 08:47:36 +00006096 // FIXME: Provide the correct paren SourceRange when available.
John McCalldadc5752010-08-24 06:29:42 +00006097 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00006098 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Chandler Carruth01718152010-10-25 08:47:36 +00006099 move(Exprs), false, CXXConstructExpr::CK_Complete,
6100 SourceRange());
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00006101 if (TempResult.isInvalid())
6102 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006103
Anders Carlsson6eb55572009-08-25 05:12:04 +00006104 Expr *Temp = TempResult.takeAs<Expr>();
John McCallacf0ee52010-10-08 02:01:28 +00006105 CheckImplicitConversions(Temp, VD->getLocation());
Douglas Gregor77b50e12009-06-22 23:06:13 +00006106 MarkDeclarationReferenced(VD->getLocation(), Constructor);
John McCall5d413782010-12-06 08:20:24 +00006107 Temp = MaybeCreateExprWithCleanups(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00006108 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00006109
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00006110 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00006111}
6112
John McCall03c48482010-02-02 09:10:11 +00006113void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
Chandler Carruth86d17d32011-03-27 21:26:48 +00006114 if (VD->isInvalidDecl()) return;
6115
John McCall03c48482010-02-02 09:10:11 +00006116 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Chandler Carruth86d17d32011-03-27 21:26:48 +00006117 if (ClassDecl->isInvalidDecl()) return;
6118 if (ClassDecl->hasTrivialDestructor()) return;
6119 if (ClassDecl->isDependentContext()) return;
John McCall47e40932010-08-01 20:20:59 +00006120
Chandler Carruth86d17d32011-03-27 21:26:48 +00006121 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6122 MarkDeclarationReferenced(VD->getLocation(), Destructor);
6123 CheckDestructorAccess(VD->getLocation(), Destructor,
6124 PDiag(diag::err_access_dtor_var)
6125 << VD->getDeclName()
6126 << VD->getType());
Anders Carlsson98766db2011-03-24 01:01:41 +00006127
Chandler Carruth86d17d32011-03-27 21:26:48 +00006128 if (!VD->hasGlobalStorage()) return;
6129
6130 // Emit warning for non-trivial dtor in global scope (a real global,
6131 // class-static, function-static).
6132 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
6133
6134 // TODO: this should be re-enabled for static locals by !CXAAtExit
6135 if (!VD->isStaticLocal())
6136 Diag(VD->getLocation(), diag::warn_global_destructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006137}
6138
Mike Stump11289f42009-09-09 15:08:12 +00006139/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006140/// ActOnDeclarator, when a C++ direct initializer is present.
6141/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00006142void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00006143 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006144 MultiExprArg Exprs,
Richard Smith30482bc2011-02-20 03:19:35 +00006145 SourceLocation RParenLoc,
6146 bool TypeMayContainAuto) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00006147 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006148
6149 // If there is no declaration, there was an error parsing it. Just ignore
6150 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00006151 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006152 return;
Mike Stump11289f42009-09-09 15:08:12 +00006153
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006154 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6155 if (!VDecl) {
6156 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
6157 RealDecl->setInvalidDecl();
6158 return;
6159 }
6160
Richard Smith30482bc2011-02-20 03:19:35 +00006161 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
6162 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
Richard Smith30482bc2011-02-20 03:19:35 +00006163 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
6164 if (Exprs.size() > 1) {
6165 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
6166 diag::err_auto_var_init_multiple_expressions)
6167 << VDecl->getDeclName() << VDecl->getType()
6168 << VDecl->getSourceRange();
6169 RealDecl->setInvalidDecl();
6170 return;
6171 }
6172
6173 Expr *Init = Exprs.get()[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00006174 TypeSourceInfo *DeducedType = 0;
6175 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
Richard Smith30482bc2011-02-20 03:19:35 +00006176 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
6177 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
6178 << Init->getSourceRange();
Richard Smith9647d3c2011-03-17 16:11:59 +00006179 if (!DeducedType) {
Richard Smith30482bc2011-02-20 03:19:35 +00006180 RealDecl->setInvalidDecl();
6181 return;
6182 }
Richard Smith9647d3c2011-03-17 16:11:59 +00006183 VDecl->setTypeSourceInfo(DeducedType);
6184 VDecl->setType(DeducedType->getType());
Richard Smith30482bc2011-02-20 03:19:35 +00006185
6186 // If this is a redeclaration, check that the type we just deduced matches
6187 // the previously declared type.
6188 if (VarDecl *Old = VDecl->getPreviousDeclaration())
6189 MergeVarDeclTypes(VDecl, Old);
6190 }
6191
Douglas Gregor402250f2009-08-26 21:14:46 +00006192 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006193 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006194 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
6195 //
6196 // Clients that want to distinguish between the two forms, can check for
6197 // direct initializer using VarDecl::hasCXXDirectInitializer().
6198 // A major benefit is that clients that don't particularly care about which
6199 // exactly form was it (like the CodeGen) can handle both cases without
6200 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006201
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006202 // C++ 8.5p11:
6203 // The form of initialization (using parentheses or '=') is generally
6204 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006205 // class type.
6206
Douglas Gregor50dc2192010-02-11 22:55:30 +00006207 if (!VDecl->getType()->isDependentType() &&
6208 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00006209 diag::err_typecheck_decl_incomplete_type)) {
6210 VDecl->setInvalidDecl();
6211 return;
6212 }
6213
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006214 // The variable can not have an abstract class type.
6215 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
6216 diag::err_abstract_type_in_decl,
6217 AbstractVariableType))
6218 VDecl->setInvalidDecl();
6219
Sebastian Redl5ca79842010-02-01 20:16:42 +00006220 const VarDecl *Def;
6221 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006222 Diag(VDecl->getLocation(), diag::err_redefinition)
6223 << VDecl->getDeclName();
6224 Diag(Def->getLocation(), diag::note_previous_definition);
6225 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00006226 return;
6227 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00006228
Douglas Gregorf0f83692010-08-24 05:27:49 +00006229 // C++ [class.static.data]p4
6230 // If a static data member is of const integral or const
6231 // enumeration type, its declaration in the class definition can
6232 // specify a constant-initializer which shall be an integral
6233 // constant expression (5.19). In that case, the member can appear
6234 // in integral constant expressions. The member shall still be
6235 // defined in a namespace scope if it is used in the program and the
6236 // namespace scope definition shall not contain an initializer.
6237 //
6238 // We already performed a redefinition check above, but for static
6239 // data members we also need to check whether there was an in-class
6240 // declaration with an initializer.
6241 const VarDecl* PrevInit = 0;
6242 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
6243 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
6244 Diag(PrevInit->getLocation(), diag::note_previous_definition);
6245 return;
6246 }
6247
Douglas Gregor71f39c92010-12-16 01:31:22 +00006248 bool IsDependent = false;
6249 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
6250 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
6251 VDecl->setInvalidDecl();
6252 return;
6253 }
6254
6255 if (Exprs.get()[I]->isTypeDependent())
6256 IsDependent = true;
6257 }
6258
Douglas Gregor50dc2192010-02-11 22:55:30 +00006259 // If either the declaration has a dependent type or if any of the
6260 // expressions is type-dependent, we represent the initialization
6261 // via a ParenListExpr for later use during template instantiation.
Douglas Gregor71f39c92010-12-16 01:31:22 +00006262 if (VDecl->getType()->isDependentType() || IsDependent) {
Douglas Gregor50dc2192010-02-11 22:55:30 +00006263 // Let clients know that initialization was done with a direct initializer.
6264 VDecl->setCXXDirectInitializer(true);
6265
6266 // Store the initialization expressions as a ParenListExpr.
6267 unsigned NumExprs = Exprs.size();
6268 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
6269 (Expr **)Exprs.release(),
6270 NumExprs, RParenLoc));
6271 return;
6272 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006273
6274 // Capture the variable that is being initialized and the style of
6275 // initialization.
6276 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
6277
6278 // FIXME: Poor source location information.
6279 InitializationKind Kind
6280 = InitializationKind::CreateDirect(VDecl->getLocation(),
6281 LParenLoc, RParenLoc);
6282
6283 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00006284 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00006285 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006286 if (Result.isInvalid()) {
6287 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006288 return;
6289 }
John McCallacf0ee52010-10-08 02:01:28 +00006290
6291 CheckImplicitConversions(Result.get(), LParenLoc);
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006292
Douglas Gregora40433a2010-12-07 00:41:46 +00006293 Result = MaybeCreateExprWithCleanups(Result);
Douglas Gregord5058122010-02-11 01:19:42 +00006294 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006295 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00006296
John McCall8b7fd8f12011-01-19 11:48:09 +00006297 CheckCompleteVariableDeclaration(VDecl);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00006298}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00006299
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006300/// \brief Given a constructor and the set of arguments provided for the
6301/// constructor, convert the arguments and add any required default arguments
6302/// to form a proper call to this constructor.
6303///
6304/// \returns true if an error occurred, false otherwise.
6305bool
6306Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
6307 MultiExprArg ArgsPtr,
6308 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00006309 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006310 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6311 unsigned NumArgs = ArgsPtr.size();
6312 Expr **Args = (Expr **)ArgsPtr.get();
6313
6314 const FunctionProtoType *Proto
6315 = Constructor->getType()->getAs<FunctionProtoType>();
6316 assert(Proto && "Constructor without a prototype?");
6317 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006318
6319 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006320 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006321 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006322 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00006323 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00006324
6325 VariadicCallType CallType =
6326 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
6327 llvm::SmallVector<Expr *, 8> AllArgs;
6328 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
6329 Proto, 0, Args, NumArgs, AllArgs,
6330 CallType);
6331 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
6332 ConvertedArgs.push_back(AllArgs[i]);
6333 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00006334}
6335
Anders Carlssone363c8e2009-12-12 00:32:00 +00006336static inline bool
6337CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
6338 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006339 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00006340 if (isa<NamespaceDecl>(DC)) {
6341 return SemaRef.Diag(FnDecl->getLocation(),
6342 diag::err_operator_new_delete_declared_in_namespace)
6343 << FnDecl->getDeclName();
6344 }
6345
6346 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00006347 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006348 return SemaRef.Diag(FnDecl->getLocation(),
6349 diag::err_operator_new_delete_declared_static)
6350 << FnDecl->getDeclName();
6351 }
6352
Anders Carlsson60659a82009-12-12 02:43:16 +00006353 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00006354}
6355
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006356static inline bool
6357CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
6358 CanQualType ExpectedResultType,
6359 CanQualType ExpectedFirstParamType,
6360 unsigned DependentParamTypeDiag,
6361 unsigned InvalidParamTypeDiag) {
6362 QualType ResultType =
6363 FnDecl->getType()->getAs<FunctionType>()->getResultType();
6364
6365 // Check that the result type is not dependent.
6366 if (ResultType->isDependentType())
6367 return SemaRef.Diag(FnDecl->getLocation(),
6368 diag::err_operator_new_delete_dependent_result_type)
6369 << FnDecl->getDeclName() << ExpectedResultType;
6370
6371 // Check that the result type is what we expect.
6372 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
6373 return SemaRef.Diag(FnDecl->getLocation(),
6374 diag::err_operator_new_delete_invalid_result_type)
6375 << FnDecl->getDeclName() << ExpectedResultType;
6376
6377 // A function template must have at least 2 parameters.
6378 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
6379 return SemaRef.Diag(FnDecl->getLocation(),
6380 diag::err_operator_new_delete_template_too_few_parameters)
6381 << FnDecl->getDeclName();
6382
6383 // The function decl must have at least 1 parameter.
6384 if (FnDecl->getNumParams() == 0)
6385 return SemaRef.Diag(FnDecl->getLocation(),
6386 diag::err_operator_new_delete_too_few_parameters)
6387 << FnDecl->getDeclName();
6388
6389 // Check the the first parameter type is not dependent.
6390 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
6391 if (FirstParamType->isDependentType())
6392 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
6393 << FnDecl->getDeclName() << ExpectedFirstParamType;
6394
6395 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00006396 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006397 ExpectedFirstParamType)
6398 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
6399 << FnDecl->getDeclName() << ExpectedFirstParamType;
6400
6401 return false;
6402}
6403
Anders Carlsson12308f42009-12-11 23:23:22 +00006404static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006405CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00006406 // C++ [basic.stc.dynamic.allocation]p1:
6407 // A program is ill-formed if an allocation function is declared in a
6408 // namespace scope other than global scope or declared static in global
6409 // scope.
6410 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6411 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006412
6413 CanQualType SizeTy =
6414 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
6415
6416 // C++ [basic.stc.dynamic.allocation]p1:
6417 // The return type shall be void*. The first parameter shall have type
6418 // std::size_t.
6419 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
6420 SizeTy,
6421 diag::err_operator_new_dependent_param_type,
6422 diag::err_operator_new_param_type))
6423 return true;
6424
6425 // C++ [basic.stc.dynamic.allocation]p1:
6426 // The first parameter shall not have an associated default argument.
6427 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00006428 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006429 diag::err_operator_new_default_arg)
6430 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
6431
6432 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00006433}
6434
6435static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00006436CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
6437 // C++ [basic.stc.dynamic.deallocation]p1:
6438 // A program is ill-formed if deallocation functions are declared in a
6439 // namespace scope other than global scope or declared static in global
6440 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00006441 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
6442 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006443
6444 // C++ [basic.stc.dynamic.deallocation]p2:
6445 // Each deallocation function shall return void and its first parameter
6446 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006447 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
6448 SemaRef.Context.VoidPtrTy,
6449 diag::err_operator_delete_dependent_param_type,
6450 diag::err_operator_delete_param_type))
6451 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00006452
Anders Carlsson12308f42009-12-11 23:23:22 +00006453 return false;
6454}
6455
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006456/// CheckOverloadedOperatorDeclaration - Check whether the declaration
6457/// of this overloaded operator is well-formed. If so, returns false;
6458/// otherwise, emits appropriate diagnostics and returns true.
6459bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00006460 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006461 "Expected an overloaded operator declaration");
6462
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006463 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
6464
Mike Stump11289f42009-09-09 15:08:12 +00006465 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006466 // The allocation and deallocation functions, operator new,
6467 // operator new[], operator delete and operator delete[], are
6468 // described completely in 3.7.3. The attributes and restrictions
6469 // found in the rest of this subclause do not apply to them unless
6470 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00006471 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00006472 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00006473
Anders Carlsson22f443f2009-12-12 00:26:23 +00006474 if (Op == OO_New || Op == OO_Array_New)
6475 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006476
6477 // C++ [over.oper]p6:
6478 // An operator function shall either be a non-static member
6479 // function or be a non-member function and have at least one
6480 // parameter whose type is a class, a reference to a class, an
6481 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00006482 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
6483 if (MethodDecl->isStatic())
6484 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006485 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006486 } else {
6487 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00006488 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
6489 ParamEnd = FnDecl->param_end();
6490 Param != ParamEnd; ++Param) {
6491 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00006492 if (ParamType->isDependentType() || ParamType->isRecordType() ||
6493 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006494 ClassOrEnumParam = true;
6495 break;
6496 }
6497 }
6498
Douglas Gregord69246b2008-11-17 16:14:12 +00006499 if (!ClassOrEnumParam)
6500 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006501 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006502 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006503 }
6504
6505 // C++ [over.oper]p8:
6506 // An operator function cannot have default arguments (8.3.6),
6507 // except where explicitly stated below.
6508 //
Mike Stump11289f42009-09-09 15:08:12 +00006509 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006510 // (C++ [over.call]p1).
6511 if (Op != OO_Call) {
6512 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
6513 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006514 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00006515 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00006516 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00006517 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006518 }
6519 }
6520
Douglas Gregor6cf08062008-11-10 13:38:07 +00006521 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
6522 { false, false, false }
6523#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6524 , { Unary, Binary, MemberOnly }
6525#include "clang/Basic/OperatorKinds.def"
6526 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006527
Douglas Gregor6cf08062008-11-10 13:38:07 +00006528 bool CanBeUnaryOperator = OperatorUses[Op][0];
6529 bool CanBeBinaryOperator = OperatorUses[Op][1];
6530 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006531
6532 // C++ [over.oper]p8:
6533 // [...] Operator functions cannot have more or fewer parameters
6534 // than the number required for the corresponding operator, as
6535 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00006536 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00006537 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006538 if (Op != OO_Call &&
6539 ((NumParams == 1 && !CanBeUnaryOperator) ||
6540 (NumParams == 2 && !CanBeBinaryOperator) ||
6541 (NumParams < 1) || (NumParams > 2))) {
6542 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006543 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00006544 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006545 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00006546 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006547 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006548 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00006549 assert(CanBeBinaryOperator &&
6550 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006551 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00006552 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006553
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00006554 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006555 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006556 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00006557
Douglas Gregord69246b2008-11-17 16:14:12 +00006558 // Overloaded operators other than operator() cannot be variadic.
6559 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00006560 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00006561 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006562 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006563 }
6564
6565 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00006566 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
6567 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00006568 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006569 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006570 }
6571
6572 // C++ [over.inc]p1:
6573 // The user-defined function called operator++ implements the
6574 // prefix and postfix ++ operator. If this function is a member
6575 // function with no parameters, or a non-member function with one
6576 // parameter of class or enumeration type, it defines the prefix
6577 // increment operator ++ for objects of that type. If the function
6578 // is a member function with one parameter (which shall be of type
6579 // int) or a non-member function with two parameters (the second
6580 // of which shall be of type int), it defines the postfix
6581 // increment operator ++ for objects of that type.
6582 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
6583 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
6584 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00006585 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006586 ParamIsInt = BT->getKind() == BuiltinType::Int;
6587
Chris Lattner2b786902008-11-21 07:50:02 +00006588 if (!ParamIsInt)
6589 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00006590 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006591 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006592 }
6593
Douglas Gregord69246b2008-11-17 16:14:12 +00006594 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00006595}
Chris Lattner3b024a32008-12-17 07:09:26 +00006596
Alexis Huntc88db062010-01-13 09:01:02 +00006597/// CheckLiteralOperatorDeclaration - Check whether the declaration
6598/// of this literal operator function is well-formed. If so, returns
6599/// false; otherwise, emits appropriate diagnostics and returns true.
6600bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
6601 DeclContext *DC = FnDecl->getDeclContext();
6602 Decl::Kind Kind = DC->getDeclKind();
6603 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
6604 Kind != Decl::LinkageSpec) {
6605 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
6606 << FnDecl->getDeclName();
6607 return true;
6608 }
6609
6610 bool Valid = false;
6611
Alexis Hunt7dd26172010-04-07 23:11:06 +00006612 // template <char...> type operator "" name() is the only valid template
6613 // signature, and the only valid signature with no parameters.
6614 if (FnDecl->param_size() == 0) {
6615 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
6616 // Must have only one template parameter
6617 TemplateParameterList *Params = TpDecl->getTemplateParameters();
6618 if (Params->size() == 1) {
6619 NonTypeTemplateParmDecl *PmDecl =
6620 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00006621
Alexis Hunt7dd26172010-04-07 23:11:06 +00006622 // The template parameter must be a char parameter pack.
Alexis Hunt7dd26172010-04-07 23:11:06 +00006623 if (PmDecl && PmDecl->isTemplateParameterPack() &&
6624 Context.hasSameType(PmDecl->getType(), Context.CharTy))
6625 Valid = true;
6626 }
6627 }
6628 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00006629 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00006630 FunctionDecl::param_iterator Param = FnDecl->param_begin();
6631
Alexis Huntc88db062010-01-13 09:01:02 +00006632 QualType T = (*Param)->getType();
6633
Alexis Hunt079a6f72010-04-07 22:57:35 +00006634 // unsigned long long int, long double, and any character type are allowed
6635 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00006636 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
6637 Context.hasSameType(T, Context.LongDoubleTy) ||
6638 Context.hasSameType(T, Context.CharTy) ||
6639 Context.hasSameType(T, Context.WCharTy) ||
6640 Context.hasSameType(T, Context.Char16Ty) ||
6641 Context.hasSameType(T, Context.Char32Ty)) {
6642 if (++Param == FnDecl->param_end())
6643 Valid = true;
6644 goto FinishedParams;
6645 }
6646
Alexis Hunt079a6f72010-04-07 22:57:35 +00006647 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00006648 const PointerType *PT = T->getAs<PointerType>();
6649 if (!PT)
6650 goto FinishedParams;
6651 T = PT->getPointeeType();
6652 if (!T.isConstQualified())
6653 goto FinishedParams;
6654 T = T.getUnqualifiedType();
6655
6656 // Move on to the second parameter;
6657 ++Param;
6658
6659 // If there is no second parameter, the first must be a const char *
6660 if (Param == FnDecl->param_end()) {
6661 if (Context.hasSameType(T, Context.CharTy))
6662 Valid = true;
6663 goto FinishedParams;
6664 }
6665
6666 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6667 // are allowed as the first parameter to a two-parameter function
6668 if (!(Context.hasSameType(T, Context.CharTy) ||
6669 Context.hasSameType(T, Context.WCharTy) ||
6670 Context.hasSameType(T, Context.Char16Ty) ||
6671 Context.hasSameType(T, Context.Char32Ty)))
6672 goto FinishedParams;
6673
6674 // The second and final parameter must be an std::size_t
6675 T = (*Param)->getType().getUnqualifiedType();
6676 if (Context.hasSameType(T, Context.getSizeType()) &&
6677 ++Param == FnDecl->param_end())
6678 Valid = true;
6679 }
6680
6681 // FIXME: This diagnostic is absolutely terrible.
6682FinishedParams:
6683 if (!Valid) {
6684 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
6685 << FnDecl->getDeclName();
6686 return true;
6687 }
6688
6689 return false;
6690}
6691
Douglas Gregor07665a62009-01-05 19:45:36 +00006692/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6693/// linkage specification, including the language and (if present)
6694/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6695/// the location of the language string literal, which is provided
6696/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6697/// the '{' brace. Otherwise, this linkage specification does not
6698/// have any braces.
Chris Lattner8ea64422010-11-09 20:15:55 +00006699Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
6700 SourceLocation LangLoc,
6701 llvm::StringRef Lang,
6702 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00006703 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006704 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006705 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00006706 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00006707 Language = LinkageSpecDecl::lang_cxx;
6708 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00006709 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00006710 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00006711 }
Mike Stump11289f42009-09-09 15:08:12 +00006712
Chris Lattner438e5012008-12-17 07:13:27 +00006713 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00006714
Douglas Gregor07665a62009-01-05 19:45:36 +00006715 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Abramo Bagnaraea947882011-03-08 16:41:52 +00006716 ExternLoc, LangLoc, Language);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006717 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00006718 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00006719 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00006720}
6721
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00006722/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00006723/// the C++ linkage specification LinkageSpec. If RBraceLoc is
6724/// valid, it's the position of the closing '}' brace in a linkage
6725/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00006726Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00006727 Decl *LinkageSpec,
6728 SourceLocation RBraceLoc) {
6729 if (LinkageSpec) {
6730 if (RBraceLoc.isValid()) {
6731 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
6732 LSDecl->setRBraceLoc(RBraceLoc);
6733 }
Douglas Gregor07665a62009-01-05 19:45:36 +00006734 PopDeclContext();
Abramo Bagnara4a8cda82011-03-03 14:52:38 +00006735 }
Douglas Gregor07665a62009-01-05 19:45:36 +00006736 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00006737}
6738
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006739/// \brief Perform semantic analysis for the variable declaration that
6740/// occurs within a C++ catch clause, returning the newly-created
6741/// variable.
Abramo Bagnaradff19302011-03-08 08:55:46 +00006742VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00006743 TypeSourceInfo *TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006744 SourceLocation StartLoc,
6745 SourceLocation Loc,
6746 IdentifierInfo *Name) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006747 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006748 QualType ExDeclType = TInfo->getType();
6749
Sebastian Redl54c04d42008-12-22 19:15:10 +00006750 // Arrays and functions decay.
6751 if (ExDeclType->isArrayType())
6752 ExDeclType = Context.getArrayDecayedType(ExDeclType);
6753 else if (ExDeclType->isFunctionType())
6754 ExDeclType = Context.getPointerType(ExDeclType);
6755
6756 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6757 // The exception-declaration shall not denote a pointer or reference to an
6758 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00006759 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00006760 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006761 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00006762 Invalid = true;
6763 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006764
Douglas Gregor104ee002010-03-08 01:47:36 +00006765 // GCC allows catching pointers and references to incomplete types
6766 // as an extension; so do we, but we warn by default.
6767
Sebastian Redl54c04d42008-12-22 19:15:10 +00006768 QualType BaseType = ExDeclType;
6769 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00006770 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00006771 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006772 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006773 BaseType = Ptr->getPointeeType();
6774 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00006775 DK = diag::ext_catch_incomplete_ptr;
6776 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00006777 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00006778 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006779 BaseType = Ref->getPointeeType();
6780 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00006781 DK = diag::ext_catch_incomplete_ref;
6782 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006783 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00006784 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00006785 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
6786 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00006787 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006788
Mike Stump11289f42009-09-09 15:08:12 +00006789 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006790 RequireNonAbstractType(Loc, ExDeclType,
6791 diag::err_abstract_type_in_decl,
6792 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00006793 Invalid = true;
6794
John McCall2ca705e2010-07-24 00:37:23 +00006795 // Only the non-fragile NeXT runtime currently supports C++ catches
6796 // of ObjC types, and no runtime supports catching ObjC types by value.
6797 if (!Invalid && getLangOptions().ObjC1) {
6798 QualType T = ExDeclType;
6799 if (const ReferenceType *RT = T->getAs<ReferenceType>())
6800 T = RT->getPointeeType();
6801
6802 if (T->isObjCObjectType()) {
6803 Diag(Loc, diag::err_objc_object_catch);
6804 Invalid = true;
6805 } else if (T->isObjCObjectPointerType()) {
David Chisnalle1d2584d2011-03-20 21:35:39 +00006806 if (!getLangOptions().ObjCNonFragileABI) {
John McCall2ca705e2010-07-24 00:37:23 +00006807 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6808 Invalid = true;
6809 }
6810 }
6811 }
6812
Abramo Bagnaradff19302011-03-08 08:55:46 +00006813 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
6814 ExDeclType, TInfo, SC_None, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006815 ExDecl->setExceptionVariable(true);
6816
Douglas Gregor6de584c2010-03-05 23:38:39 +00006817 if (!Invalid) {
John McCall1bf58462011-02-16 08:02:54 +00006818 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
Douglas Gregor6de584c2010-03-05 23:38:39 +00006819 // C++ [except.handle]p16:
6820 // The object declared in an exception-declaration or, if the
6821 // exception-declaration does not specify a name, a temporary (12.2) is
6822 // copy-initialized (8.5) from the exception object. [...]
6823 // The object is destroyed when the handler exits, after the destruction
6824 // of any automatic objects initialized within the handler.
6825 //
6826 // We just pretend to initialize the object with itself, then make sure
6827 // it can be destroyed later.
John McCall1bf58462011-02-16 08:02:54 +00006828 QualType initType = ExDeclType;
6829
6830 InitializedEntity entity =
6831 InitializedEntity::InitializeVariable(ExDecl);
6832 InitializationKind initKind =
6833 InitializationKind::CreateCopy(Loc, SourceLocation());
6834
6835 Expr *opaqueValue =
6836 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
6837 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
6838 ExprResult result = sequence.Perform(*this, entity, initKind,
6839 MultiExprArg(&opaqueValue, 1));
6840 if (result.isInvalid())
Douglas Gregor6de584c2010-03-05 23:38:39 +00006841 Invalid = true;
John McCall1bf58462011-02-16 08:02:54 +00006842 else {
6843 // If the constructor used was non-trivial, set this as the
6844 // "initializer".
6845 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
6846 if (!construct->getConstructor()->isTrivial()) {
6847 Expr *init = MaybeCreateExprWithCleanups(construct);
6848 ExDecl->setInit(init);
6849 }
6850
6851 // And make sure it's destructable.
6852 FinalizeVarWithDestructor(ExDecl, recordType);
6853 }
Douglas Gregor6de584c2010-03-05 23:38:39 +00006854 }
6855 }
6856
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006857 if (Invalid)
6858 ExDecl->setInvalidDecl();
6859
6860 return ExDecl;
6861}
6862
6863/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6864/// handler.
John McCall48871652010-08-21 09:40:31 +00006865Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006866 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
Douglas Gregor72772f62010-12-16 17:48:04 +00006867 bool Invalid = D.isInvalidType();
6868
6869 // Check for unexpanded parameter packs.
6870 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6871 UPPC_ExceptionType)) {
6872 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
6873 D.getIdentifierLoc());
6874 Invalid = true;
6875 }
6876
Sebastian Redl54c04d42008-12-22 19:15:10 +00006877 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006878 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006879 LookupOrdinaryName,
6880 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006881 // The scope should be freshly made just for us. There is just no way
6882 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006883 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006884 if (PrevDecl->isTemplateParameter()) {
6885 // Maybe we will complain about the shadowed template parameter.
6886 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006887 }
6888 }
6889
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006890 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006891 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6892 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006893 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006894 }
6895
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006896 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Abramo Bagnaradff19302011-03-08 08:55:46 +00006897 D.getSourceRange().getBegin(),
6898 D.getIdentifierLoc(),
6899 D.getIdentifier());
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006900 if (Invalid)
6901 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006902
Sebastian Redl54c04d42008-12-22 19:15:10 +00006903 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006904 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006905 PushOnScopeChains(ExDecl, S);
6906 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006907 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006908
Douglas Gregor758a8692009-06-17 21:51:59 +00006909 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006910 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006911}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006912
Abramo Bagnaraea947882011-03-08 16:41:52 +00006913Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006914 Expr *AssertExpr,
Abramo Bagnaraea947882011-03-08 16:41:52 +00006915 Expr *AssertMessageExpr_,
6916 SourceLocation RParenLoc) {
John McCallb268a282010-08-23 23:25:46 +00006917 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006918
Anders Carlsson54b26982009-03-14 00:33:21 +00006919 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6920 llvm::APSInt Value(32);
6921 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00006922 Diag(StaticAssertLoc,
6923 diag::err_static_assert_expression_is_not_constant) <<
Anders Carlsson54b26982009-03-14 00:33:21 +00006924 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006925 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006926 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006927
Anders Carlsson54b26982009-03-14 00:33:21 +00006928 if (Value == 0) {
Abramo Bagnaraea947882011-03-08 16:41:52 +00006929 Diag(StaticAssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006930 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006931 }
6932 }
Mike Stump11289f42009-09-09 15:08:12 +00006933
Douglas Gregoref68fee2010-12-15 23:55:21 +00006934 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
6935 return 0;
6936
Abramo Bagnaraea947882011-03-08 16:41:52 +00006937 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
6938 AssertExpr, AssertMessage, RParenLoc);
Mike Stump11289f42009-09-09 15:08:12 +00006939
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006940 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006941 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006942}
Sebastian Redlf769df52009-03-24 22:27:57 +00006943
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006944/// \brief Perform semantic analysis of the given friend type declaration.
6945///
6946/// \returns A friend declaration that.
6947FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6948 TypeSourceInfo *TSInfo) {
6949 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6950
6951 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006952 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006953
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006954 if (!getLangOptions().CPlusPlus0x) {
6955 // C++03 [class.friend]p2:
6956 // An elaborated-type-specifier shall be used in a friend declaration
6957 // for a class.*
6958 //
6959 // * The class-key of the elaborated-type-specifier is required.
6960 if (!ActiveTemplateInstantiations.empty()) {
6961 // Do not complain about the form of friend template types during
6962 // template instantiation; we will already have complained when the
6963 // template was declared.
6964 } else if (!T->isElaboratedTypeSpecifier()) {
6965 // If we evaluated the type to a record type, suggest putting
6966 // a tag in front.
6967 if (const RecordType *RT = T->getAs<RecordType>()) {
6968 RecordDecl *RD = RT->getDecl();
6969
6970 std::string InsertionText = std::string(" ") + RD->getKindName();
6971
6972 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6973 << (unsigned) RD->getTagKind()
6974 << T
6975 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6976 InsertionText);
6977 } else {
6978 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6979 << T
6980 << SourceRange(FriendLoc, TypeRange.getEnd());
6981 }
6982 } else if (T->getAs<EnumType>()) {
6983 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006984 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006985 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006986 }
6987 }
6988
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006989 // C++0x [class.friend]p3:
6990 // If the type specifier in a friend declaration designates a (possibly
6991 // cv-qualified) class type, that class is declared as a friend; otherwise,
6992 // the friend declaration is ignored.
6993
6994 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6995 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006996
6997 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6998}
6999
John McCallace48cd2010-10-19 01:40:49 +00007000/// Handle a friend tag declaration where the scope specifier was
7001/// templated.
7002Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
7003 unsigned TagSpec, SourceLocation TagLoc,
7004 CXXScopeSpec &SS,
7005 IdentifierInfo *Name, SourceLocation NameLoc,
7006 AttributeList *Attr,
7007 MultiTemplateParamsArg TempParamLists) {
7008 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7009
7010 bool isExplicitSpecialization = false;
John McCallace48cd2010-10-19 01:40:49 +00007011 bool Invalid = false;
7012
7013 if (TemplateParameterList *TemplateParams
7014 = MatchTemplateParametersToScopeSpecifier(TagLoc, SS,
7015 TempParamLists.get(),
7016 TempParamLists.size(),
7017 /*friend*/ true,
7018 isExplicitSpecialization,
7019 Invalid)) {
John McCallace48cd2010-10-19 01:40:49 +00007020 if (TemplateParams->size() > 0) {
7021 // This is a declaration of a class template.
7022 if (Invalid)
7023 return 0;
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007024
John McCallace48cd2010-10-19 01:40:49 +00007025 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
7026 SS, Name, NameLoc, Attr,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007027 TemplateParams, AS_public,
Abramo Bagnara60804e12011-03-18 15:16:37 +00007028 TempParamLists.size() - 1,
Abramo Bagnara0adf29a2011-03-10 13:28:31 +00007029 (TemplateParameterList**) TempParamLists.release()).take();
John McCallace48cd2010-10-19 01:40:49 +00007030 } else {
7031 // The "template<>" header is extraneous.
7032 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
7033 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
7034 isExplicitSpecialization = true;
7035 }
7036 }
7037
7038 if (Invalid) return 0;
7039
7040 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
7041
7042 bool isAllExplicitSpecializations = true;
Abramo Bagnara60804e12011-03-18 15:16:37 +00007043 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
John McCallace48cd2010-10-19 01:40:49 +00007044 if (TempParamLists.get()[I]->size()) {
7045 isAllExplicitSpecializations = false;
7046 break;
7047 }
7048 }
7049
7050 // FIXME: don't ignore attributes.
7051
7052 // If it's explicit specializations all the way down, just forget
7053 // about the template header and build an appropriate non-templated
7054 // friend. TODO: for source fidelity, remember the headers.
7055 if (isAllExplicitSpecializations) {
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007056 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
John McCallace48cd2010-10-19 01:40:49 +00007057 ElaboratedTypeKeyword Keyword
7058 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007059 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
Douglas Gregor9cbc22b2011-02-28 22:42:13 +00007060 *Name, NameLoc);
John McCallace48cd2010-10-19 01:40:49 +00007061 if (T.isNull())
7062 return 0;
7063
7064 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7065 if (isa<DependentNameType>(T)) {
7066 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7067 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007068 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00007069 TL.setNameLoc(NameLoc);
7070 } else {
7071 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
7072 TL.setKeywordLoc(TagLoc);
Douglas Gregor844cb502011-03-01 18:12:44 +00007073 TL.setQualifierLoc(QualifierLoc);
John McCallace48cd2010-10-19 01:40:49 +00007074 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
7075 }
7076
7077 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7078 TSI, FriendLoc);
7079 Friend->setAccess(AS_public);
7080 CurContext->addDecl(Friend);
7081 return Friend;
7082 }
7083
7084 // Handle the case of a templated-scope friend class. e.g.
7085 // template <class T> class A<T>::B;
7086 // FIXME: we don't support these right now.
7087 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7088 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
7089 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7090 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
7091 TL.setKeywordLoc(TagLoc);
Douglas Gregor3d0da5f2011-03-01 01:34:45 +00007092 TL.setQualifierLoc(SS.getWithLocInContext(Context));
John McCallace48cd2010-10-19 01:40:49 +00007093 TL.setNameLoc(NameLoc);
7094
7095 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
7096 TSI, FriendLoc);
7097 Friend->setAccess(AS_public);
7098 Friend->setUnsupportedFriend(true);
7099 CurContext->addDecl(Friend);
7100 return Friend;
7101}
7102
7103
John McCall11083da2009-09-16 22:47:08 +00007104/// Handle a friend type declaration. This works in tandem with
7105/// ActOnTag.
7106///
7107/// Notes on friend class templates:
7108///
7109/// We generally treat friend class declarations as if they were
7110/// declaring a class. So, for example, the elaborated type specifier
7111/// in a friend declaration is required to obey the restrictions of a
7112/// class-head (i.e. no typedefs in the scope chain), template
7113/// parameters are required to match up with simple template-ids, &c.
7114/// However, unlike when declaring a template specialization, it's
7115/// okay to refer to a template specialization without an empty
7116/// template parameter declaration, e.g.
7117/// friend class A<T>::B<unsigned>;
7118/// We permit this as a special case; if there are any template
7119/// parameters present at all, require proper matching, i.e.
7120/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00007121Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCallc9739e32010-10-16 07:23:36 +00007122 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007123 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00007124
7125 assert(DS.isFriendSpecified());
7126 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7127
John McCall11083da2009-09-16 22:47:08 +00007128 // Try to convert the decl specifier to a type. This works for
7129 // friend templates because ActOnTag never produces a ClassTemplateDecl
7130 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00007131 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00007132 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
7133 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00007134 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00007135 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007136
Douglas Gregor6c110f32010-12-16 01:14:37 +00007137 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
7138 return 0;
7139
John McCall11083da2009-09-16 22:47:08 +00007140 // This is definitely an error in C++98. It's probably meant to
7141 // be forbidden in C++0x, too, but the specification is just
7142 // poorly written.
7143 //
7144 // The problem is with declarations like the following:
7145 // template <T> friend A<T>::foo;
7146 // where deciding whether a class C is a friend or not now hinges
7147 // on whether there exists an instantiation of A that causes
7148 // 'foo' to equal C. There are restrictions on class-heads
7149 // (which we declare (by fiat) elaborated friend declarations to
7150 // be) that makes this tractable.
7151 //
7152 // FIXME: handle "template <> friend class A<T>;", which
7153 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00007154 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00007155 Diag(Loc, diag::err_tagless_friend_type_template)
7156 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00007157 return 0;
John McCall11083da2009-09-16 22:47:08 +00007158 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007159
John McCallaa74a0c2009-08-28 07:59:38 +00007160 // C++98 [class.friend]p1: A friend of a class is a function
7161 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00007162 // This is fixed in DR77, which just barely didn't make the C++03
7163 // deadline. It's also a very silly restriction that seriously
7164 // affects inner classes and which nobody else seems to implement;
7165 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00007166 //
7167 // But note that we could warn about it: it's always useless to
7168 // friend one of your own members (it's not, however, worthless to
7169 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00007170
John McCall11083da2009-09-16 22:47:08 +00007171 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007172 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00007173 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007174 NumTempParamLists,
John McCallc9739e32010-10-16 07:23:36 +00007175 TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00007176 TSI,
John McCall11083da2009-09-16 22:47:08 +00007177 DS.getFriendSpecLoc());
7178 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007179 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
7180
7181 if (!D)
John McCall48871652010-08-21 09:40:31 +00007182 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00007183
John McCall11083da2009-09-16 22:47:08 +00007184 D->setAccess(AS_public);
7185 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00007186
John McCall48871652010-08-21 09:40:31 +00007187 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00007188}
7189
John McCallde3fd222010-10-12 23:13:28 +00007190Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
7191 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00007192 const DeclSpec &DS = D.getDeclSpec();
7193
7194 assert(DS.isFriendSpecified());
7195 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
7196
7197 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00007198 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
7199 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00007200
7201 // C++ [class.friend]p1
7202 // A friend of a class is a function or class....
7203 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00007204 // It *doesn't* see through dependent types, which is correct
7205 // according to [temp.arg.type]p3:
7206 // If a declaration acquires a function type through a
7207 // type dependent on a template-parameter and this causes
7208 // a declaration that does not use the syntactic form of a
7209 // function declarator to have a function type, the program
7210 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00007211 if (!T->isFunctionType()) {
7212 Diag(Loc, diag::err_unexpected_friend);
7213
7214 // It might be worthwhile to try to recover by creating an
7215 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00007216 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007217 }
7218
7219 // C++ [namespace.memdef]p3
7220 // - If a friend declaration in a non-local class first declares a
7221 // class or function, the friend class or function is a member
7222 // of the innermost enclosing namespace.
7223 // - The name of the friend is not found by simple name lookup
7224 // until a matching declaration is provided in that namespace
7225 // scope (either before or after the class declaration granting
7226 // friendship).
7227 // - If a friend function is called, its name may be found by the
7228 // name lookup that considers functions from namespaces and
7229 // classes associated with the types of the function arguments.
7230 // - When looking for a prior declaration of a class or a function
7231 // declared as a friend, scopes outside the innermost enclosing
7232 // namespace scope are not considered.
7233
John McCallde3fd222010-10-12 23:13:28 +00007234 CXXScopeSpec &SS = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007235 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7236 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00007237 assert(Name);
7238
Douglas Gregor6c110f32010-12-16 01:14:37 +00007239 // Check for unexpanded parameter packs.
7240 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
7241 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
7242 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
7243 return 0;
7244
John McCall07e91c02009-08-06 02:15:43 +00007245 // The context we found the declaration in, or in which we should
7246 // create the declaration.
7247 DeclContext *DC;
John McCallccbc0322010-10-13 06:22:15 +00007248 Scope *DCScope = S;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007249 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00007250 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00007251
John McCallde3fd222010-10-12 23:13:28 +00007252 // FIXME: there are different rules in local classes
John McCall07e91c02009-08-06 02:15:43 +00007253
John McCallde3fd222010-10-12 23:13:28 +00007254 // There are four cases here.
7255 // - There's no scope specifier, in which case we just go to the
John McCallf7cfb222010-10-13 05:45:15 +00007256 // appropriate scope and look for a function or function template
John McCallde3fd222010-10-12 23:13:28 +00007257 // there as appropriate.
7258 // Recover from invalid scope qualifiers as if they just weren't there.
7259 if (SS.isInvalid() || !SS.isSet()) {
John McCallf7cfb222010-10-13 05:45:15 +00007260 // C++0x [namespace.memdef]p3:
7261 // If the name in a friend declaration is neither qualified nor
7262 // a template-id and the declaration is a function or an
7263 // elaborated-type-specifier, the lookup to determine whether
7264 // the entity has been previously declared shall not consider
7265 // any scopes outside the innermost enclosing namespace.
7266 // C++0x [class.friend]p11:
7267 // If a friend declaration appears in a local class and the name
7268 // specified is an unqualified name, a prior declaration is
7269 // looked up without considering scopes that are outside the
7270 // innermost enclosing non-class scope. For a friend function
7271 // declaration, if there is no prior declaration, the program is
7272 // ill-formed.
7273 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
John McCallf4776592010-10-14 22:22:28 +00007274 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
John McCall07e91c02009-08-06 02:15:43 +00007275
John McCallf7cfb222010-10-13 05:45:15 +00007276 // Find the appropriate context according to the above.
John McCall07e91c02009-08-06 02:15:43 +00007277 DC = CurContext;
7278 while (true) {
7279 // Skip class contexts. If someone can cite chapter and verse
7280 // for this behavior, that would be nice --- it's what GCC and
7281 // EDG do, and it seems like a reasonable intent, but the spec
7282 // really only says that checks for unqualified existing
7283 // declarations should stop at the nearest enclosing namespace,
7284 // not that they should only consider the nearest enclosing
7285 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007286 while (DC->isRecord())
7287 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00007288
John McCall1f82f242009-11-18 22:49:29 +00007289 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00007290
7291 // TODO: decide what we think about using declarations.
John McCallf7cfb222010-10-13 05:45:15 +00007292 if (isLocal || !Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00007293 break;
John McCallf7cfb222010-10-13 05:45:15 +00007294
John McCallf4776592010-10-14 22:22:28 +00007295 if (isTemplateId) {
7296 if (isa<TranslationUnitDecl>(DC)) break;
7297 } else {
7298 if (DC->isFileContext()) break;
7299 }
John McCall07e91c02009-08-06 02:15:43 +00007300 DC = DC->getParent();
7301 }
7302
7303 // C++ [class.friend]p1: A friend of a class is a function or
7304 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00007305 // C++0x changes this for both friend types and functions.
7306 // Most C++ 98 compilers do seem to give an error here, so
7307 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00007308 if (!Previous.empty() && DC->Equals(CurContext)
7309 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00007310 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
John McCallde3fd222010-10-12 23:13:28 +00007311
John McCallccbc0322010-10-13 06:22:15 +00007312 DCScope = getScopeForDeclContext(S, DC);
John McCallf7cfb222010-10-13 05:45:15 +00007313
John McCallde3fd222010-10-12 23:13:28 +00007314 // - There's a non-dependent scope specifier, in which case we
7315 // compute it and do a previous lookup there for a function
7316 // or function template.
7317 } else if (!SS.getScopeRep()->isDependent()) {
7318 DC = computeDeclContext(SS);
7319 if (!DC) return 0;
7320
7321 if (RequireCompleteDeclContext(SS, DC)) return 0;
7322
7323 LookupQualifiedName(Previous, DC);
7324
7325 // Ignore things found implicitly in the wrong scope.
7326 // TODO: better diagnostics for this case. Suggesting the right
7327 // qualified scope would be nice...
7328 LookupResult::Filter F = Previous.makeFilter();
7329 while (F.hasNext()) {
7330 NamedDecl *D = F.next();
7331 if (!DC->InEnclosingNamespaceSetOf(
7332 D->getDeclContext()->getRedeclContext()))
7333 F.erase();
7334 }
7335 F.done();
7336
7337 if (Previous.empty()) {
7338 D.setInvalidType();
7339 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
7340 return 0;
7341 }
7342
7343 // C++ [class.friend]p1: A friend of a class is a function or
7344 // class that is not a member of the class . . .
7345 if (DC->Equals(CurContext))
7346 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
7347
7348 // - There's a scope specifier that does not match any template
7349 // parameter lists, in which case we use some arbitrary context,
7350 // create a method or method template, and wait for instantiation.
7351 // - There's a scope specifier that does match some template
7352 // parameter lists, which we don't handle right now.
7353 } else {
7354 DC = CurContext;
7355 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
John McCall07e91c02009-08-06 02:15:43 +00007356 }
7357
John McCallf7cfb222010-10-13 05:45:15 +00007358 if (!DC->isRecord()) {
John McCall07e91c02009-08-06 02:15:43 +00007359 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00007360 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
7361 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
7362 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00007363 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00007364 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
7365 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00007366 return 0;
John McCall07e91c02009-08-06 02:15:43 +00007367 }
John McCall07e91c02009-08-06 02:15:43 +00007368 }
7369
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007370 bool Redeclaration = false;
John McCallccbc0322010-10-13 06:22:15 +00007371 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00007372 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00007373 IsDefinition,
7374 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00007375 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00007376
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007377 assert(ND->getDeclContext() == DC);
7378 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00007379
John McCall759e32b2009-08-31 22:39:49 +00007380 // Add the function declaration to the appropriate lookup tables,
7381 // adjusting the redeclarations list as necessary. We don't
7382 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00007383 //
John McCall759e32b2009-08-31 22:39:49 +00007384 // Also update the scope-based lookup if the target context's
7385 // lookup context is in lexical scope.
7386 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00007387 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007388 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007389 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007390 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00007391 }
John McCallaa74a0c2009-08-28 07:59:38 +00007392
7393 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00007394 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00007395 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00007396 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00007397 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00007398
John McCallde3fd222010-10-12 23:13:28 +00007399 if (ND->isInvalidDecl())
7400 FrD->setInvalidDecl();
John McCall2c2eb122010-10-16 06:59:13 +00007401 else {
7402 FunctionDecl *FD;
7403 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
7404 FD = FTD->getTemplatedDecl();
7405 else
7406 FD = cast<FunctionDecl>(ND);
7407
7408 // Mark templated-scope function declarations as unsupported.
7409 if (FD->getNumTemplateParameterLists())
7410 FrD->setUnsupportedFriend(true);
7411 }
John McCallde3fd222010-10-12 23:13:28 +00007412
John McCall48871652010-08-21 09:40:31 +00007413 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00007414}
7415
John McCall48871652010-08-21 09:40:31 +00007416void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
7417 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00007418
Sebastian Redlf769df52009-03-24 22:27:57 +00007419 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
7420 if (!Fn) {
7421 Diag(DelLoc, diag::err_deleted_non_function);
7422 return;
7423 }
7424 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
7425 Diag(DelLoc, diag::err_deleted_decl_not_first);
7426 Diag(Prev->getLocation(), diag::note_previous_declaration);
7427 // If the declaration wasn't the first, we delete the function anyway for
7428 // recovery.
7429 }
7430 Fn->setDeleted();
7431}
Sebastian Redl4c018662009-04-27 21:33:24 +00007432
7433static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
John McCall8322c3a2011-02-13 04:07:26 +00007434 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Sebastian Redl4c018662009-04-27 21:33:24 +00007435 Stmt *SubStmt = *CI;
7436 if (!SubStmt)
7437 continue;
7438 if (isa<ReturnStmt>(SubStmt))
7439 Self.Diag(SubStmt->getSourceRange().getBegin(),
7440 diag::err_return_in_constructor_handler);
7441 if (!isa<Expr>(SubStmt))
7442 SearchForReturnInStmt(Self, SubStmt);
7443 }
7444}
7445
7446void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
7447 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
7448 CXXCatchStmt *Handler = TryBlock->getHandler(I);
7449 SearchForReturnInStmt(*this, Handler);
7450 }
7451}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007452
Mike Stump11289f42009-09-09 15:08:12 +00007453bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007454 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00007455 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
7456 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007457
Chandler Carruth284bb2e2010-02-15 11:53:20 +00007458 if (Context.hasSameType(NewTy, OldTy) ||
7459 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007460 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007461
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007462 // Check if the return types are covariant
7463 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00007464
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007465 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007466 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
7467 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007468 NewClassTy = NewPT->getPointeeType();
7469 OldClassTy = OldPT->getPointeeType();
7470 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007471 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
7472 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
7473 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
7474 NewClassTy = NewRT->getPointeeType();
7475 OldClassTy = OldRT->getPointeeType();
7476 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007477 }
7478 }
Mike Stump11289f42009-09-09 15:08:12 +00007479
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007480 // The return types aren't either both pointers or references to a class type.
7481 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00007482 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007483 diag::err_different_return_type_for_overriding_virtual_function)
7484 << New->getDeclName() << NewTy << OldTy;
7485 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00007486
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007487 return true;
7488 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007489
Anders Carlssone60365b2009-12-31 18:34:24 +00007490 // C++ [class.virtual]p6:
7491 // If the return type of D::f differs from the return type of B::f, the
7492 // class type in the return type of D::f shall be complete at the point of
7493 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007494 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
7495 if (!RT->isBeingDefined() &&
7496 RequireCompleteType(New->getLocation(), NewClassTy,
7497 PDiag(diag::err_covariant_return_incomplete)
7498 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00007499 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00007500 }
Anders Carlssone60365b2009-12-31 18:34:24 +00007501
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00007502 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007503 // Check if the new class derives from the old class.
7504 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
7505 Diag(New->getLocation(),
7506 diag::err_covariant_return_not_derived)
7507 << New->getDeclName() << NewTy << OldTy;
7508 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7509 return true;
7510 }
Mike Stump11289f42009-09-09 15:08:12 +00007511
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007512 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00007513 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00007514 diag::err_covariant_return_inaccessible_base,
7515 diag::err_covariant_return_ambiguous_derived_to_base_conv,
7516 // FIXME: Should this point to the return type?
7517 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
John McCallc1465822011-02-14 07:13:47 +00007518 // FIXME: this note won't trigger for delayed access control
7519 // diagnostics, and it's impossible to get an undelayed error
7520 // here from access control during the original parse because
7521 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007522 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7523 return true;
7524 }
7525 }
Mike Stump11289f42009-09-09 15:08:12 +00007526
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007527 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00007528 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007529 Diag(New->getLocation(),
7530 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007531 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007532 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7533 return true;
7534 };
Mike Stump11289f42009-09-09 15:08:12 +00007535
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007536
7537 // The new class type must have the same or less qualifiers as the old type.
7538 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
7539 Diag(New->getLocation(),
7540 diag::err_covariant_return_type_class_type_more_qualified)
7541 << New->getDeclName() << NewTy << OldTy;
7542 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
7543 return true;
7544 };
Mike Stump11289f42009-09-09 15:08:12 +00007545
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00007546 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00007547}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007548
Douglas Gregor21920e372009-12-01 17:24:26 +00007549/// \brief Mark the given method pure.
7550///
7551/// \param Method the method to be marked pure.
7552///
7553/// \param InitRange the source range that covers the "0" initializer.
7554bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00007555 SourceLocation EndLoc = InitRange.getEnd();
7556 if (EndLoc.isValid())
7557 Method->setRangeEnd(EndLoc);
7558
Douglas Gregor21920e372009-12-01 17:24:26 +00007559 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
7560 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00007561 return false;
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00007562 }
Douglas Gregor21920e372009-12-01 17:24:26 +00007563
7564 if (!Method->isInvalidDecl())
7565 Diag(Method->getLocation(), diag::err_non_virtual_pure)
7566 << Method->getDeclName() << InitRange;
7567 return true;
7568}
7569
John McCall1f4ee7b2009-12-19 09:28:58 +00007570/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7571/// an initializer for the out-of-line declaration 'Dcl'. The scope
7572/// is a fresh scope pushed for just this purpose.
7573///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007574/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7575/// static data member of class X, names should be looked up in the scope of
7576/// class X.
John McCall48871652010-08-21 09:40:31 +00007577void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007578 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00007579 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007580
John McCall1f4ee7b2009-12-19 09:28:58 +00007581 // We should only get called for declarations with scope specifiers, like:
7582 // int foo::bar;
7583 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007584 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007585}
7586
7587/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00007588/// initializer for the out-of-line declaration 'D'.
7589void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007590 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00007591 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007592
John McCall1f4ee7b2009-12-19 09:28:58 +00007593 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00007594 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00007595}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007596
7597/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7598/// C++ if/switch/while/for statement.
7599/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00007600DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007601 // C++ 6.4p2:
7602 // The declarator shall not specify a function or an array.
7603 // The type-specifier-seq shall not contain typedef and shall not declare a
7604 // new class or enumeration.
7605 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
7606 "Parser allowed 'typedef' as storage class of condition decl.");
7607
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007608 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00007609 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
7610 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007611
7612 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
7613 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7614 // would be created and CXXConditionDeclExpr wants a VarDecl.
7615 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
7616 << D.getSourceRange();
7617 return DeclResult();
7618 } else if (OwnedTag && OwnedTag->isDefinition()) {
7619 // The type-specifier-seq shall not declare a new class or enumeration.
7620 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
7621 }
7622
John McCall48871652010-08-21 09:40:31 +00007623 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007624 if (!Dcl)
7625 return DeclResult();
7626
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00007627 return Dcl;
7628}
Anders Carlssonf98849e2009-12-02 17:15:43 +00007629
Douglas Gregor88d292c2010-05-13 16:44:06 +00007630void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7631 bool DefinitionRequired) {
7632 // Ignore any vtable uses in unevaluated operands or for classes that do
7633 // not have a vtable.
7634 if (!Class->isDynamicClass() || Class->isDependentContext() ||
7635 CurContext->isDependentContext() ||
7636 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00007637 return;
7638
Douglas Gregor88d292c2010-05-13 16:44:06 +00007639 // Try to insert this class into the map.
7640 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7641 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
7642 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
7643 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00007644 // If we already had an entry, check to see if we are promoting this vtable
7645 // to required a definition. If so, we need to reappend to the VTableUses
7646 // list, since we may have already processed the first entry.
7647 if (DefinitionRequired && !Pos.first->second) {
7648 Pos.first->second = true;
7649 } else {
7650 // Otherwise, we can early exit.
7651 return;
7652 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007653 }
7654
7655 // Local classes need to have their virtual members marked
7656 // immediately. For all other classes, we mark their virtual members
7657 // at the end of the translation unit.
7658 if (Class->isLocalClass())
7659 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00007660 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00007661 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00007662}
7663
Douglas Gregor88d292c2010-05-13 16:44:06 +00007664bool Sema::DefineUsedVTables() {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007665 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00007666 return false;
Chandler Carruth88bfa5e2010-12-12 21:36:11 +00007667
Douglas Gregor88d292c2010-05-13 16:44:06 +00007668 // Note: The VTableUses vector could grow as a result of marking
7669 // the members of a class as "used", so we check the size each
7670 // time through the loop and prefer indices (with are stable) to
7671 // iterators (which are not).
7672 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00007673 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00007674 if (!Class)
7675 continue;
7676
7677 SourceLocation Loc = VTableUses[I].second;
7678
7679 // If this class has a key function, but that key function is
7680 // defined in another translation unit, we don't need to emit the
7681 // vtable even though we're using it.
7682 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007683 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00007684 switch (KeyFunction->getTemplateSpecializationKind()) {
7685 case TSK_Undeclared:
7686 case TSK_ExplicitSpecialization:
7687 case TSK_ExplicitInstantiationDeclaration:
7688 // The key function is in another translation unit.
7689 continue;
7690
7691 case TSK_ExplicitInstantiationDefinition:
7692 case TSK_ImplicitInstantiation:
7693 // We will be instantiating the key function.
7694 break;
7695 }
7696 } else if (!KeyFunction) {
7697 // If we have a class with no key function that is the subject
7698 // of an explicit instantiation declaration, suppress the
7699 // vtable; it will live with the explicit instantiation
7700 // definition.
7701 bool IsExplicitInstantiationDeclaration
7702 = Class->getTemplateSpecializationKind()
7703 == TSK_ExplicitInstantiationDeclaration;
7704 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
7705 REnd = Class->redecls_end();
7706 R != REnd; ++R) {
7707 TemplateSpecializationKind TSK
7708 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
7709 if (TSK == TSK_ExplicitInstantiationDeclaration)
7710 IsExplicitInstantiationDeclaration = true;
7711 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7712 IsExplicitInstantiationDeclaration = false;
7713 break;
7714 }
7715 }
7716
7717 if (IsExplicitInstantiationDeclaration)
7718 continue;
7719 }
7720
7721 // Mark all of the virtual members of this class as referenced, so
7722 // that we can build a vtable. Then, tell the AST consumer that a
7723 // vtable for this class is required.
7724 MarkVirtualMembersReferenced(Loc, Class);
7725 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
7726 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
7727
7728 // Optionally warn if we're emitting a weak vtable.
7729 if (Class->getLinkage() == ExternalLinkage &&
7730 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00007731 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00007732 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
7733 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00007734 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00007735 VTableUses.clear();
7736
Anders Carlsson82fccd02009-12-07 08:24:59 +00007737 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00007738}
Anders Carlsson82fccd02009-12-07 08:24:59 +00007739
Rafael Espindola5b334082010-03-26 00:36:59 +00007740void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
7741 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00007742 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
7743 e = RD->method_end(); i != e; ++i) {
7744 CXXMethodDecl *MD = *i;
7745
7746 // C++ [basic.def.odr]p2:
7747 // [...] A virtual member function is used if it is not pure. [...]
7748 if (MD->isVirtual() && !MD->isPure())
7749 MarkDeclarationReferenced(Loc, MD);
7750 }
Rafael Espindola5b334082010-03-26 00:36:59 +00007751
7752 // Only classes that have virtual bases need a VTT.
7753 if (RD->getNumVBases() == 0)
7754 return;
7755
7756 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
7757 e = RD->bases_end(); i != e; ++i) {
7758 const CXXRecordDecl *Base =
7759 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00007760 if (Base->getNumVBases() == 0)
7761 continue;
7762 MarkVirtualMembersReferenced(Loc, Base);
7763 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00007764}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007765
7766/// SetIvarInitializers - This routine builds initialization ASTs for the
7767/// Objective-C implementation whose ivars need be initialized.
7768void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
7769 if (!getLangOptions().CPlusPlus)
7770 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00007771 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007772 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
7773 CollectIvarsToConstructOrDestruct(OID, ivars);
7774 if (ivars.empty())
7775 return;
Alexis Hunt1d792652011-01-08 20:30:50 +00007776 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007777 for (unsigned i = 0; i < ivars.size(); i++) {
7778 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00007779 if (Field->isInvalidDecl())
7780 continue;
7781
Alexis Hunt1d792652011-01-08 20:30:50 +00007782 CXXCtorInitializer *Member;
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007783 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
7784 InitializationKind InitKind =
7785 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
7786
7787 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00007788 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00007789 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
Douglas Gregora40433a2010-12-07 00:41:46 +00007790 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007791 // Note, MemberInit could actually come back empty if no initialization
7792 // is required (e.g., because it would call a trivial default constructor)
7793 if (!MemberInit.get() || MemberInit.isInvalid())
7794 continue;
John McCallacf0ee52010-10-08 02:01:28 +00007795
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007796 Member =
Alexis Hunt1d792652011-01-08 20:30:50 +00007797 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
7798 SourceLocation(),
7799 MemberInit.takeAs<Expr>(),
7800 SourceLocation());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007801 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00007802
7803 // Be sure that the destructor is accessible and is marked as referenced.
7804 if (const RecordType *RecordTy
7805 = Context.getBaseElementType(Field->getType())
7806 ->getAs<RecordType>()) {
7807 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00007808 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00007809 MarkDeclarationReferenced(Field->getLocation(), Destructor);
7810 CheckDestructorAccess(Field->getLocation(), Destructor,
7811 PDiag(diag::err_access_dtor_ivar)
7812 << Context.getBaseElementType(Field->getType()));
7813 }
7814 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00007815 }
7816 ObjCImplementation->setIvarInitializers(Context,
7817 AllToInit.data(), AllToInit.size());
7818 }
7819}