blob: 1d0b4a9450f89e8887b50ae408e74595720998cf [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
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Initialization.h"
16#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000017#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000018#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000019#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000021#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000022#include "clang/AST/RecordLayout.h"
23#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000024#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000025#include "clang/AST/TypeOrdering.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000026#include "clang/Parse/DeclSpec.h"
27#include "clang/Parse/Template.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000029#include "clang/Lex/Preprocessor.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000031#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000032#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000033
34using namespace clang;
35
Chris Lattner58258242008-04-10 02:22:51 +000036//===----------------------------------------------------------------------===//
37// CheckDefaultArgumentVisitor
38//===----------------------------------------------------------------------===//
39
Chris Lattnerb0d38442008-04-12 23:52:44 +000040namespace {
41 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
42 /// the default argument of a parameter to determine whether it
43 /// contains any ill-formed subexpressions. For example, this will
44 /// diagnose the use of local variables or parameters within the
45 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000046 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000047 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000048 Expr *DefaultArg;
49 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000050
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 public:
Mike Stump11289f42009-09-09 15:08:12 +000052 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000053 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000054
Chris Lattnerb0d38442008-04-12 23:52:44 +000055 bool VisitExpr(Expr *Node);
56 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000057 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 };
Chris Lattner58258242008-04-10 02:22:51 +000059
Chris Lattnerb0d38442008-04-12 23:52:44 +000060 /// VisitExpr - Visit all of the children of this expression.
61 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
62 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000063 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000064 E = Node->child_end(); I != E; ++I)
65 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000066 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000067 }
68
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 /// VisitDeclRefExpr - Visit a reference to a declaration, to
70 /// determine whether this declaration can be used in the default
71 /// argument expression.
72 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000073 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000074 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
75 // C++ [dcl.fct.default]p9
76 // Default arguments are evaluated each time the function is
77 // called. The order of evaluation of function arguments is
78 // unspecified. Consequently, parameters of a function shall not
79 // be used in default argument expressions, even if they are not
80 // evaluated. Parameters of a function declared before a default
81 // argument expression are in scope and can hide namespace and
82 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000083 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000084 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000085 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000086 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000087 // C++ [dcl.fct.default]p7
88 // Local variables shall not be used in default argument
89 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000090 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000091 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000092 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000093 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000094 }
Chris Lattner58258242008-04-10 02:22:51 +000095
Douglas Gregor8e12c382008-11-04 13:41:56 +000096 return false;
97 }
Chris Lattnerb0d38442008-04-12 23:52:44 +000098
Douglas Gregor97a9c812008-11-04 14:32:21 +000099 /// VisitCXXThisExpr - Visit a C++ "this" expression.
100 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
101 // C++ [dcl.fct.default]p8:
102 // The keyword this shall not be used in a default argument of a
103 // member function.
104 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000105 diag::err_param_default_argument_references_this)
106 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000107 }
Chris Lattner58258242008-04-10 02:22:51 +0000108}
109
Anders Carlssonc80a1272009-08-25 02:29:20 +0000110bool
111Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
Mike Stump11289f42009-09-09 15:08:12 +0000112 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000113 if (RequireCompleteType(Param->getLocation(), Param->getType(),
114 diag::err_typecheck_decl_incomplete_type)) {
115 Param->setInvalidDecl();
116 return true;
117 }
118
Anders Carlssonc80a1272009-08-25 02:29:20 +0000119 Expr *Arg = (Expr *)DefaultArg.get();
Mike Stump11289f42009-09-09 15:08:12 +0000120
Anders Carlssonc80a1272009-08-25 02:29:20 +0000121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Douglas Gregor85dabae2009-12-16 01:38:02 +0000127 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
128 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
129 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000130 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
131 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
132 MultiExprArg(*this, (void**)&Arg, 1));
133 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000134 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000136
Anders Carlsson6e997b22009-12-15 20:51:39 +0000137 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000138
Anders Carlssonc80a1272009-08-25 02:29:20 +0000139 // Okay: add the default argument to the parameter
140 Param->setDefaultArg(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Anders Carlssonc80a1272009-08-25 02:29:20 +0000142 DefaultArg.release();
Mike Stump11289f42009-09-09 15:08:12 +0000143
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000144 return false;
Anders Carlssonc80a1272009-08-25 02:29:20 +0000145}
146
Chris Lattner58258242008-04-10 02:22:51 +0000147/// ActOnParamDefaultArgument - Check whether the default argument
148/// provided for a function parameter is well-formed. If so, attach it
149/// to the parameter declaration.
Chris Lattner199abbc2008-04-08 05:04:30 +0000150void
Mike Stump11289f42009-09-09 15:08:12 +0000151Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000152 ExprArg defarg) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000153 if (!param || !defarg.get())
154 return;
Mike Stump11289f42009-09-09 15:08:12 +0000155
Chris Lattner83f095c2009-03-28 19:18:32 +0000156 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson84613c42009-06-12 16:51:40 +0000157 UnparsedDefaultArgLocs.erase(Param);
158
Anders Carlsson3cbc8592009-05-01 19:30:39 +0000159 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner199abbc2008-04-08 05:04:30 +0000160
161 // Default arguments are only permitted in C++
162 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000163 Diag(EqualLoc, diag::err_param_default_argument)
164 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000165 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000166 return;
167 }
168
Anders Carlssonf1c26952009-08-25 01:02:06 +0000169 // Check that the default argument is well-formed
170 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
171 if (DefaultArgChecker.Visit(DefaultArg.get())) {
172 Param->setInvalidDecl();
173 return;
174 }
Mike Stump11289f42009-09-09 15:08:12 +0000175
Anders Carlssonc80a1272009-08-25 02:29:20 +0000176 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000177}
178
Douglas Gregor58354032008-12-24 00:01:03 +0000179/// ActOnParamUnparsedDefaultArgument - We've seen a default
180/// argument for a function parameter, but we can't parse it yet
181/// because we're inside a class definition. Note that this default
182/// argument will be parsed later.
Mike Stump11289f42009-09-09 15:08:12 +0000183void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000184 SourceLocation EqualLoc,
185 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000186 if (!param)
187 return;
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattner83f095c2009-03-28 19:18:32 +0000189 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000190 if (Param)
191 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000192
Anders Carlsson84613c42009-06-12 16:51:40 +0000193 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000194}
195
Douglas Gregor4d87df52008-12-16 21:30:33 +0000196/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
197/// the default argument for the parameter param failed.
Chris Lattner83f095c2009-03-28 19:18:32 +0000198void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000199 if (!param)
200 return;
Mike Stump11289f42009-09-09 15:08:12 +0000201
Anders Carlsson84613c42009-06-12 16:51:40 +0000202 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Mike Stump11289f42009-09-09 15:08:12 +0000203
Anders Carlsson84613c42009-06-12 16:51:40 +0000204 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000205
Anders Carlsson84613c42009-06-12 16:51:40 +0000206 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000207}
208
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000209/// CheckExtraCXXDefaultArguments - Check for any extra default
210/// arguments in the declarator, which is not a function declaration
211/// or definition and therefore is not permitted to have default
212/// arguments. This routine should be invoked for every declarator
213/// that is not a function declaration or definition.
214void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
215 // C++ [dcl.fct.default]p3
216 // A default argument expression shall be specified only in the
217 // parameter-declaration-clause of a function declaration or in a
218 // template-parameter (14.1). It shall not be specified for a
219 // parameter pack. If it is specified in a
220 // parameter-declaration-clause, it shall not occur within a
221 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000222 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000223 DeclaratorChunk &chunk = D.getTypeObject(i);
224 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000225 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
226 ParmVarDecl *Param =
227 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +0000228 if (Param->hasUnparsedDefaultArg()) {
229 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000230 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
231 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
232 delete Toks;
233 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000234 } else if (Param->getDefaultArg()) {
235 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
236 << Param->getDefaultArg()->getSourceRange();
237 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000238 }
239 }
240 }
241 }
242}
243
Chris Lattner199abbc2008-04-08 05:04:30 +0000244// MergeCXXFunctionDecl - Merge two declarations of the same C++
245// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000246// type. Subroutine of MergeFunctionDecl. Returns true if there was an
247// error, false otherwise.
248bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
249 bool Invalid = false;
250
Chris Lattner199abbc2008-04-08 05:04:30 +0000251 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000252 // For non-template functions, default arguments can be added in
253 // later declarations of a function in the same
254 // scope. Declarations in different scopes have completely
255 // distinct sets of default arguments. That is, declarations in
256 // inner scopes do not acquire default arguments from
257 // declarations in outer scopes, and vice versa. In a given
258 // function declaration, all parameters subsequent to a
259 // parameter with a default argument shall have default
260 // arguments supplied in this or previous declarations. A
261 // default argument shall not be redefined by a later
262 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000263 //
264 // C++ [dcl.fct.default]p6:
265 // Except for member functions of class templates, the default arguments
266 // in a member function definition that appears outside of the class
267 // definition are added to the set of default arguments provided by the
268 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000269 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
270 ParmVarDecl *OldParam = Old->getParamDecl(p);
271 ParmVarDecl *NewParam = New->getParamDecl(p);
272
Douglas Gregorc732aba2009-09-11 18:44:32 +0000273 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000274 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
275 // hint here. Alternatively, we could walk the type-source information
276 // for NewParam to find the last source location in the type... but it
277 // isn't worth the effort right now. This is the kind of test case that
278 // is hard to get right:
279
280 // int f(int);
281 // void g(int (*fp)(int) = f);
282 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000283 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000284 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000285 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000286
287 // Look for the function declaration where the default argument was
288 // actually written, which may be a declaration prior to Old.
289 for (FunctionDecl *Older = Old->getPreviousDeclaration();
290 Older; Older = Older->getPreviousDeclaration()) {
291 if (!Older->getParamDecl(p)->hasDefaultArg())
292 break;
293
294 OldParam = Older->getParamDecl(p);
295 }
296
297 Diag(OldParam->getLocation(), diag::note_previous_definition)
298 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000299 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000300 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000301 // Merge the old default argument into the new parameter.
302 // It's important to use getInit() here; getDefaultArg()
303 // strips off any top-level CXXExprWithTemporaries.
John McCallf3cd6652010-03-12 18:31:32 +0000304 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000305 if (OldParam->hasUninstantiatedDefaultArg())
306 NewParam->setUninstantiatedDefaultArg(
307 OldParam->getUninstantiatedDefaultArg());
308 else
John McCalle61b02b2010-05-04 01:53:42 +0000309 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000310 } else if (NewParam->hasDefaultArg()) {
311 if (New->getDescribedFunctionTemplate()) {
312 // Paragraph 4, quoted above, only applies to non-template functions.
313 Diag(NewParam->getLocation(),
314 diag::err_param_default_argument_template_redecl)
315 << NewParam->getDefaultArgRange();
316 Diag(Old->getLocation(), diag::note_template_prev_declaration)
317 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000318 } else if (New->getTemplateSpecializationKind()
319 != TSK_ImplicitInstantiation &&
320 New->getTemplateSpecializationKind() != TSK_Undeclared) {
321 // C++ [temp.expr.spec]p21:
322 // Default function arguments shall not be specified in a declaration
323 // or a definition for one of the following explicit specializations:
324 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000325 // - the explicit specialization of a member function template;
326 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000327 // template where the class template specialization to which the
328 // member function specialization belongs is implicitly
329 // instantiated.
330 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
331 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
332 << New->getDeclName()
333 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000334 } else if (New->getDeclContext()->isDependentContext()) {
335 // C++ [dcl.fct.default]p6 (DR217):
336 // Default arguments for a member function of a class template shall
337 // be specified on the initial declaration of the member function
338 // within the class template.
339 //
340 // Reading the tea leaves a bit in DR217 and its reference to DR205
341 // leads me to the conclusion that one cannot add default function
342 // arguments for an out-of-line definition of a member function of a
343 // dependent type.
344 int WhichKind = 2;
345 if (CXXRecordDecl *Record
346 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
347 if (Record->getDescribedClassTemplate())
348 WhichKind = 0;
349 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
350 WhichKind = 1;
351 else
352 WhichKind = 2;
353 }
354
355 Diag(NewParam->getLocation(),
356 diag::err_param_default_argument_member_template_redecl)
357 << WhichKind
358 << NewParam->getDefaultArgRange();
359 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000360 }
361 }
362
Douglas Gregorf40863c2010-02-12 07:32:17 +0000363 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000364 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000365
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000366 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000367}
368
369/// CheckCXXDefaultArguments - Verify that the default arguments for a
370/// function declaration are well-formed according to C++
371/// [dcl.fct.default].
372void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
373 unsigned NumParams = FD->getNumParams();
374 unsigned p;
375
376 // Find first parameter with a default argument
377 for (p = 0; p < NumParams; ++p) {
378 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000379 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000380 break;
381 }
382
383 // C++ [dcl.fct.default]p4:
384 // In a given function declaration, all parameters
385 // subsequent to a parameter with a default argument shall
386 // have default arguments supplied in this or previous
387 // declarations. A default argument shall not be redefined
388 // by a later declaration (not even to the same value).
389 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000390 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000391 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000392 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000393 if (Param->isInvalidDecl())
394 /* We already complained about this parameter. */;
395 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000396 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000397 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000398 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000399 else
Mike Stump11289f42009-09-09 15:08:12 +0000400 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000401 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000402
Chris Lattner199abbc2008-04-08 05:04:30 +0000403 LastMissingDefaultArg = p;
404 }
405 }
406
407 if (LastMissingDefaultArg > 0) {
408 // Some default arguments were missing. Clear out all of the
409 // default arguments up to (and including) the last missing
410 // default argument, so that we leave the function parameters
411 // in a semantically valid state.
412 for (p = 0; p <= LastMissingDefaultArg; ++p) {
413 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000414 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000415 Param->setDefaultArg(0);
416 }
417 }
418 }
419}
Douglas Gregor556877c2008-04-13 21:30:24 +0000420
Douglas Gregor61956c42008-10-31 09:07:45 +0000421/// isCurrentClassName - Determine whether the identifier II is the
422/// name of the class type currently being defined. In the case of
423/// nested classes, this will only return true if II is the name of
424/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000425bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
426 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000427 assert(getLangOptions().CPlusPlus && "No class names in C!");
428
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000429 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000430 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000431 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
433 } else
434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
435
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000436 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000437 return &II == CurDecl->getIdentifier();
438 else
439 return false;
440}
441
Mike Stump11289f42009-09-09 15:08:12 +0000442/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000443///
444/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
445/// and returns NULL otherwise.
446CXXBaseSpecifier *
447Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
448 SourceRange SpecifierRange,
449 bool Virtual, AccessSpecifier Access,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000450 TypeSourceInfo *TInfo) {
451 QualType BaseType = TInfo->getType();
452
Douglas Gregor463421d2009-03-03 04:44:36 +0000453 // C++ [class.union]p1:
454 // A union shall not have base classes.
455 if (Class->isUnion()) {
456 Diag(Class->getLocation(), diag::err_base_clause_on_union)
457 << SpecifierRange;
458 return 0;
459 }
460
461 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000462 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000463 Class->getTagKind() == TTK_Class,
464 Access, TInfo);
465
466 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000467
468 // Base specifiers must be record types.
469 if (!BaseType->isRecordType()) {
470 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
471 return 0;
472 }
473
474 // C++ [class.union]p1:
475 // A union shall not be used as a base class.
476 if (BaseType->isUnionType()) {
477 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
478 return 0;
479 }
480
481 // C++ [class.derived]p2:
482 // The class-name in a base-specifier shall not be an incompletely
483 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000484 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000485 PDiag(diag::err_incomplete_base_class)
486 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000487 return 0;
488
Eli Friedmanc96d4962009-08-15 21:55:26 +0000489 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000490 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000491 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000492 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000493 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000494 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
495 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000496
Alexis Hunt96d5c762009-11-21 08:43:09 +0000497 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
498 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
499 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000500 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
501 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000502 return 0;
503 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000504
Eli Friedman89c038e2009-12-05 23:03:49 +0000505 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000506
507 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000508 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000509 Class->getTagKind() == TTK_Class,
510 Access, TInfo);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000511}
512
513void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
514 const CXXRecordDecl *BaseClass,
515 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000516 // A class with a non-empty base class is not empty.
517 // FIXME: Standard ref?
518 if (!BaseClass->isEmpty())
519 Class->setEmpty(false);
520
521 // C++ [class.virtual]p1:
522 // A class that [...] inherits a virtual function is called a polymorphic
523 // class.
524 if (BaseClass->isPolymorphic())
525 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000526
Douglas Gregor463421d2009-03-03 04:44:36 +0000527 // C++ [dcl.init.aggr]p1:
528 // An aggregate is [...] a class with [...] no base classes [...].
529 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000530
531 // C++ [class]p4:
532 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000533 Class->setPOD(false);
534
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000535 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000536 // C++ [class.ctor]p5:
537 // A constructor is trivial if its class has no virtual base classes.
538 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000539
540 // C++ [class.copy]p6:
541 // A copy constructor is trivial if its class has no virtual base classes.
542 Class->setHasTrivialCopyConstructor(false);
543
544 // C++ [class.copy]p11:
545 // A copy assignment operator is trivial if its class has no virtual
546 // base classes.
547 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000548
549 // C++0x [meta.unary.prop] is_empty:
550 // T is a class type, but not a union type, with ... no virtual base
551 // classes
552 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000553 } else {
554 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000555 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000556 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000557 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000558 Class->setHasTrivialConstructor(false);
559
560 // C++ [class.copy]p6:
561 // A copy constructor is trivial if all the direct base classes of its
562 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000563 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000564 Class->setHasTrivialCopyConstructor(false);
565
566 // C++ [class.copy]p11:
567 // A copy assignment operator is trivial if all the direct base classes
568 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000569 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000570 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000571 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000572
573 // C++ [class.ctor]p3:
574 // A destructor is trivial if all the direct base classes of its class
575 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000576 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000577 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000578}
579
Douglas Gregor556877c2008-04-13 21:30:24 +0000580/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
581/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000582/// example:
583/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000584/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000585Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000586Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000587 bool Virtual, AccessSpecifier Access,
588 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000589 if (!classdecl)
590 return true;
591
Douglas Gregorc40290e2009-03-09 23:48:35 +0000592 AdjustDeclIfTemplate(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000593 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
594 if (!Class)
595 return true;
596
Nick Lewycky19b9f952010-07-26 16:56:01 +0000597 TypeSourceInfo *TInfo = 0;
598 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor463421d2009-03-03 04:44:36 +0000599 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000600 Virtual, Access, TInfo))
Douglas Gregor463421d2009-03-03 04:44:36 +0000601 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000602
Douglas Gregor463421d2009-03-03 04:44:36 +0000603 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000604}
Douglas Gregor556877c2008-04-13 21:30:24 +0000605
Douglas Gregor463421d2009-03-03 04:44:36 +0000606/// \brief Performs the actual work of attaching the given base class
607/// specifiers to a C++ class.
608bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
609 unsigned NumBases) {
610 if (NumBases == 0)
611 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000612
613 // Used to keep track of which base types we have already seen, so
614 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000615 // that the key is always the unqualified canonical type of the base
616 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000617 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
618
619 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000620 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000621 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000622 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000623 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000624 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000625 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000626 if (!Class->hasObjectMember()) {
627 if (const RecordType *FDTTy =
628 NewBaseType.getTypePtr()->getAs<RecordType>())
629 if (FDTTy->getDecl()->hasObjectMember())
630 Class->setHasObjectMember(true);
631 }
632
Douglas Gregor29a92472008-10-22 17:49:05 +0000633 if (KnownBaseTypes[NewBaseType]) {
634 // C++ [class.mi]p3:
635 // A class shall not be specified as a direct base class of a
636 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000637 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000638 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000639 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000640 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000641
642 // Delete the duplicate base class specifier; we're going to
643 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000644 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000645
646 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000647 } else {
648 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000649 KnownBaseTypes[NewBaseType] = Bases[idx];
650 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000651 }
652 }
653
654 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000655 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000656
657 // Delete the remaining (good) base class specifiers, since their
658 // data has been copied into the CXXRecordDecl.
659 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000660 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000661
662 return Invalid;
663}
664
665/// ActOnBaseSpecifiers - Attach the given base specifiers to the
666/// class, after checking whether there are any duplicate base
667/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000668void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000669 unsigned NumBases) {
670 if (!ClassDecl || !Bases || !NumBases)
671 return;
672
673 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000674 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000675 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000676}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000677
John McCalle78aac42010-03-10 03:28:59 +0000678static CXXRecordDecl *GetClassForType(QualType T) {
679 if (const RecordType *RT = T->getAs<RecordType>())
680 return cast<CXXRecordDecl>(RT->getDecl());
681 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
682 return ICT->getDecl();
683 else
684 return 0;
685}
686
Douglas Gregor36d1b142009-10-06 17:59:45 +0000687/// \brief Determine whether the type \p Derived is a C++ class that is
688/// derived from the type \p Base.
689bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
690 if (!getLangOptions().CPlusPlus)
691 return false;
John McCalle78aac42010-03-10 03:28:59 +0000692
693 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
694 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000695 return false;
696
John McCalle78aac42010-03-10 03:28:59 +0000697 CXXRecordDecl *BaseRD = GetClassForType(Base);
698 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000699 return false;
700
John McCall67da35c2010-02-04 22:26:26 +0000701 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
702 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000703}
704
705/// \brief Determine whether the type \p Derived is a C++ class that is
706/// derived from the type \p Base.
707bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
708 if (!getLangOptions().CPlusPlus)
709 return false;
710
John McCalle78aac42010-03-10 03:28:59 +0000711 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
712 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000713 return false;
714
John McCalle78aac42010-03-10 03:28:59 +0000715 CXXRecordDecl *BaseRD = GetClassForType(Base);
716 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000717 return false;
718
Douglas Gregor36d1b142009-10-06 17:59:45 +0000719 return DerivedRD->isDerivedFrom(BaseRD, Paths);
720}
721
Anders Carlssona70cff62010-04-24 19:06:50 +0000722void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000723 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000724 assert(BasePathArray.empty() && "Base path array must be empty!");
725 assert(Paths.isRecordingPaths() && "Must record paths!");
726
727 const CXXBasePath &Path = Paths.front();
728
729 // We first go backward and check if we have a virtual base.
730 // FIXME: It would be better if CXXBasePath had the base specifier for
731 // the nearest virtual base.
732 unsigned Start = 0;
733 for (unsigned I = Path.size(); I != 0; --I) {
734 if (Path[I - 1].Base->isVirtual()) {
735 Start = I - 1;
736 break;
737 }
738 }
739
740 // Now add all bases.
741 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000742 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000743}
744
Douglas Gregor88d292c2010-05-13 16:44:06 +0000745/// \brief Determine whether the given base path includes a virtual
746/// base class.
John McCallcf142162010-08-07 06:22:56 +0000747bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
748 for (CXXCastPath::const_iterator B = BasePath.begin(),
749 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000750 B != BEnd; ++B)
751 if ((*B)->isVirtual())
752 return true;
753
754 return false;
755}
756
Douglas Gregor36d1b142009-10-06 17:59:45 +0000757/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
758/// conversion (where Derived and Base are class types) is
759/// well-formed, meaning that the conversion is unambiguous (and
760/// that all of the base classes are accessible). Returns true
761/// and emits a diagnostic if the code is ill-formed, returns false
762/// otherwise. Loc is the location where this routine should point to
763/// if there is an error, and Range is the source range to highlight
764/// if there is an error.
765bool
766Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000767 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000768 unsigned AmbigiousBaseConvID,
769 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000770 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000771 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000772 // First, determine whether the path from Derived to Base is
773 // ambiguous. This is slightly more expensive than checking whether
774 // the Derived to Base conversion exists, because here we need to
775 // explore multiple paths to determine if there is an ambiguity.
776 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
777 /*DetectVirtual=*/false);
778 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
779 assert(DerivationOkay &&
780 "Can only be used with a derived-to-base conversion");
781 (void)DerivationOkay;
782
783 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000784 if (InaccessibleBaseID) {
785 // Check that the base class can be accessed.
786 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
787 InaccessibleBaseID)) {
788 case AR_inaccessible:
789 return true;
790 case AR_accessible:
791 case AR_dependent:
792 case AR_delayed:
793 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000794 }
John McCall5b0829a2010-02-10 09:31:12 +0000795 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000796
797 // Build a base path if necessary.
798 if (BasePath)
799 BuildBasePathArray(Paths, *BasePath);
800 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000801 }
802
803 // We know that the derived-to-base conversion is ambiguous, and
804 // we're going to produce a diagnostic. Perform the derived-to-base
805 // search just one more time to compute all of the possible paths so
806 // that we can print them out. This is more expensive than any of
807 // the previous derived-to-base checks we've done, but at this point
808 // performance isn't as much of an issue.
809 Paths.clear();
810 Paths.setRecordingPaths(true);
811 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
812 assert(StillOkay && "Can only be used with a derived-to-base conversion");
813 (void)StillOkay;
814
815 // Build up a textual representation of the ambiguous paths, e.g.,
816 // D -> B -> A, that will be used to illustrate the ambiguous
817 // conversions in the diagnostic. We only print one of the paths
818 // to each base class subobject.
819 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
820
821 Diag(Loc, AmbigiousBaseConvID)
822 << Derived << Base << PathDisplayStr << Range << Name;
823 return true;
824}
825
826bool
827Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000828 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000829 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000830 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000831 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000832 IgnoreAccess ? 0
833 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000834 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000835 Loc, Range, DeclarationName(),
836 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000837}
838
839
840/// @brief Builds a string representing ambiguous paths from a
841/// specific derived class to different subobjects of the same base
842/// class.
843///
844/// This function builds a string that can be used in error messages
845/// to show the different paths that one can take through the
846/// inheritance hierarchy to go from the derived class to different
847/// subobjects of a base class. The result looks something like this:
848/// @code
849/// struct D -> struct B -> struct A
850/// struct D -> struct C -> struct A
851/// @endcode
852std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
853 std::string PathDisplayStr;
854 std::set<unsigned> DisplayedPaths;
855 for (CXXBasePaths::paths_iterator Path = Paths.begin();
856 Path != Paths.end(); ++Path) {
857 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
858 // We haven't displayed a path to this particular base
859 // class subobject yet.
860 PathDisplayStr += "\n ";
861 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
862 for (CXXBasePath::const_iterator Element = Path->begin();
863 Element != Path->end(); ++Element)
864 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
865 }
866 }
867
868 return PathDisplayStr;
869}
870
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000871//===----------------------------------------------------------------------===//
872// C++ class member Handling
873//===----------------------------------------------------------------------===//
874
Abramo Bagnarad7340582010-06-05 05:09:32 +0000875/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
876Sema::DeclPtrTy
877Sema::ActOnAccessSpecifier(AccessSpecifier Access,
878 SourceLocation ASLoc, SourceLocation ColonLoc) {
879 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
880 AccessSpecDecl* ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
881 ASLoc, ColonLoc);
882 CurContext->addHiddenDecl(ASDecl);
883 return DeclPtrTy::make(ASDecl);
884}
885
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000886/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
887/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
888/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000889/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000890Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000891Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000892 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000893 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
894 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000895 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000896 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
897 DeclarationName Name = NameInfo.getName();
898 SourceLocation Loc = NameInfo.getLoc();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000899 Expr *BitWidth = static_cast<Expr*>(BW);
900 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000901
John McCallb1cd7da2010-06-04 08:34:12 +0000902 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000903 assert(!DS.isFriendSpecified());
904
John McCallb1cd7da2010-06-04 08:34:12 +0000905 bool isFunc = false;
906 if (D.isFunctionDeclarator())
907 isFunc = true;
908 else if (D.getNumTypeObjects() == 0 &&
909 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
910 QualType TDType = GetTypeFromParser(DS.getTypeRep());
911 isFunc = TDType->isFunctionType();
912 }
913
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000914 // C++ 9.2p6: A member shall not be declared to have automatic storage
915 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000916 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
917 // data members and cannot be applied to names declared const or static,
918 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000919 switch (DS.getStorageClassSpec()) {
920 case DeclSpec::SCS_unspecified:
921 case DeclSpec::SCS_typedef:
922 case DeclSpec::SCS_static:
923 // FALL THROUGH.
924 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000925 case DeclSpec::SCS_mutable:
926 if (isFunc) {
927 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000928 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000929 else
Chris Lattner3b054132008-11-19 05:08:23 +0000930 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000931
Sebastian Redl8071edb2008-11-17 23:24:37 +0000932 // FIXME: It would be nicer if the keyword was ignored only for this
933 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000934 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000935 }
936 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000937 default:
938 if (DS.getStorageClassSpecLoc().isValid())
939 Diag(DS.getStorageClassSpecLoc(),
940 diag::err_storageclass_invalid_for_member);
941 else
942 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
943 D.getMutableDeclSpec().ClearStorageClassSpecs();
944 }
945
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000946 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
947 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000948 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000949
950 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000951 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000952 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000953 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
954 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000955 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000956 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000957 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000958 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000959 if (!Member) {
960 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000961 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000962 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000963
964 // Non-instance-fields can't have a bitfield.
965 if (BitWidth) {
966 if (Member->isInvalidDecl()) {
967 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000968 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000969 // C++ 9.6p3: A bit-field shall not be a static member.
970 // "static member 'A' cannot be a bit-field"
971 Diag(Loc, diag::err_static_not_bitfield)
972 << Name << BitWidth->getSourceRange();
973 } else if (isa<TypedefDecl>(Member)) {
974 // "typedef member 'x' cannot be a bit-field"
975 Diag(Loc, diag::err_typedef_not_bitfield)
976 << Name << BitWidth->getSourceRange();
977 } else {
978 // A function typedef ("typedef int f(); f a;").
979 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
980 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000981 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000982 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000983 }
Mike Stump11289f42009-09-09 15:08:12 +0000984
Chris Lattnerd26760a2009-03-05 23:01:03 +0000985 DeleteExpr(BitWidth);
986 BitWidth = 0;
987 Member->setInvalidDecl();
988 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000989
990 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000991
Douglas Gregor3447e762009-08-20 22:52:58 +0000992 // If we have declared a member function template, set the access of the
993 // templated declaration as well.
994 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
995 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000996 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000997
Douglas Gregor92751d42008-11-17 22:58:34 +0000998 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000999
Douglas Gregor0c880302009-03-11 23:00:04 +00001000 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +00001001 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001002 if (Deleted) // FIXME: Source location is not very good.
1003 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001004
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001005 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001006 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001007 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001008 }
Chris Lattner83f095c2009-03-28 19:18:32 +00001009 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001010}
1011
Douglas Gregor15e77a22009-12-31 09:10:24 +00001012/// \brief Find the direct and/or virtual base specifiers that
1013/// correspond to the given base type, for use in base initialization
1014/// within a constructor.
1015static bool FindBaseInitializer(Sema &SemaRef,
1016 CXXRecordDecl *ClassDecl,
1017 QualType BaseType,
1018 const CXXBaseSpecifier *&DirectBaseSpec,
1019 const CXXBaseSpecifier *&VirtualBaseSpec) {
1020 // First, check for a direct base class.
1021 DirectBaseSpec = 0;
1022 for (CXXRecordDecl::base_class_const_iterator Base
1023 = ClassDecl->bases_begin();
1024 Base != ClassDecl->bases_end(); ++Base) {
1025 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1026 // We found a direct base of this type. That's what we're
1027 // initializing.
1028 DirectBaseSpec = &*Base;
1029 break;
1030 }
1031 }
1032
1033 // Check for a virtual base class.
1034 // FIXME: We might be able to short-circuit this if we know in advance that
1035 // there are no virtual bases.
1036 VirtualBaseSpec = 0;
1037 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1038 // We haven't found a base yet; search the class hierarchy for a
1039 // virtual base class.
1040 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1041 /*DetectVirtual=*/false);
1042 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1043 BaseType, Paths)) {
1044 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1045 Path != Paths.end(); ++Path) {
1046 if (Path->back().Base->isVirtual()) {
1047 VirtualBaseSpec = Path->back().Base;
1048 break;
1049 }
1050 }
1051 }
1052 }
1053
1054 return DirectBaseSpec || VirtualBaseSpec;
1055}
1056
Douglas Gregore8381c02008-11-05 04:29:56 +00001057/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001058Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +00001059Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001060 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001061 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001062 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001063 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001064 SourceLocation IdLoc,
1065 SourceLocation LParenLoc,
1066 ExprTy **Args, unsigned NumArgs,
1067 SourceLocation *CommaLocs,
1068 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001069 if (!ConstructorD)
1070 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001071
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001072 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001073
1074 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +00001075 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +00001076 if (!Constructor) {
1077 // The user wrote a constructor initializer on a function that is
1078 // not a C++ constructor. Ignore the error for now, because we may
1079 // have more member initializers coming; we'll diagnose it just
1080 // once in ActOnMemInitializers.
1081 return true;
1082 }
1083
1084 CXXRecordDecl *ClassDecl = Constructor->getParent();
1085
1086 // C++ [class.base.init]p2:
1087 // Names in a mem-initializer-id are looked up in the scope of the
1088 // constructor’s class and, if not found in that scope, are looked
1089 // up in the scope containing the constructor’s
1090 // definition. [Note: if the constructor’s class contains a member
1091 // with the same name as a direct or virtual base class of the
1092 // class, a mem-initializer-id naming the member or base class and
1093 // composed of a single identifier refers to the class member. A
1094 // mem-initializer-id for the hidden base class may be specified
1095 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001096 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001097 // Look for a member, first.
1098 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001099 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001100 = ClassDecl->lookup(MemberOrBase);
1101 if (Result.first != Result.second)
1102 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001103
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001104 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001105
Eli Friedman8e1433b2009-07-29 19:44:27 +00001106 if (Member)
1107 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001108 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001109 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001110 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001111 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001112 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001113
1114 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001115 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001116 } else {
1117 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1118 LookupParsedName(R, S, &SS);
1119
1120 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1121 if (!TyD) {
1122 if (R.isAmbiguous()) return true;
1123
John McCallda6841b2010-04-09 19:01:14 +00001124 // We don't want access-control diagnostics here.
1125 R.suppressDiagnostics();
1126
Douglas Gregora3b624a2010-01-19 06:46:48 +00001127 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1128 bool NotUnknownSpecialization = false;
1129 DeclContext *DC = computeDeclContext(SS, false);
1130 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1131 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1132
1133 if (!NotUnknownSpecialization) {
1134 // When the scope specifier can refer to a member of an unknown
1135 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001136 BaseType = CheckTypenameType(ETK_None,
1137 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001138 *MemberOrBase, SourceLocation(),
1139 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001140 if (BaseType.isNull())
1141 return true;
1142
Douglas Gregora3b624a2010-01-19 06:46:48 +00001143 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001144 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001145 }
1146 }
1147
Douglas Gregor15e77a22009-12-31 09:10:24 +00001148 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001149 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001150 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1151 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001152 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1153 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1154 // We have found a non-static data member with a similar
1155 // name to what was typed; complain and initialize that
1156 // member.
1157 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1158 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001159 << FixItHint::CreateReplacement(R.getNameLoc(),
1160 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001161 Diag(Member->getLocation(), diag::note_previous_decl)
1162 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001163
1164 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1165 LParenLoc, RParenLoc);
1166 }
1167 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1168 const CXXBaseSpecifier *DirectBaseSpec;
1169 const CXXBaseSpecifier *VirtualBaseSpec;
1170 if (FindBaseInitializer(*this, ClassDecl,
1171 Context.getTypeDeclType(Type),
1172 DirectBaseSpec, VirtualBaseSpec)) {
1173 // We have found a direct or virtual base class with a
1174 // similar name to what was typed; complain and initialize
1175 // that base class.
1176 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1177 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001178 << FixItHint::CreateReplacement(R.getNameLoc(),
1179 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001180
1181 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1182 : VirtualBaseSpec;
1183 Diag(BaseSpec->getSourceRange().getBegin(),
1184 diag::note_base_class_specified_here)
1185 << BaseSpec->getType()
1186 << BaseSpec->getSourceRange();
1187
Douglas Gregor15e77a22009-12-31 09:10:24 +00001188 TyD = Type;
1189 }
1190 }
1191 }
1192
Douglas Gregora3b624a2010-01-19 06:46:48 +00001193 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001194 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1195 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1196 return true;
1197 }
John McCallb5a0d312009-12-21 10:41:20 +00001198 }
1199
Douglas Gregora3b624a2010-01-19 06:46:48 +00001200 if (BaseType.isNull()) {
1201 BaseType = Context.getTypeDeclType(TyD);
1202 if (SS.isSet()) {
1203 NestedNameSpecifier *Qualifier =
1204 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001205
Douglas Gregora3b624a2010-01-19 06:46:48 +00001206 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001207 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001208 }
John McCallb5a0d312009-12-21 10:41:20 +00001209 }
1210 }
Mike Stump11289f42009-09-09 15:08:12 +00001211
John McCallbcd03502009-12-07 02:54:59 +00001212 if (!TInfo)
1213 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001214
John McCallbcd03502009-12-07 02:54:59 +00001215 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001216 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001217}
1218
John McCalle22a04a2009-11-04 23:02:40 +00001219/// Checks an initializer expression for use of uninitialized fields, such as
1220/// containing the field that is being initialized. Returns true if there is an
1221/// uninitialized field was used an updates the SourceLocation parameter; false
1222/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001223static bool InitExprContainsUninitializedFields(const Stmt *S,
1224 const FieldDecl *LhsField,
1225 SourceLocation *L) {
1226 if (isa<CallExpr>(S)) {
1227 // Do not descend into function calls or constructors, as the use
1228 // of an uninitialized field may be valid. One would have to inspect
1229 // the contents of the function/ctor to determine if it is safe or not.
1230 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1231 // may be safe, depending on what the function/ctor does.
1232 return false;
1233 }
1234 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1235 const NamedDecl *RhsField = ME->getMemberDecl();
John McCalle22a04a2009-11-04 23:02:40 +00001236 if (RhsField == LhsField) {
1237 // Initializing a field with itself. Throw a warning.
1238 // But wait; there are exceptions!
1239 // Exception #1: The field may not belong to this record.
1240 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001241 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001242 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1243 // Even though the field matches, it does not belong to this record.
1244 return false;
1245 }
1246 // None of the exceptions triggered; return true to indicate an
1247 // uninitialized field was used.
1248 *L = ME->getMemberLoc();
1249 return true;
1250 }
1251 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001252 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1253 it != e; ++it) {
1254 if (!*it) {
1255 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001256 continue;
1257 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001258 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1259 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001260 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001261 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001262}
1263
Eli Friedman8e1433b2009-07-29 19:44:27 +00001264Sema::MemInitResult
1265Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1266 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001267 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001268 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001269 // Diagnose value-uses of fields to initialize themselves, e.g.
1270 // foo(foo)
1271 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001272 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001273 for (unsigned i = 0; i < NumArgs; ++i) {
1274 SourceLocation L;
1275 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1276 // FIXME: Return true in the case when other fields are used before being
1277 // uninitialized. For example, let this field be the i'th field. When
1278 // initializing the i'th field, throw a warning if any of the >= i'th
1279 // fields are used, as they are not yet initialized.
1280 // Right now we are only handling the case where the i'th field uses
1281 // itself in its initializer.
1282 Diag(L, diag::warn_field_is_uninit);
1283 }
1284 }
1285
Eli Friedman8e1433b2009-07-29 19:44:27 +00001286 bool HasDependentArg = false;
1287 for (unsigned i = 0; i < NumArgs; i++)
1288 HasDependentArg |= Args[i]->isTypeDependent();
1289
Eli Friedman9255adf2010-07-24 21:19:15 +00001290 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001291 // Can't check initialization for a member of dependent type or when
1292 // any of the arguments are type-dependent expressions.
1293 OwningExprResult Init
1294 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1295 RParenLoc));
1296
1297 // Erase any temporaries within this evaluation context; we're not
1298 // going to track them in the AST, since we'll be rebuilding the
1299 // ASTs during template instantiation.
1300 ExprTemporaries.erase(
1301 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1302 ExprTemporaries.end());
1303
1304 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1305 LParenLoc,
1306 Init.takeAs<Expr>(),
1307 RParenLoc);
1308
Douglas Gregore8381c02008-11-05 04:29:56 +00001309 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001310
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001311 if (Member->isInvalidDecl())
1312 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001313
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001314 // Initialize the member.
1315 InitializedEntity MemberEntity =
1316 InitializedEntity::InitializeMember(Member, 0);
1317 InitializationKind Kind =
1318 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1319
1320 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1321
1322 OwningExprResult MemberInit =
1323 InitSeq.Perform(*this, MemberEntity, Kind,
1324 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1325 if (MemberInit.isInvalid())
1326 return true;
1327
1328 // C++0x [class.base.init]p7:
1329 // The initialization of each base and member constitutes a
1330 // full-expression.
1331 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1332 if (MemberInit.isInvalid())
1333 return true;
1334
1335 // If we are in a dependent context, template instantiation will
1336 // perform this type-checking again. Just save the arguments that we
1337 // received in a ParenListExpr.
1338 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1339 // of the information that we have about the member
1340 // initializer. However, deconstructing the ASTs is a dicey process,
1341 // and this approach is far more likely to get the corner cases right.
1342 if (CurContext->isDependentContext()) {
1343 // Bump the reference count of all of the arguments.
1344 for (unsigned I = 0; I != NumArgs; ++I)
1345 Args[I]->Retain();
1346
1347 OwningExprResult Init
1348 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1349 RParenLoc));
1350 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1351 LParenLoc,
1352 Init.takeAs<Expr>(),
1353 RParenLoc);
1354 }
1355
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001356 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001357 LParenLoc,
1358 MemberInit.takeAs<Expr>(),
1359 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001360}
1361
1362Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001363Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001364 Expr **Args, unsigned NumArgs,
1365 SourceLocation LParenLoc, SourceLocation RParenLoc,
1366 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001367 bool HasDependentArg = false;
1368 for (unsigned i = 0; i < NumArgs; i++)
1369 HasDependentArg |= Args[i]->isTypeDependent();
1370
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001371 SourceLocation BaseLoc
1372 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1373
1374 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1375 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1376 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1377
1378 // C++ [class.base.init]p2:
1379 // [...] Unless the mem-initializer-id names a nonstatic data
1380 // member of the constructor’s class or a direct or virtual base
1381 // of that class, the mem-initializer is ill-formed. A
1382 // mem-initializer-list can initialize a base class using any
1383 // name that denotes that base class type.
1384 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1385
1386 // Check for direct and virtual base classes.
1387 const CXXBaseSpecifier *DirectBaseSpec = 0;
1388 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1389 if (!Dependent) {
1390 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1391 VirtualBaseSpec);
1392
1393 // C++ [base.class.init]p2:
1394 // Unless the mem-initializer-id names a nonstatic data member of the
1395 // constructor's class or a direct or virtual base of that class, the
1396 // mem-initializer is ill-formed.
1397 if (!DirectBaseSpec && !VirtualBaseSpec) {
1398 // If the class has any dependent bases, then it's possible that
1399 // one of those types will resolve to the same type as
1400 // BaseType. Therefore, just treat this as a dependent base
1401 // class initialization. FIXME: Should we try to check the
1402 // initialization anyway? It seems odd.
1403 if (ClassDecl->hasAnyDependentBases())
1404 Dependent = true;
1405 else
1406 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1407 << BaseType << Context.getTypeDeclType(ClassDecl)
1408 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1409 }
1410 }
1411
1412 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001413 // Can't check initialization for a base of dependent type or when
1414 // any of the arguments are type-dependent expressions.
1415 OwningExprResult BaseInit
1416 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1417 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001418
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001419 // Erase any temporaries within this evaluation context; we're not
1420 // going to track them in the AST, since we'll be rebuilding the
1421 // ASTs during template instantiation.
1422 ExprTemporaries.erase(
1423 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1424 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001425
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001426 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001427 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001428 LParenLoc,
1429 BaseInit.takeAs<Expr>(),
1430 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001431 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001432
1433 // C++ [base.class.init]p2:
1434 // If a mem-initializer-id is ambiguous because it designates both
1435 // a direct non-virtual base class and an inherited virtual base
1436 // class, the mem-initializer is ill-formed.
1437 if (DirectBaseSpec && VirtualBaseSpec)
1438 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001439 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001440
1441 CXXBaseSpecifier *BaseSpec
1442 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1443 if (!BaseSpec)
1444 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1445
1446 // Initialize the base.
1447 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001448 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001449 InitializationKind Kind =
1450 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1451
1452 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1453
1454 OwningExprResult BaseInit =
1455 InitSeq.Perform(*this, BaseEntity, Kind,
1456 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1457 if (BaseInit.isInvalid())
1458 return true;
1459
1460 // C++0x [class.base.init]p7:
1461 // The initialization of each base and member constitutes a
1462 // full-expression.
1463 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1464 if (BaseInit.isInvalid())
1465 return true;
1466
1467 // If we are in a dependent context, template instantiation will
1468 // perform this type-checking again. Just save the arguments that we
1469 // received in a ParenListExpr.
1470 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1471 // of the information that we have about the base
1472 // initializer. However, deconstructing the ASTs is a dicey process,
1473 // and this approach is far more likely to get the corner cases right.
1474 if (CurContext->isDependentContext()) {
1475 // Bump the reference count of all of the arguments.
1476 for (unsigned I = 0; I != NumArgs; ++I)
1477 Args[I]->Retain();
1478
1479 OwningExprResult Init
1480 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1481 RParenLoc));
1482 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001483 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001484 LParenLoc,
1485 Init.takeAs<Expr>(),
1486 RParenLoc);
1487 }
1488
1489 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001490 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001491 LParenLoc,
1492 BaseInit.takeAs<Expr>(),
1493 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001494}
1495
Anders Carlsson1b00e242010-04-23 03:10:23 +00001496/// ImplicitInitializerKind - How an implicit base or member initializer should
1497/// initialize its base or member.
1498enum ImplicitInitializerKind {
1499 IIK_Default,
1500 IIK_Copy,
1501 IIK_Move
1502};
1503
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001504static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001505BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001506 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001507 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001508 bool IsInheritedVirtualBase,
1509 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001510 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001511 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1512 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001513
Anders Carlsson1b00e242010-04-23 03:10:23 +00001514 Sema::OwningExprResult BaseInit(SemaRef);
1515
1516 switch (ImplicitInitKind) {
1517 case IIK_Default: {
1518 InitializationKind InitKind
1519 = InitializationKind::CreateDefault(Constructor->getLocation());
1520 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1521 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1522 Sema::MultiExprArg(SemaRef, 0, 0));
1523 break;
1524 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001525
Anders Carlsson1b00e242010-04-23 03:10:23 +00001526 case IIK_Copy: {
1527 ParmVarDecl *Param = Constructor->getParamDecl(0);
1528 QualType ParamType = Param->getType().getNonReferenceType();
1529
1530 Expr *CopyCtorArg =
1531 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregored088b72010-05-03 15:43:53 +00001532 Constructor->getLocation(), ParamType, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001533
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001534 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001535 QualType ArgTy =
1536 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1537 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001538
1539 CXXCastPath BasePath;
1540 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001541 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001542 CastExpr::CK_UncheckedDerivedToBase,
John McCallcf142162010-08-07 06:22:56 +00001543 ImplicitCastExpr::LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001544
Anders Carlsson1b00e242010-04-23 03:10:23 +00001545 InitializationKind InitKind
1546 = InitializationKind::CreateDirect(Constructor->getLocation(),
1547 SourceLocation(), SourceLocation());
1548 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1549 &CopyCtorArg, 1);
1550 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1551 Sema::MultiExprArg(SemaRef,
1552 (void**)&CopyCtorArg, 1));
1553 break;
1554 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001555
Anders Carlsson1b00e242010-04-23 03:10:23 +00001556 case IIK_Move:
1557 assert(false && "Unhandled initializer kind!");
1558 }
1559
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001560 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1561 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001562 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001563
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001564 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001565 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1566 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1567 SourceLocation()),
1568 BaseSpec->isVirtual(),
1569 SourceLocation(),
1570 BaseInit.takeAs<Expr>(),
1571 SourceLocation());
1572
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001573 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001574}
1575
Anders Carlsson3c1db572010-04-23 02:15:47 +00001576static bool
1577BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001578 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001579 FieldDecl *Field,
1580 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001581 if (Field->isInvalidDecl())
1582 return true;
1583
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001584 SourceLocation Loc = Constructor->getLocation();
1585
Anders Carlsson423f5d82010-04-23 16:04:08 +00001586 if (ImplicitInitKind == IIK_Copy) {
1587 ParmVarDecl *Param = Constructor->getParamDecl(0);
1588 QualType ParamType = Param->getType().getNonReferenceType();
1589
1590 Expr *MemberExprBase =
1591 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001592 Loc, ParamType, 0);
1593
1594 // Build a reference to this field within the parameter.
1595 CXXScopeSpec SS;
1596 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1597 Sema::LookupMemberName);
1598 MemberLookup.addDecl(Field, AS_public);
1599 MemberLookup.resolveKind();
1600 Sema::OwningExprResult CopyCtorArg
1601 = SemaRef.BuildMemberReferenceExpr(SemaRef.Owned(MemberExprBase),
1602 ParamType, Loc,
1603 /*IsArrow=*/false,
1604 SS,
1605 /*FirstQualifierInScope=*/0,
1606 MemberLookup,
1607 /*TemplateArgs=*/0);
1608 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001609 return true;
1610
Douglas Gregor94f9a482010-05-05 05:51:00 +00001611 // When the field we are copying is an array, create index variables for
1612 // each dimension of the array. We use these index variables to subscript
1613 // the source array, and other clients (e.g., CodeGen) will perform the
1614 // necessary iteration with these index variables.
1615 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1616 QualType BaseType = Field->getType();
1617 QualType SizeType = SemaRef.Context.getSizeType();
1618 while (const ConstantArrayType *Array
1619 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1620 // Create the iteration variable for this array index.
1621 IdentifierInfo *IterationVarName = 0;
1622 {
1623 llvm::SmallString<8> Str;
1624 llvm::raw_svector_ostream OS(Str);
1625 OS << "__i" << IndexVariables.size();
1626 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1627 }
1628 VarDecl *IterationVar
1629 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1630 IterationVarName, SizeType,
1631 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
1632 VarDecl::None, VarDecl::None);
1633 IndexVariables.push_back(IterationVar);
1634
1635 // Create a reference to the iteration variable.
1636 Sema::OwningExprResult IterationVarRef
1637 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1638 assert(!IterationVarRef.isInvalid() &&
1639 "Reference to invented variable cannot fail!");
1640
1641 // Subscript the array with this iteration variable.
1642 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(move(CopyCtorArg),
1643 Loc,
1644 move(IterationVarRef),
1645 Loc);
1646 if (CopyCtorArg.isInvalid())
1647 return true;
1648
1649 BaseType = Array->getElementType();
1650 }
1651
1652 // Construct the entity that we will be initializing. For an array, this
1653 // will be first element in the array, which may require several levels
1654 // of array-subscript entities.
1655 llvm::SmallVector<InitializedEntity, 4> Entities;
1656 Entities.reserve(1 + IndexVariables.size());
1657 Entities.push_back(InitializedEntity::InitializeMember(Field));
1658 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1659 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1660 0,
1661 Entities.back()));
1662
1663 // Direct-initialize to use the copy constructor.
1664 InitializationKind InitKind =
1665 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1666
1667 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1668 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1669 &CopyCtorArgE, 1);
1670
1671 Sema::OwningExprResult MemberInit
1672 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
1673 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArgE, 1));
1674 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1675 if (MemberInit.isInvalid())
1676 return true;
1677
1678 CXXMemberInit
1679 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1680 MemberInit.takeAs<Expr>(), Loc,
1681 IndexVariables.data(),
1682 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001683 return false;
1684 }
1685
Anders Carlsson423f5d82010-04-23 16:04:08 +00001686 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1687
Anders Carlsson3c1db572010-04-23 02:15:47 +00001688 QualType FieldBaseElementType =
1689 SemaRef.Context.getBaseElementType(Field->getType());
1690
Anders Carlsson3c1db572010-04-23 02:15:47 +00001691 if (FieldBaseElementType->isRecordType()) {
1692 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001693 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001694 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001695
1696 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1697 Sema::OwningExprResult MemberInit =
1698 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1699 Sema::MultiExprArg(SemaRef, 0, 0));
1700 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1701 if (MemberInit.isInvalid())
1702 return true;
1703
1704 CXXMemberInit =
1705 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001706 Field, Loc, Loc,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001707 MemberInit.takeAs<Expr>(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001708 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001709 return false;
1710 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001711
1712 if (FieldBaseElementType->isReferenceType()) {
1713 SemaRef.Diag(Constructor->getLocation(),
1714 diag::err_uninitialized_member_in_ctor)
1715 << (int)Constructor->isImplicit()
1716 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1717 << 0 << Field->getDeclName();
1718 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1719 return true;
1720 }
1721
1722 if (FieldBaseElementType.isConstQualified()) {
1723 SemaRef.Diag(Constructor->getLocation(),
1724 diag::err_uninitialized_member_in_ctor)
1725 << (int)Constructor->isImplicit()
1726 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1727 << 1 << Field->getDeclName();
1728 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1729 return true;
1730 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001731
1732 // Nothing to initialize.
1733 CXXMemberInit = 0;
1734 return false;
1735}
John McCallbc83b3f2010-05-20 23:23:51 +00001736
1737namespace {
1738struct BaseAndFieldInfo {
1739 Sema &S;
1740 CXXConstructorDecl *Ctor;
1741 bool AnyErrorsInInits;
1742 ImplicitInitializerKind IIK;
1743 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1744 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1745
1746 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1747 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1748 // FIXME: Handle implicit move constructors.
1749 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1750 IIK = IIK_Copy;
1751 else
1752 IIK = IIK_Default;
1753 }
1754};
1755}
1756
Chandler Carruth139e9622010-06-30 02:59:29 +00001757static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1758 FieldDecl *Top, FieldDecl *Field,
1759 CXXBaseOrMemberInitializer *Init) {
1760 // If the member doesn't need to be initialized, Init will still be null.
1761 if (!Init)
1762 return;
1763
1764 Info.AllToInit.push_back(Init);
1765 if (Field != Top) {
1766 Init->setMember(Top);
1767 Init->setAnonUnionMember(Field);
1768 }
1769}
1770
John McCallbc83b3f2010-05-20 23:23:51 +00001771static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1772 FieldDecl *Top, FieldDecl *Field) {
1773
Chandler Carruth139e9622010-06-30 02:59:29 +00001774 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallbc83b3f2010-05-20 23:23:51 +00001775 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruth139e9622010-06-30 02:59:29 +00001776 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001777 return false;
1778 }
1779
1780 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1781 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1782 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001783 CXXRecordDecl *FieldClassDecl
1784 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001785
1786 // Even though union members never have non-trivial default
1787 // constructions in C++03, we still build member initializers for aggregate
1788 // record types which can be union members, and C++0x allows non-trivial
1789 // default constructors for union members, so we ensure that only one
1790 // member is initialized for these.
1791 if (FieldClassDecl->isUnion()) {
1792 // First check for an explicit initializer for one field.
1793 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1794 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1795 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1796 RecordFieldInitializer(Info, Top, *FA, Init);
1797
1798 // Once we've initialized a field of an anonymous union, the union
1799 // field in the class is also initialized, so exit immediately.
1800 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001801 } else if ((*FA)->isAnonymousStructOrUnion()) {
1802 if (CollectFieldInitializer(Info, Top, *FA))
1803 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001804 }
1805 }
1806
1807 // Fallthrough and construct a default initializer for the union as
1808 // a whole, which can call its default constructor if such a thing exists
1809 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1810 // behavior going forward with C++0x, when anonymous unions there are
1811 // finalized, we should revisit this.
1812 } else {
1813 // For structs, we simply descend through to initialize all members where
1814 // necessary.
1815 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1816 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1817 if (CollectFieldInitializer(Info, Top, *FA))
1818 return true;
1819 }
1820 }
John McCallbc83b3f2010-05-20 23:23:51 +00001821 }
1822
1823 // Don't try to build an implicit initializer if there were semantic
1824 // errors in any of the initializers (and therefore we might be
1825 // missing some that the user actually wrote).
1826 if (Info.AnyErrorsInInits)
1827 return false;
1828
1829 CXXBaseOrMemberInitializer *Init = 0;
1830 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1831 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001832
Chandler Carruth139e9622010-06-30 02:59:29 +00001833 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001834 return false;
1835}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001836
Eli Friedman9cf6b592009-11-09 19:20:36 +00001837bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001838Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001839 CXXBaseOrMemberInitializer **Initializers,
1840 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001841 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001842 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001843 // Just store the initializers as written, they will be checked during
1844 // instantiation.
1845 if (NumInitializers > 0) {
1846 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1847 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1848 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1849 memcpy(baseOrMemberInitializers, Initializers,
1850 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1851 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1852 }
1853
1854 return false;
1855 }
1856
John McCallbc83b3f2010-05-20 23:23:51 +00001857 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001858
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001859 // We need to build the initializer AST according to order of construction
1860 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001861 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001862 if (!ClassDecl)
1863 return true;
1864
Eli Friedman9cf6b592009-11-09 19:20:36 +00001865 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001866
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001867 for (unsigned i = 0; i < NumInitializers; i++) {
1868 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001869
1870 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001871 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001872 else
John McCallbc83b3f2010-05-20 23:23:51 +00001873 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001874 }
1875
Anders Carlsson43c64af2010-04-21 19:52:01 +00001876 // Keep track of the direct virtual bases.
1877 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1878 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1879 E = ClassDecl->bases_end(); I != E; ++I) {
1880 if (I->isVirtual())
1881 DirectVBases.insert(I);
1882 }
1883
Anders Carlssondb0a9652010-04-02 06:26:44 +00001884 // Push virtual bases before others.
1885 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1886 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1887
1888 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001889 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1890 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001891 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001892 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001893 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001894 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001895 VBase, IsInheritedVirtualBase,
1896 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001897 HadError = true;
1898 continue;
1899 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001900
John McCallbc83b3f2010-05-20 23:23:51 +00001901 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001902 }
1903 }
Mike Stump11289f42009-09-09 15:08:12 +00001904
John McCallbc83b3f2010-05-20 23:23:51 +00001905 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001906 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1907 E = ClassDecl->bases_end(); Base != E; ++Base) {
1908 // Virtuals are in the virtual base list and already constructed.
1909 if (Base->isVirtual())
1910 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001911
Anders Carlssondb0a9652010-04-02 06:26:44 +00001912 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001913 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1914 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001915 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001916 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001917 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001918 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001919 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001920 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001921 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001922 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001923
John McCallbc83b3f2010-05-20 23:23:51 +00001924 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001925 }
1926 }
Mike Stump11289f42009-09-09 15:08:12 +00001927
John McCallbc83b3f2010-05-20 23:23:51 +00001928 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001929 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001930 E = ClassDecl->field_end(); Field != E; ++Field) {
1931 if ((*Field)->getType()->isIncompleteArrayType()) {
1932 assert(ClassDecl->hasFlexibleArrayMember() &&
1933 "Incomplete array type is not valid");
1934 continue;
1935 }
John McCallbc83b3f2010-05-20 23:23:51 +00001936 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001937 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001938 }
Mike Stump11289f42009-09-09 15:08:12 +00001939
John McCallbc83b3f2010-05-20 23:23:51 +00001940 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001941 if (NumInitializers > 0) {
1942 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1943 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1944 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001945 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001946 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001947 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001948
John McCalla6309952010-03-16 21:39:52 +00001949 // Constructors implicitly reference the base and member
1950 // destructors.
1951 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1952 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001953 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001954
1955 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001956}
1957
Eli Friedman952c15d2009-07-21 19:28:10 +00001958static void *GetKeyForTopLevelField(FieldDecl *Field) {
1959 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001960 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001961 if (RT->getDecl()->isAnonymousStructOrUnion())
1962 return static_cast<void *>(RT->getDecl());
1963 }
1964 return static_cast<void *>(Field);
1965}
1966
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001967static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1968 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001969}
1970
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001971static void *GetKeyForMember(ASTContext &Context,
1972 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001973 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001974 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001975 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001976
Eli Friedman952c15d2009-07-21 19:28:10 +00001977 // For fields injected into the class via declaration of an anonymous union,
1978 // use its anonymous union class declaration as the unique key.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001979 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001980
Anders Carlssona942dcd2010-03-30 15:39:27 +00001981 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1982 // data member of the class. Data member used in the initializer list is
1983 // in AnonUnionMember field.
1984 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1985 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001986
John McCall23eebd92010-04-10 09:28:51 +00001987 // If the field is a member of an anonymous struct or union, our key
1988 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001989 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001990 if (RD->isAnonymousStructOrUnion()) {
1991 while (true) {
1992 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1993 if (Parent->isAnonymousStructOrUnion())
1994 RD = Parent;
1995 else
1996 break;
1997 }
1998
Anders Carlsson83ac3122010-03-30 16:19:37 +00001999 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00002000 }
Mike Stump11289f42009-09-09 15:08:12 +00002001
Anders Carlssona942dcd2010-03-30 15:39:27 +00002002 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002003}
2004
Anders Carlssone857b292010-04-02 03:37:03 +00002005static void
2006DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002007 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00002008 CXXBaseOrMemberInitializer **Inits,
2009 unsigned NumInits) {
2010 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002011 return;
Mike Stump11289f42009-09-09 15:08:12 +00002012
John McCallbb7b6582010-04-10 07:37:23 +00002013 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
2014 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002015 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002016
John McCallbb7b6582010-04-10 07:37:23 +00002017 // Build the list of bases and members in the order that they'll
2018 // actually be initialized. The explicit initializers should be in
2019 // this same order but may be missing things.
2020 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002021
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002022 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2023
John McCallbb7b6582010-04-10 07:37:23 +00002024 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002025 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002026 ClassDecl->vbases_begin(),
2027 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002028 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002029
John McCallbb7b6582010-04-10 07:37:23 +00002030 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002031 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002032 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002033 if (Base->isVirtual())
2034 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002035 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002036 }
Mike Stump11289f42009-09-09 15:08:12 +00002037
John McCallbb7b6582010-04-10 07:37:23 +00002038 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002039 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2040 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002041 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002042
John McCallbb7b6582010-04-10 07:37:23 +00002043 unsigned NumIdealInits = IdealInitKeys.size();
2044 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002045
John McCallbb7b6582010-04-10 07:37:23 +00002046 CXXBaseOrMemberInitializer *PrevInit = 0;
2047 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2048 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2049 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2050
2051 // Scan forward to try to find this initializer in the idealized
2052 // initializers list.
2053 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2054 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002055 break;
John McCallbb7b6582010-04-10 07:37:23 +00002056
2057 // If we didn't find this initializer, it must be because we
2058 // scanned past it on a previous iteration. That can only
2059 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002060 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002061 Sema::SemaDiagnosticBuilder D =
2062 SemaRef.Diag(PrevInit->getSourceLocation(),
2063 diag::warn_initializer_out_of_order);
2064
2065 if (PrevInit->isMemberInitializer())
2066 D << 0 << PrevInit->getMember()->getDeclName();
2067 else
2068 D << 1 << PrevInit->getBaseClassInfo()->getType();
2069
2070 if (Init->isMemberInitializer())
2071 D << 0 << Init->getMember()->getDeclName();
2072 else
2073 D << 1 << Init->getBaseClassInfo()->getType();
2074
2075 // Move back to the initializer's location in the ideal list.
2076 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2077 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002078 break;
John McCallbb7b6582010-04-10 07:37:23 +00002079
2080 assert(IdealIndex != NumIdealInits &&
2081 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002082 }
John McCallbb7b6582010-04-10 07:37:23 +00002083
2084 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002085 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002086}
2087
John McCall23eebd92010-04-10 09:28:51 +00002088namespace {
2089bool CheckRedundantInit(Sema &S,
2090 CXXBaseOrMemberInitializer *Init,
2091 CXXBaseOrMemberInitializer *&PrevInit) {
2092 if (!PrevInit) {
2093 PrevInit = Init;
2094 return false;
2095 }
2096
2097 if (FieldDecl *Field = Init->getMember())
2098 S.Diag(Init->getSourceLocation(),
2099 diag::err_multiple_mem_initialization)
2100 << Field->getDeclName()
2101 << Init->getSourceRange();
2102 else {
2103 Type *BaseClass = Init->getBaseClass();
2104 assert(BaseClass && "neither field nor base");
2105 S.Diag(Init->getSourceLocation(),
2106 diag::err_multiple_base_initialization)
2107 << QualType(BaseClass, 0)
2108 << Init->getSourceRange();
2109 }
2110 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2111 << 0 << PrevInit->getSourceRange();
2112
2113 return true;
2114}
2115
2116typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2117typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2118
2119bool CheckRedundantUnionInit(Sema &S,
2120 CXXBaseOrMemberInitializer *Init,
2121 RedundantUnionMap &Unions) {
2122 FieldDecl *Field = Init->getMember();
2123 RecordDecl *Parent = Field->getParent();
2124 if (!Parent->isAnonymousStructOrUnion())
2125 return false;
2126
2127 NamedDecl *Child = Field;
2128 do {
2129 if (Parent->isUnion()) {
2130 UnionEntry &En = Unions[Parent];
2131 if (En.first && En.first != Child) {
2132 S.Diag(Init->getSourceLocation(),
2133 diag::err_multiple_mem_union_initialization)
2134 << Field->getDeclName()
2135 << Init->getSourceRange();
2136 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2137 << 0 << En.second->getSourceRange();
2138 return true;
2139 } else if (!En.first) {
2140 En.first = Child;
2141 En.second = Init;
2142 }
2143 }
2144
2145 Child = Parent;
2146 Parent = cast<RecordDecl>(Parent->getDeclContext());
2147 } while (Parent->isAnonymousStructOrUnion());
2148
2149 return false;
2150}
2151}
2152
Anders Carlssone857b292010-04-02 03:37:03 +00002153/// ActOnMemInitializers - Handle the member initializers for a constructor.
2154void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
2155 SourceLocation ColonLoc,
2156 MemInitTy **meminits, unsigned NumMemInits,
2157 bool AnyErrors) {
2158 if (!ConstructorDecl)
2159 return;
2160
2161 AdjustDeclIfTemplate(ConstructorDecl);
2162
2163 CXXConstructorDecl *Constructor
2164 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2165
2166 if (!Constructor) {
2167 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2168 return;
2169 }
2170
2171 CXXBaseOrMemberInitializer **MemInits =
2172 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002173
2174 // Mapping for the duplicate initializers check.
2175 // For member initializers, this is keyed with a FieldDecl*.
2176 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002177 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002178
2179 // Mapping for the inconsistent anonymous-union initializers check.
2180 RedundantUnionMap MemberUnions;
2181
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002182 bool HadError = false;
2183 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002184 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002185
Abramo Bagnara341d7832010-05-26 18:09:23 +00002186 // Set the source order index.
2187 Init->setSourceOrder(i);
2188
John McCall23eebd92010-04-10 09:28:51 +00002189 if (Init->isMemberInitializer()) {
2190 FieldDecl *Field = Init->getMember();
2191 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2192 CheckRedundantUnionInit(*this, Init, MemberUnions))
2193 HadError = true;
2194 } else {
2195 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2196 if (CheckRedundantInit(*this, Init, Members[Key]))
2197 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002198 }
Anders Carlssone857b292010-04-02 03:37:03 +00002199 }
2200
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002201 if (HadError)
2202 return;
2203
Anders Carlssone857b292010-04-02 03:37:03 +00002204 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002205
2206 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002207}
2208
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002209void
John McCalla6309952010-03-16 21:39:52 +00002210Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2211 CXXRecordDecl *ClassDecl) {
2212 // Ignore dependent contexts.
2213 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002214 return;
John McCall1064d7e2010-03-16 05:22:47 +00002215
2216 // FIXME: all the access-control diagnostics are positioned on the
2217 // field/base declaration. That's probably good; that said, the
2218 // user might reasonably want to know why the destructor is being
2219 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002220
Anders Carlssondee9a302009-11-17 04:44:12 +00002221 // Non-static data members.
2222 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2223 E = ClassDecl->field_end(); I != E; ++I) {
2224 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002225 if (Field->isInvalidDecl())
2226 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002227 QualType FieldType = Context.getBaseElementType(Field->getType());
2228
2229 const RecordType* RT = FieldType->getAs<RecordType>();
2230 if (!RT)
2231 continue;
2232
2233 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2234 if (FieldClassDecl->hasTrivialDestructor())
2235 continue;
2236
Douglas Gregore71edda2010-07-01 22:47:18 +00002237 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002238 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002239 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002240 << Field->getDeclName()
2241 << FieldType);
2242
John McCalla6309952010-03-16 21:39:52 +00002243 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002244 }
2245
John McCall1064d7e2010-03-16 05:22:47 +00002246 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2247
Anders Carlssondee9a302009-11-17 04:44:12 +00002248 // Bases.
2249 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2250 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002251 // Bases are always records in a well-formed non-dependent class.
2252 const RecordType *RT = Base->getType()->getAs<RecordType>();
2253
2254 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002255 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002256 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002257
2258 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002259 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002260 if (BaseClassDecl->hasTrivialDestructor())
2261 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002262
Douglas Gregore71edda2010-07-01 22:47:18 +00002263 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002264
2265 // FIXME: caret should be on the start of the class name
2266 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002267 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002268 << Base->getType()
2269 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002270
John McCalla6309952010-03-16 21:39:52 +00002271 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002272 }
2273
2274 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002275 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2276 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002277
2278 // Bases are always records in a well-formed non-dependent class.
2279 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2280
2281 // Ignore direct virtual bases.
2282 if (DirectVirtualBases.count(RT))
2283 continue;
2284
Anders Carlssondee9a302009-11-17 04:44:12 +00002285 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002286 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002287 if (BaseClassDecl->hasTrivialDestructor())
2288 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002289
Douglas Gregore71edda2010-07-01 22:47:18 +00002290 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002291 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002292 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002293 << VBase->getType());
2294
John McCalla6309952010-03-16 21:39:52 +00002295 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002296 }
2297}
2298
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00002299void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002300 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002301 return;
Mike Stump11289f42009-09-09 15:08:12 +00002302
Mike Stump11289f42009-09-09 15:08:12 +00002303 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002304 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002305 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002306}
2307
Mike Stump11289f42009-09-09 15:08:12 +00002308bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002309 unsigned DiagID, AbstractDiagSelID SelID,
2310 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002311 if (SelID == -1)
2312 return RequireNonAbstractType(Loc, T,
2313 PDiag(DiagID), CurrentRD);
2314 else
2315 return RequireNonAbstractType(Loc, T,
2316 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002317}
2318
Anders Carlssoneabf7702009-08-27 00:13:57 +00002319bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2320 const PartialDiagnostic &PD,
2321 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002322 if (!getLangOptions().CPlusPlus)
2323 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002324
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002325 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002326 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002327 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002328
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002329 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002330 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002331 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002332 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002333
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002334 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002335 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002336 }
Mike Stump11289f42009-09-09 15:08:12 +00002337
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002338 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002339 if (!RT)
2340 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002341
John McCall67da35c2010-02-04 22:26:26 +00002342 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002343
Anders Carlssonb57738b2009-03-24 17:23:42 +00002344 if (CurrentRD && CurrentRD != RD)
2345 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002346
John McCall67da35c2010-02-04 22:26:26 +00002347 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002348 if (!RD->getDefinition())
John McCall67da35c2010-02-04 22:26:26 +00002349 return false;
2350
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002351 if (!RD->isAbstract())
2352 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002353
Anders Carlssoneabf7702009-08-27 00:13:57 +00002354 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002355
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002356 // Check if we've already emitted the list of pure virtual functions for this
2357 // class.
2358 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2359 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002360
Douglas Gregor4165bd62010-03-23 23:47:56 +00002361 CXXFinalOverriderMap FinalOverriders;
2362 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002363
Anders Carlssona2f74f32010-06-03 01:00:02 +00002364 // Keep a set of seen pure methods so we won't diagnose the same method
2365 // more than once.
2366 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2367
Douglas Gregor4165bd62010-03-23 23:47:56 +00002368 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2369 MEnd = FinalOverriders.end();
2370 M != MEnd;
2371 ++M) {
2372 for (OverridingMethods::iterator SO = M->second.begin(),
2373 SOEnd = M->second.end();
2374 SO != SOEnd; ++SO) {
2375 // C++ [class.abstract]p4:
2376 // A class is abstract if it contains or inherits at least one
2377 // pure virtual function for which the final overrider is pure
2378 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002379
Douglas Gregor4165bd62010-03-23 23:47:56 +00002380 //
2381 if (SO->second.size() != 1)
2382 continue;
2383
2384 if (!SO->second.front().Method->isPure())
2385 continue;
2386
Anders Carlssona2f74f32010-06-03 01:00:02 +00002387 if (!SeenPureMethods.insert(SO->second.front().Method))
2388 continue;
2389
Douglas Gregor4165bd62010-03-23 23:47:56 +00002390 Diag(SO->second.front().Method->getLocation(),
2391 diag::note_pure_virtual_function)
2392 << SO->second.front().Method->getDeclName();
2393 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002394 }
2395
2396 if (!PureVirtualClassDiagSet)
2397 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2398 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002399
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002400 return true;
2401}
2402
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002403namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00002404 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002405 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2406 Sema &SemaRef;
2407 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00002408
Anders Carlssonb57738b2009-03-24 17:23:42 +00002409 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002410 bool Invalid = false;
2411
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002412 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2413 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002414 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002415
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002416 return Invalid;
2417 }
Mike Stump11289f42009-09-09 15:08:12 +00002418
Anders Carlssonb57738b2009-03-24 17:23:42 +00002419 public:
2420 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2421 : SemaRef(SemaRef), AbstractClass(ac) {
2422 Visit(SemaRef.Context.getTranslationUnitDecl());
2423 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002424
Anders Carlssonb57738b2009-03-24 17:23:42 +00002425 bool VisitFunctionDecl(const FunctionDecl *FD) {
2426 if (FD->isThisDeclarationADefinition()) {
2427 // No need to do the check if we're in a definition, because it requires
2428 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00002429 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00002430 return VisitDeclContext(FD);
2431 }
Mike Stump11289f42009-09-09 15:08:12 +00002432
Anders Carlssonb57738b2009-03-24 17:23:42 +00002433 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00002434 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00002435 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00002436 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2437 diag::err_abstract_type_in_decl,
2438 Sema::AbstractReturnType,
2439 AbstractClass);
2440
Mike Stump11289f42009-09-09 15:08:12 +00002441 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00002442 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002443 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002444 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002445 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002446 VD->getOriginalType(),
2447 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002448 Sema::AbstractParamType,
2449 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002450 }
2451
2452 return Invalid;
2453 }
Mike Stump11289f42009-09-09 15:08:12 +00002454
Anders Carlssonb57738b2009-03-24 17:23:42 +00002455 bool VisitDecl(const Decl* D) {
2456 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2457 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00002458
Anders Carlssonb57738b2009-03-24 17:23:42 +00002459 return false;
2460 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002461 };
2462}
2463
Douglas Gregorc99f1552009-12-03 18:33:45 +00002464/// \brief Perform semantic checks on a class definition that has been
2465/// completing, introducing implicitly-declared members, checking for
2466/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002467void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregorc99f1552009-12-03 18:33:45 +00002468 if (!Record || Record->isInvalidDecl())
2469 return;
2470
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002471 if (!Record->isDependentType())
Douglas Gregor0be31a22010-07-02 17:43:08 +00002472 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00002473
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002474 if (Record->isInvalidDecl())
2475 return;
2476
John McCall2cb94162010-01-28 07:38:46 +00002477 // Set access bits correctly on the directly-declared conversions.
2478 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2479 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2480 Convs->setAccess(I, (*I)->getAccess());
2481
Douglas Gregor4165bd62010-03-23 23:47:56 +00002482 // Determine whether we need to check for final overriders. We do
2483 // this either when there are virtual base classes (in which case we
2484 // may end up finding multiple final overriders for a given virtual
2485 // function) or any of the base classes is abstract (in which case
2486 // we might detect that this class is abstract).
2487 bool CheckFinalOverriders = false;
2488 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2489 !Record->isDependentType()) {
2490 if (Record->getNumVBases())
2491 CheckFinalOverriders = true;
2492 else if (!Record->isAbstract()) {
2493 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2494 BEnd = Record->bases_end();
2495 B != BEnd; ++B) {
2496 CXXRecordDecl *BaseDecl
2497 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2498 if (BaseDecl->isAbstract()) {
2499 CheckFinalOverriders = true;
2500 break;
2501 }
2502 }
2503 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002504 }
2505
Douglas Gregor4165bd62010-03-23 23:47:56 +00002506 if (CheckFinalOverriders) {
2507 CXXFinalOverriderMap FinalOverriders;
2508 Record->getFinalOverriders(FinalOverriders);
2509
2510 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2511 MEnd = FinalOverriders.end();
2512 M != MEnd; ++M) {
2513 for (OverridingMethods::iterator SO = M->second.begin(),
2514 SOEnd = M->second.end();
2515 SO != SOEnd; ++SO) {
2516 assert(SO->second.size() > 0 &&
2517 "All virtual functions have overridding virtual functions");
2518 if (SO->second.size() == 1) {
2519 // C++ [class.abstract]p4:
2520 // A class is abstract if it contains or inherits at least one
2521 // pure virtual function for which the final overrider is pure
2522 // virtual.
2523 if (SO->second.front().Method->isPure())
2524 Record->setAbstract(true);
2525 continue;
2526 }
2527
2528 // C++ [class.virtual]p2:
2529 // In a derived class, if a virtual member function of a base
2530 // class subobject has more than one final overrider the
2531 // program is ill-formed.
2532 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2533 << (NamedDecl *)M->first << Record;
2534 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2535 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2536 OMEnd = SO->second.end();
2537 OM != OMEnd; ++OM)
2538 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2539 << (NamedDecl *)M->first << OM->Method->getParent();
2540
2541 Record->setInvalidDecl();
2542 }
2543 }
2544 }
2545
2546 if (Record->isAbstract() && !Record->isInvalidDecl())
Douglas Gregorc99f1552009-12-03 18:33:45 +00002547 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor454a5b62010-04-15 00:00:53 +00002548
2549 // If this is not an aggregate type and has no user-declared constructor,
2550 // complain about any non-static data members of reference or const scalar
2551 // type, since they will never get initializers.
2552 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2553 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2554 bool Complained = false;
2555 for (RecordDecl::field_iterator F = Record->field_begin(),
2556 FEnd = Record->field_end();
2557 F != FEnd; ++F) {
2558 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002559 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002560 if (!Complained) {
2561 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2562 << Record->getTagKind() << Record;
2563 Complained = true;
2564 }
2565
2566 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2567 << F->getType()->isReferenceType()
2568 << F->getDeclName();
2569 }
2570 }
2571 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002572
2573 if (Record->isDynamicClass())
2574 DynamicClasses.push_back(Record);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002575}
2576
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002577void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002578 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002579 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002580 SourceLocation RBrac,
2581 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002582 if (!TagDecl)
2583 return;
Mike Stump11289f42009-09-09 15:08:12 +00002584
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002585 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002586
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002587 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002588 (DeclPtrTy*)FieldCollector->getCurFields(),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002589 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002590
Douglas Gregor0be31a22010-07-02 17:43:08 +00002591 CheckCompletedCXXClass(
2592 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002593}
2594
Douglas Gregor95755162010-07-01 05:10:53 +00002595namespace {
2596 /// \brief Helper class that collects exception specifications for
2597 /// implicitly-declared special member functions.
2598 class ImplicitExceptionSpecification {
2599 ASTContext &Context;
2600 bool AllowsAllExceptions;
2601 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2602 llvm::SmallVector<QualType, 4> Exceptions;
2603
2604 public:
2605 explicit ImplicitExceptionSpecification(ASTContext &Context)
2606 : Context(Context), AllowsAllExceptions(false) { }
2607
2608 /// \brief Whether the special member function should have any
2609 /// exception specification at all.
2610 bool hasExceptionSpecification() const {
2611 return !AllowsAllExceptions;
2612 }
2613
2614 /// \brief Whether the special member function should have a
2615 /// throw(...) exception specification (a Microsoft extension).
2616 bool hasAnyExceptionSpecification() const {
2617 return false;
2618 }
2619
2620 /// \brief The number of exceptions in the exception specification.
2621 unsigned size() const { return Exceptions.size(); }
2622
2623 /// \brief The set of exceptions in the exception specification.
2624 const QualType *data() const { return Exceptions.data(); }
2625
2626 /// \brief Note that
2627 void CalledDecl(CXXMethodDecl *Method) {
2628 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002629 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002630 return;
2631
2632 const FunctionProtoType *Proto
2633 = Method->getType()->getAs<FunctionProtoType>();
2634
2635 // If this function can throw any exceptions, make a note of that.
2636 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2637 AllowsAllExceptions = true;
2638 ExceptionsSeen.clear();
2639 Exceptions.clear();
2640 return;
2641 }
2642
2643 // Record the exceptions in this function's exception specification.
2644 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2645 EEnd = Proto->exception_end();
2646 E != EEnd; ++E)
2647 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2648 Exceptions.push_back(*E);
2649 }
2650 };
2651}
2652
2653
Douglas Gregor05379422008-11-03 17:51:48 +00002654/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2655/// special functions, such as the default constructor, copy
2656/// constructor, or destructor, to the given C++ class (C++
2657/// [special]p1). This routine can only be executed just before the
2658/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002659void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002660 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002661 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002662
Douglas Gregor54be3392010-07-01 17:57:27 +00002663 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002664 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002665
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002666 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2667 ++ASTContext::NumImplicitCopyAssignmentOperators;
2668
2669 // If we have a dynamic class, then the copy assignment operator may be
2670 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2671 // it shows up in the right place in the vtable and that we diagnose
2672 // problems with the implicit exception specification.
2673 if (ClassDecl->isDynamicClass())
2674 DeclareImplicitCopyAssignment(ClassDecl);
2675 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002676
Douglas Gregor7454c562010-07-02 20:37:36 +00002677 if (!ClassDecl->hasUserDeclaredDestructor()) {
2678 ++ASTContext::NumImplicitDestructors;
2679
2680 // If we have a dynamic class, then the destructor may be virtual, so we
2681 // have to declare the destructor immediately. This ensures that, e.g., it
2682 // shows up in the right place in the vtable and that we diagnose problems
2683 // with the implicit exception specification.
2684 if (ClassDecl->isDynamicClass())
2685 DeclareImplicitDestructor(ClassDecl);
2686 }
Douglas Gregor05379422008-11-03 17:51:48 +00002687}
2688
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002689void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002690 Decl *D = TemplateD.getAs<Decl>();
2691 if (!D)
2692 return;
2693
2694 TemplateParameterList *Params = 0;
2695 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2696 Params = Template->getTemplateParameters();
2697 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2698 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2699 Params = PartialSpec->getTemplateParameters();
2700 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002701 return;
2702
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002703 for (TemplateParameterList::iterator Param = Params->begin(),
2704 ParamEnd = Params->end();
2705 Param != ParamEnd; ++Param) {
2706 NamedDecl *Named = cast<NamedDecl>(*Param);
2707 if (Named->getDeclName()) {
2708 S->AddDecl(DeclPtrTy::make(Named));
2709 IdResolver.AddDecl(Named);
2710 }
2711 }
2712}
2713
John McCall6df5fef2009-12-19 10:49:29 +00002714void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2715 if (!RecordD) return;
2716 AdjustDeclIfTemplate(RecordD);
2717 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2718 PushDeclContext(S, Record);
2719}
2720
2721void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2722 if (!RecordD) return;
2723 PopDeclContext();
2724}
2725
Douglas Gregor4d87df52008-12-16 21:30:33 +00002726/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2727/// parsing a top-level (non-nested) C++ class, and we are now
2728/// parsing those parts of the given Method declaration that could
2729/// not be parsed earlier (C++ [class.mem]p2), such as default
2730/// arguments. This action should enter the scope of the given
2731/// Method declaration as if we had just parsed the qualified method
2732/// name. However, it should not bring the parameters into scope;
2733/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002734void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002735}
2736
2737/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2738/// C++ method declaration. We're (re-)introducing the given
2739/// function parameter into scope for use in parsing later parts of
2740/// the method declaration. For example, we could see an
2741/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002742void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002743 if (!ParamD)
2744 return;
Mike Stump11289f42009-09-09 15:08:12 +00002745
Chris Lattner83f095c2009-03-28 19:18:32 +00002746 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002747
2748 // If this parameter has an unparsed default argument, clear it out
2749 // to make way for the parsed default argument.
2750 if (Param->hasUnparsedDefaultArg())
2751 Param->setDefaultArg(0);
2752
Chris Lattner83f095c2009-03-28 19:18:32 +00002753 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002754 if (Param->getDeclName())
2755 IdResolver.AddDecl(Param);
2756}
2757
2758/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2759/// processing the delayed method declaration for Method. The method
2760/// declaration is now considered finished. There may be a separate
2761/// ActOnStartOfFunctionDef action later (not necessarily
2762/// immediately!) for this method, if it was also defined inside the
2763/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002764void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002765 if (!MethodD)
2766 return;
Mike Stump11289f42009-09-09 15:08:12 +00002767
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002768 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002769
Chris Lattner83f095c2009-03-28 19:18:32 +00002770 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002771
2772 // Now that we have our default arguments, check the constructor
2773 // again. It could produce additional diagnostics or affect whether
2774 // the class has implicitly-declared destructors, among other
2775 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002776 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2777 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002778
2779 // Check the default arguments, which we may have added.
2780 if (!Method->isInvalidDecl())
2781 CheckCXXDefaultArguments(Method);
2782}
2783
Douglas Gregor831c93f2008-11-05 20:51:48 +00002784/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002785/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002786/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002787/// emit diagnostics and set the invalid bit to true. In any case, the type
2788/// will be updated to reflect a well-formed type for the constructor and
2789/// returned.
2790QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2791 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002792 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002793
2794 // C++ [class.ctor]p3:
2795 // A constructor shall not be virtual (10.3) or static (9.4). A
2796 // constructor can be invoked for a const, volatile or const
2797 // volatile object. A constructor shall not be declared const,
2798 // volatile, or const volatile (9.3.2).
2799 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002800 if (!D.isInvalidType())
2801 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2802 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2803 << SourceRange(D.getIdentifierLoc());
2804 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002805 }
2806 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002807 if (!D.isInvalidType())
2808 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2809 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2810 << SourceRange(D.getIdentifierLoc());
2811 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002812 SC = FunctionDecl::None;
2813 }
Mike Stump11289f42009-09-09 15:08:12 +00002814
Chris Lattner38378bf2009-04-25 08:28:21 +00002815 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2816 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002817 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002818 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2819 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002820 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002821 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2822 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002823 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002824 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2825 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002826 }
Mike Stump11289f42009-09-09 15:08:12 +00002827
Douglas Gregor831c93f2008-11-05 20:51:48 +00002828 // Rebuild the function type "R" without any type qualifiers (in
2829 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002830 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002831 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002832 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2833 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002834 Proto->isVariadic(), 0,
2835 Proto->hasExceptionSpec(),
2836 Proto->hasAnyExceptionSpec(),
2837 Proto->getNumExceptions(),
2838 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002839 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002840}
2841
Douglas Gregor4d87df52008-12-16 21:30:33 +00002842/// CheckConstructor - Checks a fully-formed constructor for
2843/// well-formedness, issuing any diagnostics required. Returns true if
2844/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002845void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002846 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002847 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2848 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002849 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002850
2851 // C++ [class.copy]p3:
2852 // A declaration of a constructor for a class X is ill-formed if
2853 // its first parameter is of type (optionally cv-qualified) X and
2854 // either there are no other parameters or else all other
2855 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002856 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002857 ((Constructor->getNumParams() == 1) ||
2858 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002859 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2860 Constructor->getTemplateSpecializationKind()
2861 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002862 QualType ParamType = Constructor->getParamDecl(0)->getType();
2863 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2864 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002865 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002866 const char *ConstRef
2867 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2868 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002869 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002870 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002871
2872 // FIXME: Rather that making the constructor invalid, we should endeavor
2873 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002874 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002875 }
2876 }
Mike Stump11289f42009-09-09 15:08:12 +00002877
John McCall43314ab2010-04-13 07:45:41 +00002878 // Notify the class that we've added a constructor. In principle we
2879 // don't need to do this for out-of-line declarations; in practice
2880 // we only instantiate the most recent declaration of a method, so
2881 // we have to call this for everything but friends.
2882 if (!Constructor->getFriendObjectKind())
2883 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002884}
2885
John McCalldeb646e2010-08-04 01:04:25 +00002886/// CheckDestructor - Checks a fully-formed destructor definition for
2887/// well-formedness, issuing any diagnostics required. Returns true
2888/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002889bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002890 CXXRecordDecl *RD = Destructor->getParent();
2891
2892 if (Destructor->isVirtual()) {
2893 SourceLocation Loc;
2894
2895 if (!Destructor->isImplicit())
2896 Loc = Destructor->getLocation();
2897 else
2898 Loc = RD->getLocation();
2899
2900 // If we have a virtual destructor, look up the deallocation function
2901 FunctionDecl *OperatorDelete = 0;
2902 DeclarationName Name =
2903 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002904 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002905 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00002906
2907 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00002908
2909 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002910 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002911
2912 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002913}
2914
Mike Stump11289f42009-09-09 15:08:12 +00002915static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002916FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2917 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2918 FTI.ArgInfo[0].Param &&
2919 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2920}
2921
Douglas Gregor831c93f2008-11-05 20:51:48 +00002922/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2923/// the well-formednes of the destructor declarator @p D with type @p
2924/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002925/// emit diagnostics and set the declarator to invalid. Even if this happens,
2926/// will be updated to reflect a well-formed type for the destructor and
2927/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00002928QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
Chris Lattner38378bf2009-04-25 08:28:21 +00002929 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002930 // C++ [class.dtor]p1:
2931 // [...] A typedef-name that names a class is a class-name
2932 // (7.1.3); however, a typedef-name that names a class shall not
2933 // be used as the identifier in the declarator for a destructor
2934 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002935 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00002936 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00002937 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002938 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002939
2940 // C++ [class.dtor]p2:
2941 // A destructor is used to destroy objects of its class type. A
2942 // destructor takes no parameters, and no return type can be
2943 // specified for it (not even void). The address of a destructor
2944 // shall not be taken. A destructor shall not be static. A
2945 // destructor can be invoked for a const, volatile or const
2946 // volatile object. A destructor shall not be declared const,
2947 // volatile or const volatile (9.3.2).
2948 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002949 if (!D.isInvalidType())
2950 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2951 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00002952 << SourceRange(D.getIdentifierLoc())
2953 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2954
Douglas Gregor831c93f2008-11-05 20:51:48 +00002955 SC = FunctionDecl::None;
2956 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002957 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002958 // Destructors don't have return types, but the parser will
2959 // happily parse something like:
2960 //
2961 // class X {
2962 // float ~X();
2963 // };
2964 //
2965 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002966 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2967 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2968 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002969 }
Mike Stump11289f42009-09-09 15:08:12 +00002970
Chris Lattner38378bf2009-04-25 08:28:21 +00002971 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2972 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002973 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002974 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2975 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002976 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002977 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2978 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002979 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002980 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2981 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002982 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002983 }
2984
2985 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002986 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002987 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2988
2989 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002990 FTI.freeArgs();
2991 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002992 }
2993
Mike Stump11289f42009-09-09 15:08:12 +00002994 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002995 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002996 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002997 D.setInvalidType();
2998 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002999
3000 // Rebuild the function type "R" without any type qualifiers or
3001 // parameters (in case any of the errors above fired) and with
3002 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003003 // types.
3004 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3005 if (!Proto)
3006 return QualType();
3007
Douglas Gregor36c569f2010-02-21 22:15:06 +00003008 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregor95755162010-07-01 05:10:53 +00003009 Proto->hasExceptionSpec(),
3010 Proto->hasAnyExceptionSpec(),
3011 Proto->getNumExceptions(),
3012 Proto->exception_begin(),
3013 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003014}
3015
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003016/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3017/// well-formednes of the conversion function declarator @p D with
3018/// type @p R. If there are any errors in the declarator, this routine
3019/// will emit diagnostics and return true. Otherwise, it will return
3020/// false. Either way, the type @p R will be updated to reflect a
3021/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003022void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003023 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003024 // C++ [class.conv.fct]p1:
3025 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003026 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003027 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003028 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003029 if (!D.isInvalidType())
3030 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3031 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3032 << SourceRange(D.getIdentifierLoc());
3033 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003034 SC = FunctionDecl::None;
3035 }
John McCall212fa2e2010-04-13 00:04:31 +00003036
3037 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3038
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003039 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003040 // Conversion functions don't have return types, but the parser will
3041 // happily parse something like:
3042 //
3043 // class X {
3044 // float operator bool();
3045 // };
3046 //
3047 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003048 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3049 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3050 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003051 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003052 }
3053
John McCall212fa2e2010-04-13 00:04:31 +00003054 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3055
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003056 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003057 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003058 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3059
3060 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003061 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003062 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003063 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003064 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003065 D.setInvalidType();
3066 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003067
John McCall212fa2e2010-04-13 00:04:31 +00003068 // Diagnose "&operator bool()" and other such nonsense. This
3069 // is actually a gcc extension which we don't support.
3070 if (Proto->getResultType() != ConvType) {
3071 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3072 << Proto->getResultType();
3073 D.setInvalidType();
3074 ConvType = Proto->getResultType();
3075 }
3076
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003077 // C++ [class.conv.fct]p4:
3078 // The conversion-type-id shall not represent a function type nor
3079 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003080 if (ConvType->isArrayType()) {
3081 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3082 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003083 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003084 } else if (ConvType->isFunctionType()) {
3085 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3086 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003087 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003088 }
3089
3090 // Rebuild the function type "R" without any parameters (in case any
3091 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003092 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003093 if (D.isInvalidType()) {
3094 R = Context.getFunctionType(ConvType, 0, 0, false,
3095 Proto->getTypeQuals(),
3096 Proto->hasExceptionSpec(),
3097 Proto->hasAnyExceptionSpec(),
3098 Proto->getNumExceptions(),
3099 Proto->exception_begin(),
3100 Proto->getExtInfo());
3101 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003102
Douglas Gregor5fb53972009-01-14 15:45:31 +00003103 // C++0x explicit conversion operators.
3104 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003105 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003106 diag::warn_explicit_conversion_functions)
3107 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003108}
3109
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003110/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3111/// the declaration of the given C++ conversion function. This routine
3112/// is responsible for recording the conversion function in the C++
3113/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00003114Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003115 assert(Conversion && "Expected to receive a conversion function declaration");
3116
Douglas Gregor4287b372008-12-12 08:25:50 +00003117 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003118
3119 // Make sure we aren't redeclaring the conversion function.
3120 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003121
3122 // C++ [class.conv.fct]p1:
3123 // [...] A conversion function is never used to convert a
3124 // (possibly cv-qualified) object to the (possibly cv-qualified)
3125 // same object type (or a reference to it), to a (possibly
3126 // cv-qualified) base class of that type (or a reference to it),
3127 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003128 // FIXME: Suppress this warning if the conversion function ends up being a
3129 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003130 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003131 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003132 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003133 ConvType = ConvTypeRef->getPointeeType();
3134 if (ConvType->isRecordType()) {
3135 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3136 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003137 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003138 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003139 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003140 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003141 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003142 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003143 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003144 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003145 }
3146
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003147 if (Conversion->getPrimaryTemplate()) {
3148 // ignore specializations
3149 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump11289f42009-09-09 15:08:12 +00003150 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor133bc742010-01-11 18:53:25 +00003151 = Conversion->getDescribedFunctionTemplate()) {
3152 if (ClassDecl->replaceConversion(
3153 ConversionTemplate->getPreviousDeclaration(),
3154 ConversionTemplate))
3155 return DeclPtrTy::make(ConversionTemplate);
3156 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3157 Conversion))
John McCalld14a8642009-11-21 08:51:07 +00003158 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00003159 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00003160 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003161 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003162 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003163 else
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003164 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003165
Chris Lattner83f095c2009-03-28 19:18:32 +00003166 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003167}
3168
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003169//===----------------------------------------------------------------------===//
3170// Namespace Handling
3171//===----------------------------------------------------------------------===//
3172
3173/// ActOnStartNamespaceDef - This is called at the start of a namespace
3174/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00003175Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3176 SourceLocation IdentLoc,
3177 IdentifierInfo *II,
Anders Carlssona7bcade2010-02-07 01:09:23 +00003178 SourceLocation LBrace,
3179 AttributeList *AttrList) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003180 NamespaceDecl *Namespc =
3181 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3182 Namespc->setLBracLoc(LBrace);
3183
3184 Scope *DeclRegionScope = NamespcScope->getParent();
3185
Anders Carlssona7bcade2010-02-07 01:09:23 +00003186 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3187
Eli Friedman570024a2010-08-05 06:57:20 +00003188 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
3189 PushPragmaVisibility(attr->getVisibility());
3190
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003191 if (II) {
3192 // C++ [namespace.def]p2:
3193 // The identifier in an original-namespace-definition shall not have been
3194 // previously defined in the declarative region in which the
3195 // original-namespace-definition appears. The identifier in an
3196 // original-namespace-definition is the name of the namespace. Subsequently
3197 // in that declarative region, it is treated as an original-namespace-name.
3198
John McCall9f3059a2009-10-09 21:13:30 +00003199 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003200 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003201 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00003202
Douglas Gregor91f84212008-12-11 16:49:14 +00003203 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3204 // This is an extended namespace definition.
3205 // Attach this namespace decl to the chain of extended namespace
3206 // definitions.
3207 OrigNS->setNextNamespace(Namespc);
3208 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003209
Mike Stump11289f42009-09-09 15:08:12 +00003210 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003211 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003212 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00003213 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003214 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003215 } else if (PrevDecl) {
3216 // This is an invalid name redefinition.
3217 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3218 << Namespc->getDeclName();
3219 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3220 Namespc->setInvalidDecl();
3221 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003222 } else if (II->isStr("std") &&
3223 CurContext->getLookupContext()->isTranslationUnit()) {
3224 // This is the first "real" definition of the namespace "std", so update
3225 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003226 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003227 // We had already defined a dummy namespace "std". Link this new
3228 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003229 StdNS->setNextNamespace(Namespc);
3230 StdNS->setLocation(IdentLoc);
3231 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003232 }
3233
3234 // Make our StdNamespace cache point at the first real definition of the
3235 // "std" namespace.
3236 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003237 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003238
3239 PushOnScopeChains(Namespc, DeclRegionScope);
3240 } else {
John McCall4fa53422009-10-01 00:25:31 +00003241 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003242 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003243
3244 // Link the anonymous namespace into its parent.
3245 NamespaceDecl *PrevDecl;
3246 DeclContext *Parent = CurContext->getLookupContext();
3247 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3248 PrevDecl = TU->getAnonymousNamespace();
3249 TU->setAnonymousNamespace(Namespc);
3250 } else {
3251 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3252 PrevDecl = ND->getAnonymousNamespace();
3253 ND->setAnonymousNamespace(Namespc);
3254 }
3255
3256 // Link the anonymous namespace with its previous declaration.
3257 if (PrevDecl) {
3258 assert(PrevDecl->isAnonymousNamespace());
3259 assert(!PrevDecl->getNextNamespace());
3260 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3261 PrevDecl->setNextNamespace(Namespc);
3262 }
John McCall4fa53422009-10-01 00:25:31 +00003263
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003264 CurContext->addDecl(Namespc);
3265
John McCall4fa53422009-10-01 00:25:31 +00003266 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3267 // behaves as if it were replaced by
3268 // namespace unique { /* empty body */ }
3269 // using namespace unique;
3270 // namespace unique { namespace-body }
3271 // where all occurrences of 'unique' in a translation unit are
3272 // replaced by the same identifier and this identifier differs
3273 // from all other identifiers in the entire program.
3274
3275 // We just create the namespace with an empty name and then add an
3276 // implicit using declaration, just like the standard suggests.
3277 //
3278 // CodeGen enforces the "universally unique" aspect by giving all
3279 // declarations semantically contained within an anonymous
3280 // namespace internal linkage.
3281
John McCall0db42252009-12-16 02:06:49 +00003282 if (!PrevDecl) {
3283 UsingDirectiveDecl* UD
3284 = UsingDirectiveDecl::Create(Context, CurContext,
3285 /* 'using' */ LBrace,
3286 /* 'namespace' */ SourceLocation(),
3287 /* qualifier */ SourceRange(),
3288 /* NNS */ NULL,
3289 /* identifier */ SourceLocation(),
3290 Namespc,
3291 /* Ancestor */ CurContext);
3292 UD->setImplicit();
3293 CurContext->addDecl(UD);
3294 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003295 }
3296
3297 // Although we could have an invalid decl (i.e. the namespace name is a
3298 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003299 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3300 // for the namespace has the declarations that showed up in that particular
3301 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003302 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00003303 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003304}
3305
Sebastian Redla6602e92009-11-23 15:34:23 +00003306/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3307/// is a namespace alias, returns the namespace it points to.
3308static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3309 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3310 return AD->getNamespace();
3311 return dyn_cast_or_null<NamespaceDecl>(D);
3312}
3313
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003314/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3315/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00003316void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3317 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003318 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3319 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3320 Namespc->setRBracLoc(RBrace);
3321 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003322 if (Namespc->hasAttr<VisibilityAttr>())
3323 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003324}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003325
Douglas Gregorcdf87022010-06-29 17:53:46 +00003326/// \brief Retrieve the special "std" namespace, which may require us to
3327/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003328NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003329 if (!StdNamespace) {
3330 // The "std" namespace has not yet been defined, so build one implicitly.
3331 StdNamespace = NamespaceDecl::Create(Context,
3332 Context.getTranslationUnitDecl(),
3333 SourceLocation(),
3334 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003335 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003336 }
3337
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003338 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003339}
3340
Chris Lattner83f095c2009-03-28 19:18:32 +00003341Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3342 SourceLocation UsingLoc,
3343 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003344 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003345 SourceLocation IdentLoc,
3346 IdentifierInfo *NamespcName,
3347 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003348 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3349 assert(NamespcName && "Invalid NamespcName.");
3350 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003351 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003352
Douglas Gregor889ceb72009-02-03 19:21:40 +00003353 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003354 NestedNameSpecifier *Qualifier = 0;
3355 if (SS.isSet())
3356 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3357
Douglas Gregor34074322009-01-14 22:20:51 +00003358 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003359 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3360 LookupParsedName(R, S, &SS);
3361 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003362 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00003363
Douglas Gregorcdf87022010-06-29 17:53:46 +00003364 if (R.empty()) {
3365 // Allow "using namespace std;" or "using namespace ::std;" even if
3366 // "std" hasn't been defined yet, for GCC compatibility.
3367 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3368 NamespcName->isStr("std")) {
3369 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003370 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003371 R.resolveKind();
3372 }
3373 // Otherwise, attempt typo correction.
3374 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3375 CTC_NoKeywords, 0)) {
3376 if (R.getAsSingle<NamespaceDecl>() ||
3377 R.getAsSingle<NamespaceAliasDecl>()) {
3378 if (DeclContext *DC = computeDeclContext(SS, false))
3379 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3380 << NamespcName << DC << Corrected << SS.getRange()
3381 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3382 else
3383 Diag(IdentLoc, diag::err_using_directive_suggest)
3384 << NamespcName << Corrected
3385 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3386 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3387 << Corrected;
3388
3389 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003390 } else {
3391 R.clear();
3392 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003393 }
3394 }
3395 }
3396
John McCall9f3059a2009-10-09 21:13:30 +00003397 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003398 NamedDecl *Named = R.getFoundDecl();
3399 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3400 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003401 // C++ [namespace.udir]p1:
3402 // A using-directive specifies that the names in the nominated
3403 // namespace can be used in the scope in which the
3404 // using-directive appears after the using-directive. During
3405 // unqualified name lookup (3.4.1), the names appear as if they
3406 // were declared in the nearest enclosing namespace which
3407 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003408 // namespace. [Note: in this context, "contains" means "contains
3409 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003410
3411 // Find enclosing context containing both using-directive and
3412 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003413 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003414 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3415 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3416 CommonAncestor = CommonAncestor->getParent();
3417
Sebastian Redla6602e92009-11-23 15:34:23 +00003418 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003419 SS.getRange(),
3420 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003421 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003422 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003423 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003424 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003425 }
3426
Douglas Gregor889ceb72009-02-03 19:21:40 +00003427 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003428 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00003429 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003430}
3431
3432void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3433 // If scope has associated entity, then using directive is at namespace
3434 // or translation unit scope. We add UsingDirectiveDecls, into
3435 // it's lookup structure.
3436 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003437 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003438 else
3439 // Otherwise it is block-sope. using-directives will affect lookup
3440 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003441 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00003442}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003443
Douglas Gregorfec52632009-06-20 00:51:54 +00003444
3445Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003446 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003447 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003448 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003449 CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003450 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003451 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003452 bool IsTypeName,
3453 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003454 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003455
Douglas Gregor220f4272009-11-04 16:30:06 +00003456 switch (Name.getKind()) {
3457 case UnqualifiedId::IK_Identifier:
3458 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003459 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003460 case UnqualifiedId::IK_ConversionFunctionId:
3461 break;
3462
3463 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003464 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003465 // C++0x inherited constructors.
3466 if (getLangOptions().CPlusPlus0x) break;
3467
Douglas Gregor220f4272009-11-04 16:30:06 +00003468 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3469 << SS.getRange();
3470 return DeclPtrTy();
3471
3472 case UnqualifiedId::IK_DestructorName:
3473 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3474 << SS.getRange();
3475 return DeclPtrTy();
3476
3477 case UnqualifiedId::IK_TemplateId:
3478 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3479 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3480 return DeclPtrTy();
3481 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003482
3483 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3484 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003485 if (!TargetName)
3486 return DeclPtrTy();
3487
John McCalla0097262009-12-11 02:10:03 +00003488 // Warn about using declarations.
3489 // TODO: store that the declaration was written without 'using' and
3490 // talk about access decls instead of using decls in the
3491 // diagnostics.
3492 if (!HasUsingKeyword) {
3493 UsingLoc = Name.getSourceRange().getBegin();
3494
3495 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003496 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003497 }
3498
John McCall3f746822009-11-17 05:59:44 +00003499 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003500 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003501 /* IsInstantiation */ false,
3502 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003503 if (UD)
3504 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003505
Anders Carlsson696a3f12009-08-28 05:40:36 +00003506 return DeclPtrTy::make(UD);
3507}
3508
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003509/// \brief Determine whether a using declaration considers the given
3510/// declarations as "equivalent", e.g., if they are redeclarations of
3511/// the same entity or are both typedefs of the same type.
3512static bool
3513IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3514 bool &SuppressRedeclaration) {
3515 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3516 SuppressRedeclaration = false;
3517 return true;
3518 }
3519
3520 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3521 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3522 SuppressRedeclaration = true;
3523 return Context.hasSameType(TD1->getUnderlyingType(),
3524 TD2->getUnderlyingType());
3525 }
3526
3527 return false;
3528}
3529
3530
John McCall84d87672009-12-10 09:41:52 +00003531/// Determines whether to create a using shadow decl for a particular
3532/// decl, given the set of decls existing prior to this using lookup.
3533bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3534 const LookupResult &Previous) {
3535 // Diagnose finding a decl which is not from a base class of the
3536 // current class. We do this now because there are cases where this
3537 // function will silently decide not to build a shadow decl, which
3538 // will pre-empt further diagnostics.
3539 //
3540 // We don't need to do this in C++0x because we do the check once on
3541 // the qualifier.
3542 //
3543 // FIXME: diagnose the following if we care enough:
3544 // struct A { int foo; };
3545 // struct B : A { using A::foo; };
3546 // template <class T> struct C : A {};
3547 // template <class T> struct D : C<T> { using B::foo; } // <---
3548 // This is invalid (during instantiation) in C++03 because B::foo
3549 // resolves to the using decl in B, which is not a base class of D<T>.
3550 // We can't diagnose it immediately because C<T> is an unknown
3551 // specialization. The UsingShadowDecl in D<T> then points directly
3552 // to A::foo, which will look well-formed when we instantiate.
3553 // The right solution is to not collapse the shadow-decl chain.
3554 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3555 DeclContext *OrigDC = Orig->getDeclContext();
3556
3557 // Handle enums and anonymous structs.
3558 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3559 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3560 while (OrigRec->isAnonymousStructOrUnion())
3561 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3562
3563 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3564 if (OrigDC == CurContext) {
3565 Diag(Using->getLocation(),
3566 diag::err_using_decl_nested_name_specifier_is_current_class)
3567 << Using->getNestedNameRange();
3568 Diag(Orig->getLocation(), diag::note_using_decl_target);
3569 return true;
3570 }
3571
3572 Diag(Using->getNestedNameRange().getBegin(),
3573 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3574 << Using->getTargetNestedNameDecl()
3575 << cast<CXXRecordDecl>(CurContext)
3576 << Using->getNestedNameRange();
3577 Diag(Orig->getLocation(), diag::note_using_decl_target);
3578 return true;
3579 }
3580 }
3581
3582 if (Previous.empty()) return false;
3583
3584 NamedDecl *Target = Orig;
3585 if (isa<UsingShadowDecl>(Target))
3586 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3587
John McCalla17e83e2009-12-11 02:33:26 +00003588 // If the target happens to be one of the previous declarations, we
3589 // don't have a conflict.
3590 //
3591 // FIXME: but we might be increasing its access, in which case we
3592 // should redeclare it.
3593 NamedDecl *NonTag = 0, *Tag = 0;
3594 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3595 I != E; ++I) {
3596 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003597 bool Result;
3598 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3599 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003600
3601 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3602 }
3603
John McCall84d87672009-12-10 09:41:52 +00003604 if (Target->isFunctionOrFunctionTemplate()) {
3605 FunctionDecl *FD;
3606 if (isa<FunctionTemplateDecl>(Target))
3607 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3608 else
3609 FD = cast<FunctionDecl>(Target);
3610
3611 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003612 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003613 case Ovl_Overload:
3614 return false;
3615
3616 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003617 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003618 break;
3619
3620 // We found a decl with the exact signature.
3621 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003622 // If we're in a record, we want to hide the target, so we
3623 // return true (without a diagnostic) to tell the caller not to
3624 // build a shadow decl.
3625 if (CurContext->isRecord())
3626 return true;
3627
3628 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003629 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003630 break;
3631 }
3632
3633 Diag(Target->getLocation(), diag::note_using_decl_target);
3634 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3635 return true;
3636 }
3637
3638 // Target is not a function.
3639
John McCall84d87672009-12-10 09:41:52 +00003640 if (isa<TagDecl>(Target)) {
3641 // No conflict between a tag and a non-tag.
3642 if (!Tag) return false;
3643
John McCalle29c5cd2009-12-10 19:51:03 +00003644 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003645 Diag(Target->getLocation(), diag::note_using_decl_target);
3646 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3647 return true;
3648 }
3649
3650 // No conflict between a tag and a non-tag.
3651 if (!NonTag) return false;
3652
John McCalle29c5cd2009-12-10 19:51:03 +00003653 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003654 Diag(Target->getLocation(), diag::note_using_decl_target);
3655 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3656 return true;
3657}
3658
John McCall3f746822009-11-17 05:59:44 +00003659/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003660UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003661 UsingDecl *UD,
3662 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003663
3664 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003665 NamedDecl *Target = Orig;
3666 if (isa<UsingShadowDecl>(Target)) {
3667 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3668 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003669 }
3670
3671 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003672 = UsingShadowDecl::Create(Context, CurContext,
3673 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003674 UD->addShadowDecl(Shadow);
3675
3676 if (S)
John McCall3969e302009-12-08 07:46:18 +00003677 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003678 else
John McCall3969e302009-12-08 07:46:18 +00003679 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003680 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003681
John McCallda4458e2010-03-31 01:36:47 +00003682 // Register it as a conversion if appropriate.
3683 if (Shadow->getDeclName().getNameKind()
3684 == DeclarationName::CXXConversionFunctionName)
3685 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3686
John McCall3969e302009-12-08 07:46:18 +00003687 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3688 Shadow->setInvalidDecl();
3689
John McCall84d87672009-12-10 09:41:52 +00003690 return Shadow;
3691}
John McCall3969e302009-12-08 07:46:18 +00003692
John McCall84d87672009-12-10 09:41:52 +00003693/// Hides a using shadow declaration. This is required by the current
3694/// using-decl implementation when a resolvable using declaration in a
3695/// class is followed by a declaration which would hide or override
3696/// one or more of the using decl's targets; for example:
3697///
3698/// struct Base { void foo(int); };
3699/// struct Derived : Base {
3700/// using Base::foo;
3701/// void foo(int);
3702/// };
3703///
3704/// The governing language is C++03 [namespace.udecl]p12:
3705///
3706/// When a using-declaration brings names from a base class into a
3707/// derived class scope, member functions in the derived class
3708/// override and/or hide member functions with the same name and
3709/// parameter types in a base class (rather than conflicting).
3710///
3711/// There are two ways to implement this:
3712/// (1) optimistically create shadow decls when they're not hidden
3713/// by existing declarations, or
3714/// (2) don't create any shadow decls (or at least don't make them
3715/// visible) until we've fully parsed/instantiated the class.
3716/// The problem with (1) is that we might have to retroactively remove
3717/// a shadow decl, which requires several O(n) operations because the
3718/// decl structures are (very reasonably) not designed for removal.
3719/// (2) avoids this but is very fiddly and phase-dependent.
3720void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003721 if (Shadow->getDeclName().getNameKind() ==
3722 DeclarationName::CXXConversionFunctionName)
3723 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3724
John McCall84d87672009-12-10 09:41:52 +00003725 // Remove it from the DeclContext...
3726 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003727
John McCall84d87672009-12-10 09:41:52 +00003728 // ...and the scope, if applicable...
3729 if (S) {
3730 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3731 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003732 }
3733
John McCall84d87672009-12-10 09:41:52 +00003734 // ...and the using decl.
3735 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3736
3737 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003738 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003739}
3740
John McCalle61f2ba2009-11-18 02:36:19 +00003741/// Builds a using declaration.
3742///
3743/// \param IsInstantiation - Whether this call arises from an
3744/// instantiation of an unresolved using declaration. We treat
3745/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003746NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3747 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003748 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003749 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003750 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003751 bool IsInstantiation,
3752 bool IsTypeName,
3753 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003754 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003755 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003756 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003757
Anders Carlssonf038fc22009-08-28 05:49:21 +00003758 // FIXME: We ignore attributes for now.
3759 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003760
Anders Carlsson59140b32009-08-28 03:16:11 +00003761 if (SS.isEmpty()) {
3762 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003763 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003764 }
Mike Stump11289f42009-09-09 15:08:12 +00003765
John McCall84d87672009-12-10 09:41:52 +00003766 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003767 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003768 ForRedeclaration);
3769 Previous.setHideTags(false);
3770 if (S) {
3771 LookupName(Previous, S);
3772
3773 // It is really dumb that we have to do this.
3774 LookupResult::Filter F = Previous.makeFilter();
3775 while (F.hasNext()) {
3776 NamedDecl *D = F.next();
3777 if (!isDeclInScope(D, CurContext, S))
3778 F.erase();
3779 }
3780 F.done();
3781 } else {
3782 assert(IsInstantiation && "no scope in non-instantiation");
3783 assert(CurContext->isRecord() && "scope not record in instantiation");
3784 LookupQualifiedName(Previous, CurContext);
3785 }
3786
Mike Stump11289f42009-09-09 15:08:12 +00003787 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003788 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3789
John McCall84d87672009-12-10 09:41:52 +00003790 // Check for invalid redeclarations.
3791 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3792 return 0;
3793
3794 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003795 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3796 return 0;
3797
John McCall84c16cf2009-11-12 03:15:40 +00003798 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003799 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003800 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003801 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003802 // FIXME: not all declaration name kinds are legal here
3803 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3804 UsingLoc, TypenameLoc,
3805 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003806 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003807 } else {
3808 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003809 UsingLoc, SS.getRange(),
3810 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003811 }
John McCallb96ec562009-12-04 22:46:56 +00003812 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003813 D = UsingDecl::Create(Context, CurContext,
3814 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003815 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003816 }
John McCallb96ec562009-12-04 22:46:56 +00003817 D->setAccess(AS);
3818 CurContext->addDecl(D);
3819
3820 if (!LookupContext) return D;
3821 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003822
John McCall0b66eb32010-05-01 00:40:08 +00003823 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003824 UD->setInvalidDecl();
3825 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003826 }
3827
John McCall3969e302009-12-08 07:46:18 +00003828 // Look up the target name.
3829
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003830 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003831
John McCall3969e302009-12-08 07:46:18 +00003832 // Unlike most lookups, we don't always want to hide tag
3833 // declarations: tag names are visible through the using declaration
3834 // even if hidden by ordinary names, *except* in a dependent context
3835 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003836 if (!IsInstantiation)
3837 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003838
John McCall27b18f82009-11-17 02:14:36 +00003839 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003840
John McCall9f3059a2009-10-09 21:13:30 +00003841 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003842 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003843 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003844 UD->setInvalidDecl();
3845 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003846 }
3847
John McCallb96ec562009-12-04 22:46:56 +00003848 if (R.isAmbiguous()) {
3849 UD->setInvalidDecl();
3850 return UD;
3851 }
Mike Stump11289f42009-09-09 15:08:12 +00003852
John McCalle61f2ba2009-11-18 02:36:19 +00003853 if (IsTypeName) {
3854 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003855 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003856 Diag(IdentLoc, diag::err_using_typename_non_type);
3857 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3858 Diag((*I)->getUnderlyingDecl()->getLocation(),
3859 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003860 UD->setInvalidDecl();
3861 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003862 }
3863 } else {
3864 // If we asked for a non-typename and we got a type, error out,
3865 // but only if this is an instantiation of an unresolved using
3866 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003867 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003868 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3869 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003870 UD->setInvalidDecl();
3871 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003872 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003873 }
3874
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003875 // C++0x N2914 [namespace.udecl]p6:
3876 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003877 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003878 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3879 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003880 UD->setInvalidDecl();
3881 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003882 }
Mike Stump11289f42009-09-09 15:08:12 +00003883
John McCall84d87672009-12-10 09:41:52 +00003884 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3885 if (!CheckUsingShadowDecl(UD, *I, Previous))
3886 BuildUsingShadowDecl(S, UD, *I);
3887 }
John McCall3f746822009-11-17 05:59:44 +00003888
3889 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003890}
3891
John McCall84d87672009-12-10 09:41:52 +00003892/// Checks that the given using declaration is not an invalid
3893/// redeclaration. Note that this is checking only for the using decl
3894/// itself, not for any ill-formedness among the UsingShadowDecls.
3895bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3896 bool isTypeName,
3897 const CXXScopeSpec &SS,
3898 SourceLocation NameLoc,
3899 const LookupResult &Prev) {
3900 // C++03 [namespace.udecl]p8:
3901 // C++0x [namespace.udecl]p10:
3902 // A using-declaration is a declaration and can therefore be used
3903 // repeatedly where (and only where) multiple declarations are
3904 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00003905 //
3906 // That's in non-member contexts.
3907 if (!CurContext->getLookupContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00003908 return false;
3909
3910 NestedNameSpecifier *Qual
3911 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3912
3913 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3914 NamedDecl *D = *I;
3915
3916 bool DTypename;
3917 NestedNameSpecifier *DQual;
3918 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3919 DTypename = UD->isTypeName();
3920 DQual = UD->getTargetNestedNameDecl();
3921 } else if (UnresolvedUsingValueDecl *UD
3922 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3923 DTypename = false;
3924 DQual = UD->getTargetNestedNameSpecifier();
3925 } else if (UnresolvedUsingTypenameDecl *UD
3926 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3927 DTypename = true;
3928 DQual = UD->getTargetNestedNameSpecifier();
3929 } else continue;
3930
3931 // using decls differ if one says 'typename' and the other doesn't.
3932 // FIXME: non-dependent using decls?
3933 if (isTypeName != DTypename) continue;
3934
3935 // using decls differ if they name different scopes (but note that
3936 // template instantiation can cause this check to trigger when it
3937 // didn't before instantiation).
3938 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3939 Context.getCanonicalNestedNameSpecifier(DQual))
3940 continue;
3941
3942 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003943 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003944 return true;
3945 }
3946
3947 return false;
3948}
3949
John McCall3969e302009-12-08 07:46:18 +00003950
John McCallb96ec562009-12-04 22:46:56 +00003951/// Checks that the given nested-name qualifier used in a using decl
3952/// in the current context is appropriately related to the current
3953/// scope. If an error is found, diagnoses it and returns true.
3954bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3955 const CXXScopeSpec &SS,
3956 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003957 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003958
John McCall3969e302009-12-08 07:46:18 +00003959 if (!CurContext->isRecord()) {
3960 // C++03 [namespace.udecl]p3:
3961 // C++0x [namespace.udecl]p8:
3962 // A using-declaration for a class member shall be a member-declaration.
3963
3964 // If we weren't able to compute a valid scope, it must be a
3965 // dependent class scope.
3966 if (!NamedContext || NamedContext->isRecord()) {
3967 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3968 << SS.getRange();
3969 return true;
3970 }
3971
3972 // Otherwise, everything is known to be fine.
3973 return false;
3974 }
3975
3976 // The current scope is a record.
3977
3978 // If the named context is dependent, we can't decide much.
3979 if (!NamedContext) {
3980 // FIXME: in C++0x, we can diagnose if we can prove that the
3981 // nested-name-specifier does not refer to a base class, which is
3982 // still possible in some cases.
3983
3984 // Otherwise we have to conservatively report that things might be
3985 // okay.
3986 return false;
3987 }
3988
3989 if (!NamedContext->isRecord()) {
3990 // Ideally this would point at the last name in the specifier,
3991 // but we don't have that level of source info.
3992 Diag(SS.getRange().getBegin(),
3993 diag::err_using_decl_nested_name_specifier_is_not_class)
3994 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3995 return true;
3996 }
3997
3998 if (getLangOptions().CPlusPlus0x) {
3999 // C++0x [namespace.udecl]p3:
4000 // In a using-declaration used as a member-declaration, the
4001 // nested-name-specifier shall name a base class of the class
4002 // being defined.
4003
4004 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4005 cast<CXXRecordDecl>(NamedContext))) {
4006 if (CurContext == NamedContext) {
4007 Diag(NameLoc,
4008 diag::err_using_decl_nested_name_specifier_is_current_class)
4009 << SS.getRange();
4010 return true;
4011 }
4012
4013 Diag(SS.getRange().getBegin(),
4014 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4015 << (NestedNameSpecifier*) SS.getScopeRep()
4016 << cast<CXXRecordDecl>(CurContext)
4017 << SS.getRange();
4018 return true;
4019 }
4020
4021 return false;
4022 }
4023
4024 // C++03 [namespace.udecl]p4:
4025 // A using-declaration used as a member-declaration shall refer
4026 // to a member of a base class of the class being defined [etc.].
4027
4028 // Salient point: SS doesn't have to name a base class as long as
4029 // lookup only finds members from base classes. Therefore we can
4030 // diagnose here only if we can prove that that can't happen,
4031 // i.e. if the class hierarchies provably don't intersect.
4032
4033 // TODO: it would be nice if "definitely valid" results were cached
4034 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4035 // need to be repeated.
4036
4037 struct UserData {
4038 llvm::DenseSet<const CXXRecordDecl*> Bases;
4039
4040 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4041 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4042 Data->Bases.insert(Base);
4043 return true;
4044 }
4045
4046 bool hasDependentBases(const CXXRecordDecl *Class) {
4047 return !Class->forallBases(collect, this);
4048 }
4049
4050 /// Returns true if the base is dependent or is one of the
4051 /// accumulated base classes.
4052 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4053 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4054 return !Data->Bases.count(Base);
4055 }
4056
4057 bool mightShareBases(const CXXRecordDecl *Class) {
4058 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4059 }
4060 };
4061
4062 UserData Data;
4063
4064 // Returns false if we find a dependent base.
4065 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4066 return false;
4067
4068 // Returns false if the class has a dependent base or if it or one
4069 // of its bases is present in the base set of the current context.
4070 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4071 return false;
4072
4073 Diag(SS.getRange().getBegin(),
4074 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4075 << (NestedNameSpecifier*) SS.getScopeRep()
4076 << cast<CXXRecordDecl>(CurContext)
4077 << SS.getRange();
4078
4079 return true;
John McCallb96ec562009-12-04 22:46:56 +00004080}
4081
Mike Stump11289f42009-09-09 15:08:12 +00004082Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004083 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004084 SourceLocation AliasLoc,
4085 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004086 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004087 SourceLocation IdentLoc,
4088 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004089
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004090 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004091 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4092 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004093
Anders Carlssondca83c42009-03-28 06:23:46 +00004094 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004095 NamedDecl *PrevDecl
4096 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4097 ForRedeclaration);
4098 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4099 PrevDecl = 0;
4100
4101 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004102 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004103 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004104 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004105 // FIXME: At some point, we'll want to create the (redundant)
4106 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004107 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004108 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004109 return DeclPtrTy();
4110 }
Mike Stump11289f42009-09-09 15:08:12 +00004111
Anders Carlssondca83c42009-03-28 06:23:46 +00004112 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4113 diag::err_redefinition_different_kind;
4114 Diag(AliasLoc, DiagID) << Alias;
4115 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00004116 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00004117 }
4118
John McCall27b18f82009-11-17 02:14:36 +00004119 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00004120 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00004121
John McCall9f3059a2009-10-09 21:13:30 +00004122 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004123 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4124 CTC_NoKeywords, 0)) {
4125 if (R.getAsSingle<NamespaceDecl>() ||
4126 R.getAsSingle<NamespaceAliasDecl>()) {
4127 if (DeclContext *DC = computeDeclContext(SS, false))
4128 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4129 << Ident << DC << Corrected << SS.getRange()
4130 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4131 else
4132 Diag(IdentLoc, diag::err_using_directive_suggest)
4133 << Ident << Corrected
4134 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4135
4136 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4137 << Corrected;
4138
4139 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004140 } else {
4141 R.clear();
4142 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004143 }
4144 }
4145
4146 if (R.empty()) {
4147 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
4148 return DeclPtrTy();
4149 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004150 }
Mike Stump11289f42009-09-09 15:08:12 +00004151
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004152 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004153 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4154 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004155 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004156 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004157
John McCalld8d0d432010-02-16 06:53:13 +00004158 PushOnScopeChains(AliasDecl, S);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00004159 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00004160}
4161
Douglas Gregora57478e2010-05-01 15:04:51 +00004162namespace {
4163 /// \brief Scoped object used to handle the state changes required in Sema
4164 /// to implicitly define the body of a C++ member function;
4165 class ImplicitlyDefinedFunctionScope {
4166 Sema &S;
4167 DeclContext *PreviousContext;
4168
4169 public:
4170 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4171 : S(S), PreviousContext(S.CurContext)
4172 {
4173 S.CurContext = Method;
4174 S.PushFunctionScope();
4175 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4176 }
4177
4178 ~ImplicitlyDefinedFunctionScope() {
4179 S.PopExpressionEvaluationContext();
4180 S.PopFunctionOrBlockScope();
4181 S.CurContext = PreviousContext;
4182 }
4183 };
4184}
4185
Douglas Gregor0be31a22010-07-02 17:43:08 +00004186CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4187 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004188 // C++ [class.ctor]p5:
4189 // A default constructor for a class X is a constructor of class X
4190 // that can be called without an argument. If there is no
4191 // user-declared constructor for class X, a default constructor is
4192 // implicitly declared. An implicitly-declared default constructor
4193 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004194 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4195 "Should not build implicit default constructor!");
4196
Douglas Gregor6d880b12010-07-01 22:31:05 +00004197 // C++ [except.spec]p14:
4198 // An implicitly declared special member function (Clause 12) shall have an
4199 // exception-specification. [...]
4200 ImplicitExceptionSpecification ExceptSpec(Context);
4201
4202 // Direct base-class destructors.
4203 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4204 BEnd = ClassDecl->bases_end();
4205 B != BEnd; ++B) {
4206 if (B->isVirtual()) // Handled below.
4207 continue;
4208
Douglas Gregor9672f922010-07-03 00:47:00 +00004209 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4210 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4211 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4212 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4213 else if (CXXConstructorDecl *Constructor
4214 = BaseClassDecl->getDefaultConstructor())
Douglas Gregor6d880b12010-07-01 22:31:05 +00004215 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004216 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004217 }
4218
4219 // Virtual base-class destructors.
4220 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4221 BEnd = ClassDecl->vbases_end();
4222 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004223 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4224 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4225 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4226 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4227 else if (CXXConstructorDecl *Constructor
4228 = BaseClassDecl->getDefaultConstructor())
Douglas Gregor6d880b12010-07-01 22:31:05 +00004229 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004230 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004231 }
4232
4233 // Field destructors.
4234 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4235 FEnd = ClassDecl->field_end();
4236 F != FEnd; ++F) {
4237 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004238 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4239 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4240 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4241 ExceptSpec.CalledDecl(
4242 DeclareImplicitDefaultConstructor(FieldClassDecl));
4243 else if (CXXConstructorDecl *Constructor
4244 = FieldClassDecl->getDefaultConstructor())
Douglas Gregor6d880b12010-07-01 22:31:05 +00004245 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004246 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004247 }
4248
4249
4250 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004251 CanQualType ClassType
4252 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4253 DeclarationName Name
4254 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004255 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004256 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004257 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004258 Context.getFunctionType(Context.VoidTy,
4259 0, 0, false, 0,
Douglas Gregor6d880b12010-07-01 22:31:05 +00004260 ExceptSpec.hasExceptionSpecification(),
4261 ExceptSpec.hasAnyExceptionSpecification(),
4262 ExceptSpec.size(),
4263 ExceptSpec.data(),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004264 FunctionType::ExtInfo()),
4265 /*TInfo=*/0,
4266 /*isExplicit=*/false,
4267 /*isInline=*/true,
4268 /*isImplicitlyDeclared=*/true);
4269 DefaultCon->setAccess(AS_public);
4270 DefaultCon->setImplicit();
4271 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004272
4273 // Note that we have declared this constructor.
4274 ClassDecl->setDeclaredDefaultConstructor(true);
4275 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4276
Douglas Gregor0be31a22010-07-02 17:43:08 +00004277 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004278 PushOnScopeChains(DefaultCon, S, false);
4279 ClassDecl->addDecl(DefaultCon);
4280
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004281 return DefaultCon;
4282}
4283
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004284void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4285 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004286 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004287 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004288 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004289
Anders Carlsson423f5d82010-04-23 16:04:08 +00004290 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004291 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004292
Douglas Gregora57478e2010-05-01 15:04:51 +00004293 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00004294 ErrorTrap Trap(*this);
4295 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4296 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004297 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004298 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004299 Constructor->setInvalidDecl();
4300 } else {
4301 Constructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004302 MarkVTableUsed(CurrentLocation, ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004303 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004304}
4305
Douglas Gregor0be31a22010-07-02 17:43:08 +00004306CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004307 // C++ [class.dtor]p2:
4308 // If a class has no user-declared destructor, a destructor is
4309 // declared implicitly. An implicitly-declared destructor is an
4310 // inline public member of its class.
4311
4312 // C++ [except.spec]p14:
4313 // An implicitly declared special member function (Clause 12) shall have
4314 // an exception-specification.
4315 ImplicitExceptionSpecification ExceptSpec(Context);
4316
4317 // Direct base-class destructors.
4318 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4319 BEnd = ClassDecl->bases_end();
4320 B != BEnd; ++B) {
4321 if (B->isVirtual()) // Handled below.
4322 continue;
4323
4324 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4325 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004326 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004327 }
4328
4329 // Virtual base-class destructors.
4330 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4331 BEnd = ClassDecl->vbases_end();
4332 B != BEnd; ++B) {
4333 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4334 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004335 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004336 }
4337
4338 // Field destructors.
4339 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4340 FEnd = ClassDecl->field_end();
4341 F != FEnd; ++F) {
4342 if (const RecordType *RecordTy
4343 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4344 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004345 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004346 }
4347
Douglas Gregor7454c562010-07-02 20:37:36 +00004348 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00004349 QualType Ty = Context.getFunctionType(Context.VoidTy,
4350 0, 0, false, 0,
4351 ExceptSpec.hasExceptionSpecification(),
4352 ExceptSpec.hasAnyExceptionSpecification(),
4353 ExceptSpec.size(),
4354 ExceptSpec.data(),
4355 FunctionType::ExtInfo());
4356
4357 CanQualType ClassType
4358 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4359 DeclarationName Name
4360 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004361 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004362 CXXDestructorDecl *Destructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004363 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty,
Douglas Gregorf1203042010-07-01 19:09:28 +00004364 /*isInline=*/true,
4365 /*isImplicitlyDeclared=*/true);
4366 Destructor->setAccess(AS_public);
4367 Destructor->setImplicit();
4368 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004369
4370 // Note that we have declared this destructor.
4371 ClassDecl->setDeclaredDestructor(true);
4372 ++ASTContext::NumImplicitDestructorsDeclared;
4373
4374 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004375 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004376 PushOnScopeChains(Destructor, S, false);
4377 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004378
4379 // This could be uniqued if it ever proves significant.
4380 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4381
4382 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004383
Douglas Gregorf1203042010-07-01 19:09:28 +00004384 return Destructor;
4385}
4386
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004387void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004388 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004389 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004390 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004391 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004392 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004393
Douglas Gregor54818f02010-05-12 16:39:35 +00004394 if (Destructor->isInvalidDecl())
4395 return;
4396
Douglas Gregora57478e2010-05-01 15:04:51 +00004397 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004398
Douglas Gregor54818f02010-05-12 16:39:35 +00004399 ErrorTrap Trap(*this);
John McCalla6309952010-03-16 21:39:52 +00004400 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4401 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004402
Douglas Gregor54818f02010-05-12 16:39:35 +00004403 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004404 Diag(CurrentLocation, diag::note_member_synthesized_at)
4405 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4406
4407 Destructor->setInvalidDecl();
4408 return;
4409 }
4410
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004411 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004412 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004413}
4414
Douglas Gregorb139cd52010-05-01 20:49:11 +00004415/// \brief Builds a statement that copies the given entity from \p From to
4416/// \c To.
4417///
4418/// This routine is used to copy the members of a class with an
4419/// implicitly-declared copy assignment operator. When the entities being
4420/// copied are arrays, this routine builds for loops to copy them.
4421///
4422/// \param S The Sema object used for type-checking.
4423///
4424/// \param Loc The location where the implicit copy is being generated.
4425///
4426/// \param T The type of the expressions being copied. Both expressions must
4427/// have this type.
4428///
4429/// \param To The expression we are copying to.
4430///
4431/// \param From The expression we are copying from.
4432///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004433/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4434/// Otherwise, it's a non-static member subobject.
4435///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004436/// \param Depth Internal parameter recording the depth of the recursion.
4437///
4438/// \returns A statement or a loop that copies the expressions.
4439static Sema::OwningStmtResult
4440BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4441 Sema::OwningExprResult To, Sema::OwningExprResult From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004442 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004443 typedef Sema::OwningStmtResult OwningStmtResult;
4444 typedef Sema::OwningExprResult OwningExprResult;
4445
4446 // C++0x [class.copy]p30:
4447 // Each subobject is assigned in the manner appropriate to its type:
4448 //
4449 // - if the subobject is of class type, the copy assignment operator
4450 // for the class is used (as if by explicit qualification; that is,
4451 // ignoring any possible virtual overriding functions in more derived
4452 // classes);
4453 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4454 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4455
4456 // Look for operator=.
4457 DeclarationName Name
4458 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4459 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4460 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4461
4462 // Filter out any result that isn't a copy-assignment operator.
4463 LookupResult::Filter F = OpLookup.makeFilter();
4464 while (F.hasNext()) {
4465 NamedDecl *D = F.next();
4466 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4467 if (Method->isCopyAssignmentOperator())
4468 continue;
4469
4470 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004471 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004472 F.done();
4473
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004474 // Suppress the protected check (C++ [class.protected]) for each of the
4475 // assignment operators we found. This strange dance is required when
4476 // we're assigning via a base classes's copy-assignment operator. To
4477 // ensure that we're getting the right base class subobject (without
4478 // ambiguities), we need to cast "this" to that subobject type; to
4479 // ensure that we don't go through the virtual call mechanism, we need
4480 // to qualify the operator= name with the base class (see below). However,
4481 // this means that if the base class has a protected copy assignment
4482 // operator, the protected member access check will fail. So, we
4483 // rewrite "protected" access to "public" access in this case, since we
4484 // know by construction that we're calling from a derived class.
4485 if (CopyingBaseSubobject) {
4486 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4487 L != LEnd; ++L) {
4488 if (L.getAccess() == AS_protected)
4489 L.setAccess(AS_public);
4490 }
4491 }
4492
Douglas Gregorb139cd52010-05-01 20:49:11 +00004493 // Create the nested-name-specifier that will be used to qualify the
4494 // reference to operator=; this is required to suppress the virtual
4495 // call mechanism.
4496 CXXScopeSpec SS;
4497 SS.setRange(Loc);
4498 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4499 T.getTypePtr()));
4500
4501 // Create the reference to operator=.
4502 OwningExprResult OpEqualRef
4503 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4504 /*FirstQualifierInScope=*/0, OpLookup,
4505 /*TemplateArgs=*/0,
4506 /*SuppressQualifierCheck=*/true);
4507 if (OpEqualRef.isInvalid())
4508 return S.StmtError();
4509
4510 // Build the call to the assignment operator.
4511 Expr *FromE = From.takeAs<Expr>();
4512 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4513 OpEqualRef.takeAs<Expr>(),
4514 Loc, &FromE, 1, 0, Loc);
4515 if (Call.isInvalid())
4516 return S.StmtError();
4517
4518 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004519 }
John McCallab8c2732010-03-16 06:11:48 +00004520
Douglas Gregorb139cd52010-05-01 20:49:11 +00004521 // - if the subobject is of scalar type, the built-in assignment
4522 // operator is used.
4523 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4524 if (!ArrayTy) {
4525 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4526 BinaryOperator::Assign,
4527 To.takeAs<Expr>(),
4528 From.takeAs<Expr>());
4529 if (Assignment.isInvalid())
4530 return S.StmtError();
4531
4532 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004533 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004534
4535 // - if the subobject is an array, each element is assigned, in the
4536 // manner appropriate to the element type;
4537
4538 // Construct a loop over the array bounds, e.g.,
4539 //
4540 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4541 //
4542 // that will copy each of the array elements.
4543 QualType SizeType = S.Context.getSizeType();
4544
4545 // Create the iteration variable.
4546 IdentifierInfo *IterationVarName = 0;
4547 {
4548 llvm::SmallString<8> Str;
4549 llvm::raw_svector_ostream OS(Str);
4550 OS << "__i" << Depth;
4551 IterationVarName = &S.Context.Idents.get(OS.str());
4552 }
4553 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4554 IterationVarName, SizeType,
4555 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4556 VarDecl::None, VarDecl::None);
4557
4558 // Initialize the iteration variable to zero.
4559 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4560 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4561
4562 // Create a reference to the iteration variable; we'll use this several
4563 // times throughout.
4564 Expr *IterationVarRef
4565 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4566 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4567
4568 // Create the DeclStmt that holds the iteration variable.
4569 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4570
4571 // Create the comparison against the array bound.
4572 llvm::APInt Upper = ArrayTy->getSize();
4573 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4574 OwningExprResult Comparison
4575 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4576 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4577 BinaryOperator::NE, S.Context.BoolTy, Loc));
4578
4579 // Create the pre-increment of the iteration variable.
4580 OwningExprResult Increment
4581 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4582 UnaryOperator::PreInc,
4583 SizeType, Loc));
4584
4585 // Subscript the "from" and "to" expressions with the iteration variable.
4586 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4587 S.Owned(IterationVarRef->Retain()),
4588 Loc);
4589 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4590 S.Owned(IterationVarRef->Retain()),
4591 Loc);
4592 assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4593 assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4594
4595 // Build the copy for an individual element of the array.
4596 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4597 ArrayTy->getElementType(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004598 move(To), move(From),
4599 CopyingBaseSubobject, Depth+1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004600 if (Copy.isInvalid())
Douglas Gregorb139cd52010-05-01 20:49:11 +00004601 return S.StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004602
4603 // Construct the loop that copies all elements of this array.
4604 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4605 S.MakeFullExpr(Comparison),
4606 Sema::DeclPtrTy(),
4607 S.MakeFullExpr(Increment),
4608 Loc, move(Copy));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004609}
4610
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004611/// \brief Determine whether the given class has a copy assignment operator
4612/// that accepts a const-qualified argument.
4613static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4614 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4615
4616 if (!Class->hasDeclaredCopyAssignment())
4617 S.DeclareImplicitCopyAssignment(Class);
4618
4619 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4620 DeclarationName OpName
4621 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4622
4623 DeclContext::lookup_const_iterator Op, OpEnd;
4624 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4625 // C++ [class.copy]p9:
4626 // A user-declared copy assignment operator is a non-static non-template
4627 // member function of class X with exactly one parameter of type X, X&,
4628 // const X&, volatile X& or const volatile X&.
4629 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4630 if (!Method)
4631 continue;
4632
4633 if (Method->isStatic())
4634 continue;
4635 if (Method->getPrimaryTemplate())
4636 continue;
4637 const FunctionProtoType *FnType =
4638 Method->getType()->getAs<FunctionProtoType>();
4639 assert(FnType && "Overloaded operator has no prototype.");
4640 // Don't assert on this; an invalid decl might have been left in the AST.
4641 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4642 continue;
4643 bool AcceptsConst = true;
4644 QualType ArgType = FnType->getArgType(0);
4645 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4646 ArgType = Ref->getPointeeType();
4647 // Is it a non-const lvalue reference?
4648 if (!ArgType.isConstQualified())
4649 AcceptsConst = false;
4650 }
4651 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4652 continue;
4653
4654 // We have a single argument of type cv X or cv X&, i.e. we've found the
4655 // copy assignment operator. Return whether it accepts const arguments.
4656 return AcceptsConst;
4657 }
4658 assert(Class->isInvalidDecl() &&
4659 "No copy assignment operator declared in valid code.");
4660 return false;
4661}
4662
Douglas Gregor0be31a22010-07-02 17:43:08 +00004663CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004664 // Note: The following rules are largely analoguous to the copy
4665 // constructor rules. Note that virtual bases are not taken into account
4666 // for determining the argument type of the operator. Note also that
4667 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004668
4669
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004670 // C++ [class.copy]p10:
4671 // If the class definition does not explicitly declare a copy
4672 // assignment operator, one is declared implicitly.
4673 // The implicitly-defined copy assignment operator for a class X
4674 // will have the form
4675 //
4676 // X& X::operator=(const X&)
4677 //
4678 // if
4679 bool HasConstCopyAssignment = true;
4680
4681 // -- each direct base class B of X has a copy assignment operator
4682 // whose parameter is of type const B&, const volatile B& or B,
4683 // and
4684 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4685 BaseEnd = ClassDecl->bases_end();
4686 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4687 assert(!Base->getType()->isDependentType() &&
4688 "Cannot generate implicit members for class with dependent bases.");
4689 const CXXRecordDecl *BaseClassDecl
4690 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004691 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004692 }
4693
4694 // -- for all the nonstatic data members of X that are of a class
4695 // type M (or array thereof), each such class type has a copy
4696 // assignment operator whose parameter is of type const M&,
4697 // const volatile M& or M.
4698 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4699 FieldEnd = ClassDecl->field_end();
4700 HasConstCopyAssignment && Field != FieldEnd;
4701 ++Field) {
4702 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4703 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4704 const CXXRecordDecl *FieldClassDecl
4705 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004706 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004707 }
4708 }
4709
4710 // Otherwise, the implicitly declared copy assignment operator will
4711 // have the form
4712 //
4713 // X& X::operator=(X&)
4714 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4715 QualType RetType = Context.getLValueReferenceType(ArgType);
4716 if (HasConstCopyAssignment)
4717 ArgType = ArgType.withConst();
4718 ArgType = Context.getLValueReferenceType(ArgType);
4719
Douglas Gregor68e11362010-07-01 17:48:08 +00004720 // C++ [except.spec]p14:
4721 // An implicitly declared special member function (Clause 12) shall have an
4722 // exception-specification. [...]
4723 ImplicitExceptionSpecification ExceptSpec(Context);
4724 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4725 BaseEnd = ClassDecl->bases_end();
4726 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004727 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004728 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004729
4730 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4731 DeclareImplicitCopyAssignment(BaseClassDecl);
4732
Douglas Gregor68e11362010-07-01 17:48:08 +00004733 if (CXXMethodDecl *CopyAssign
4734 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4735 ExceptSpec.CalledDecl(CopyAssign);
4736 }
4737 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4738 FieldEnd = ClassDecl->field_end();
4739 Field != FieldEnd;
4740 ++Field) {
4741 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4742 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004743 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004744 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004745
4746 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4747 DeclareImplicitCopyAssignment(FieldClassDecl);
4748
Douglas Gregor68e11362010-07-01 17:48:08 +00004749 if (CXXMethodDecl *CopyAssign
4750 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4751 ExceptSpec.CalledDecl(CopyAssign);
4752 }
4753 }
4754
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004755 // An implicitly-declared copy assignment operator is an inline public
4756 // member of its class.
4757 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004758 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004759 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004760 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004761 Context.getFunctionType(RetType, &ArgType, 1,
4762 false, 0,
Douglas Gregor68e11362010-07-01 17:48:08 +00004763 ExceptSpec.hasExceptionSpecification(),
4764 ExceptSpec.hasAnyExceptionSpecification(),
4765 ExceptSpec.size(),
4766 ExceptSpec.data(),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004767 FunctionType::ExtInfo()),
4768 /*TInfo=*/0, /*isStatic=*/false,
4769 /*StorageClassAsWritten=*/FunctionDecl::None,
4770 /*isInline=*/true);
4771 CopyAssignment->setAccess(AS_public);
4772 CopyAssignment->setImplicit();
4773 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
4774 CopyAssignment->setCopyAssignment(true);
4775
4776 // Add the parameter to the operator.
4777 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4778 ClassDecl->getLocation(),
4779 /*Id=*/0,
4780 ArgType, /*TInfo=*/0,
4781 VarDecl::None,
4782 VarDecl::None, 0);
4783 CopyAssignment->setParams(&FromParam, 1);
4784
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004785 // Note that we have added this copy-assignment operator.
4786 ClassDecl->setDeclaredCopyAssignment(true);
4787 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4788
Douglas Gregor0be31a22010-07-02 17:43:08 +00004789 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004790 PushOnScopeChains(CopyAssignment, S, false);
4791 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004792
4793 AddOverriddenMethods(ClassDecl, CopyAssignment);
4794 return CopyAssignment;
4795}
4796
Douglas Gregorb139cd52010-05-01 20:49:11 +00004797void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4798 CXXMethodDecl *CopyAssignOperator) {
4799 assert((CopyAssignOperator->isImplicit() &&
4800 CopyAssignOperator->isOverloadedOperator() &&
4801 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004802 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004803 "DefineImplicitCopyAssignment called for wrong function");
4804
4805 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4806
4807 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4808 CopyAssignOperator->setInvalidDecl();
4809 return;
4810 }
4811
4812 CopyAssignOperator->setUsed();
4813
4814 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregor54818f02010-05-12 16:39:35 +00004815 ErrorTrap Trap(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004816
4817 // C++0x [class.copy]p30:
4818 // The implicitly-defined or explicitly-defaulted copy assignment operator
4819 // for a non-union class X performs memberwise copy assignment of its
4820 // subobjects. The direct base classes of X are assigned first, in the
4821 // order of their declaration in the base-specifier-list, and then the
4822 // immediate non-static data members of X are assigned, in the order in
4823 // which they were declared in the class definition.
4824
4825 // The statements that form the synthesized function body.
4826 ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this);
4827
4828 // The parameter for the "other" object, which we are copying from.
4829 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4830 Qualifiers OtherQuals = Other->getType().getQualifiers();
4831 QualType OtherRefType = Other->getType();
4832 if (const LValueReferenceType *OtherRef
4833 = OtherRefType->getAs<LValueReferenceType>()) {
4834 OtherRefType = OtherRef->getPointeeType();
4835 OtherQuals = OtherRefType.getQualifiers();
4836 }
4837
4838 // Our location for everything implicitly-generated.
4839 SourceLocation Loc = CopyAssignOperator->getLocation();
4840
4841 // Construct a reference to the "other" object. We'll be using this
4842 // throughout the generated ASTs.
4843 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4844 assert(OtherRef && "Reference to parameter cannot fail!");
4845
4846 // Construct the "this" pointer. We'll be using this throughout the generated
4847 // ASTs.
4848 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4849 assert(This && "Reference to this cannot fail!");
4850
4851 // Assign base classes.
4852 bool Invalid = false;
4853 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4854 E = ClassDecl->bases_end(); Base != E; ++Base) {
4855 // Form the assignment:
4856 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4857 QualType BaseType = Base->getType().getUnqualifiedType();
4858 CXXRecordDecl *BaseClassDecl = 0;
4859 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4860 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4861 else {
4862 Invalid = true;
4863 continue;
4864 }
4865
John McCallcf142162010-08-07 06:22:56 +00004866 CXXCastPath BasePath;
4867 BasePath.push_back(Base);
4868
Douglas Gregorb139cd52010-05-01 20:49:11 +00004869 // Construct the "from" expression, which is an implicit cast to the
4870 // appropriately-qualified base type.
4871 Expr *From = OtherRef->Retain();
4872 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004873 CastExpr::CK_UncheckedDerivedToBase,
John McCallcf142162010-08-07 06:22:56 +00004874 ImplicitCastExpr::LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004875
4876 // Dereference "this".
4877 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4878 Owned(This->Retain()));
4879
4880 // Implicitly cast "this" to the appropriately-qualified base type.
4881 Expr *ToE = To.takeAs<Expr>();
4882 ImpCastExprToType(ToE,
4883 Context.getCVRQualifiedType(BaseType,
4884 CopyAssignOperator->getTypeQualifiers()),
4885 CastExpr::CK_UncheckedDerivedToBase,
John McCallcf142162010-08-07 06:22:56 +00004886 ImplicitCastExpr::LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004887 To = Owned(ToE);
4888
4889 // Build the copy.
4890 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004891 move(To), Owned(From),
4892 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004893 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004894 Diag(CurrentLocation, diag::note_member_synthesized_at)
4895 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4896 CopyAssignOperator->setInvalidDecl();
4897 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004898 }
4899
4900 // Success! Record the copy.
4901 Statements.push_back(Copy.takeAs<Expr>());
4902 }
4903
4904 // \brief Reference to the __builtin_memcpy function.
4905 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004906 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004907 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004908
4909 // Assign non-static members.
4910 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4911 FieldEnd = ClassDecl->field_end();
4912 Field != FieldEnd; ++Field) {
4913 // Check for members of reference type; we can't copy those.
4914 if (Field->getType()->isReferenceType()) {
4915 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4916 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4917 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004918 Diag(CurrentLocation, diag::note_member_synthesized_at)
4919 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004920 Invalid = true;
4921 continue;
4922 }
4923
4924 // Check for members of const-qualified, non-class type.
4925 QualType BaseType = Context.getBaseElementType(Field->getType());
4926 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4927 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4928 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4929 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004930 Diag(CurrentLocation, diag::note_member_synthesized_at)
4931 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004932 Invalid = true;
4933 continue;
4934 }
4935
4936 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004937 if (FieldType->isIncompleteArrayType()) {
4938 assert(ClassDecl->hasFlexibleArrayMember() &&
4939 "Incomplete array type is not valid");
4940 continue;
4941 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004942
4943 // Build references to the field in the object we're copying from and to.
4944 CXXScopeSpec SS; // Intentionally empty
4945 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4946 LookupMemberName);
4947 MemberLookup.addDecl(*Field);
4948 MemberLookup.resolveKind();
4949 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
4950 OtherRefType,
4951 Loc, /*IsArrow=*/false,
4952 SS, 0, MemberLookup, 0);
4953 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
4954 This->getType(),
4955 Loc, /*IsArrow=*/true,
4956 SS, 0, MemberLookup, 0);
4957 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4958 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4959
4960 // If the field should be copied with __builtin_memcpy rather than via
4961 // explicit assignments, do so. This optimization only applies for arrays
4962 // of scalars and arrays of class type with trivial copy-assignment
4963 // operators.
4964 if (FieldType->isArrayType() &&
4965 (!BaseType->isRecordType() ||
4966 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4967 ->hasTrivialCopyAssignment())) {
4968 // Compute the size of the memory buffer to be copied.
4969 QualType SizeType = Context.getSizeType();
4970 llvm::APInt Size(Context.getTypeSize(SizeType),
4971 Context.getTypeSizeInChars(BaseType).getQuantity());
4972 for (const ConstantArrayType *Array
4973 = Context.getAsConstantArrayType(FieldType);
4974 Array;
4975 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4976 llvm::APInt ArraySize = Array->getSize();
4977 ArraySize.zextOrTrunc(Size.getBitWidth());
4978 Size *= ArraySize;
4979 }
4980
4981 // Take the address of the field references for "from" and "to".
4982 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
4983 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004984
4985 bool NeedsCollectableMemCpy =
4986 (BaseType->isRecordType() &&
4987 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
4988
4989 if (NeedsCollectableMemCpy) {
4990 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004991 // Create a reference to the __builtin_objc_memmove_collectable function.
4992 LookupResult R(*this,
4993 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004994 Loc, LookupOrdinaryName);
4995 LookupName(R, TUScope, true);
4996
4997 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
4998 if (!CollectableMemCpy) {
4999 // Something went horribly wrong earlier, and we will have
5000 // complained about it.
5001 Invalid = true;
5002 continue;
5003 }
5004
5005 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5006 CollectableMemCpy->getType(),
5007 Loc, 0).takeAs<Expr>();
5008 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5009 }
5010 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005011 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005012 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005013 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5014 LookupOrdinaryName);
5015 LookupName(R, TUScope, true);
5016
5017 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5018 if (!BuiltinMemCpy) {
5019 // Something went horribly wrong earlier, and we will have complained
5020 // about it.
5021 Invalid = true;
5022 continue;
5023 }
5024
5025 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5026 BuiltinMemCpy->getType(),
5027 Loc, 0).takeAs<Expr>();
5028 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5029 }
5030
5031 ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this);
5032 CallArgs.push_back(To.takeAs<Expr>());
5033 CallArgs.push_back(From.takeAs<Expr>());
5034 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
5035 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
5036 Commas.push_back(Loc);
5037 Commas.push_back(Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005038 OwningExprResult Call = ExprError();
5039 if (NeedsCollectableMemCpy)
5040 Call = ActOnCallExpr(/*Scope=*/0,
5041 Owned(CollectableMemCpyRef->Retain()),
5042 Loc, move_arg(CallArgs),
5043 Commas.data(), Loc);
5044 else
5045 Call = ActOnCallExpr(/*Scope=*/0,
5046 Owned(BuiltinMemCpyRef->Retain()),
5047 Loc, move_arg(CallArgs),
5048 Commas.data(), Loc);
5049
Douglas Gregorb139cd52010-05-01 20:49:11 +00005050 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5051 Statements.push_back(Call.takeAs<Expr>());
5052 continue;
5053 }
5054
5055 // Build the copy of this field.
5056 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005057 move(To), move(From),
5058 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005059 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005060 Diag(CurrentLocation, diag::note_member_synthesized_at)
5061 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5062 CopyAssignOperator->setInvalidDecl();
5063 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005064 }
5065
5066 // Success! Record the copy.
5067 Statements.push_back(Copy.takeAs<Stmt>());
5068 }
5069
5070 if (!Invalid) {
5071 // Add a "return *this;"
5072 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
5073 Owned(This->Retain()));
5074
5075 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
5076 if (Return.isInvalid())
5077 Invalid = true;
5078 else {
5079 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005080
5081 if (Trap.hasErrorOccurred()) {
5082 Diag(CurrentLocation, diag::note_member_synthesized_at)
5083 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5084 Invalid = true;
5085 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005086 }
5087 }
5088
5089 if (Invalid) {
5090 CopyAssignOperator->setInvalidDecl();
5091 return;
5092 }
5093
5094 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
5095 /*isStmtExpr=*/false);
5096 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5097 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005098}
5099
Douglas Gregor0be31a22010-07-02 17:43:08 +00005100CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5101 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005102 // C++ [class.copy]p4:
5103 // If the class definition does not explicitly declare a copy
5104 // constructor, one is declared implicitly.
5105
Douglas Gregor54be3392010-07-01 17:57:27 +00005106 // C++ [class.copy]p5:
5107 // The implicitly-declared copy constructor for a class X will
5108 // have the form
5109 //
5110 // X::X(const X&)
5111 //
5112 // if
5113 bool HasConstCopyConstructor = true;
5114
5115 // -- each direct or virtual base class B of X has a copy
5116 // constructor whose first parameter is of type const B& or
5117 // const volatile B&, and
5118 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5119 BaseEnd = ClassDecl->bases_end();
5120 HasConstCopyConstructor && Base != BaseEnd;
5121 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005122 // Virtual bases are handled below.
5123 if (Base->isVirtual())
5124 continue;
5125
Douglas Gregora6d69502010-07-02 23:41:54 +00005126 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005127 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005128 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5129 DeclareImplicitCopyConstructor(BaseClassDecl);
5130
Douglas Gregorcfe68222010-07-01 18:27:03 +00005131 HasConstCopyConstructor
5132 = BaseClassDecl->hasConstCopyConstructor(Context);
5133 }
5134
5135 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5136 BaseEnd = ClassDecl->vbases_end();
5137 HasConstCopyConstructor && Base != BaseEnd;
5138 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005139 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005140 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005141 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5142 DeclareImplicitCopyConstructor(BaseClassDecl);
5143
Douglas Gregor54be3392010-07-01 17:57:27 +00005144 HasConstCopyConstructor
5145 = BaseClassDecl->hasConstCopyConstructor(Context);
5146 }
5147
5148 // -- for all the nonstatic data members of X that are of a
5149 // class type M (or array thereof), each such class type
5150 // has a copy constructor whose first parameter is of type
5151 // const M& or const volatile M&.
5152 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5153 FieldEnd = ClassDecl->field_end();
5154 HasConstCopyConstructor && Field != FieldEnd;
5155 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005156 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005157 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005158 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005159 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005160 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5161 DeclareImplicitCopyConstructor(FieldClassDecl);
5162
Douglas Gregor54be3392010-07-01 17:57:27 +00005163 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005164 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005165 }
5166 }
5167
5168 // Otherwise, the implicitly declared copy constructor will have
5169 // the form
5170 //
5171 // X::X(X&)
5172 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5173 QualType ArgType = ClassType;
5174 if (HasConstCopyConstructor)
5175 ArgType = ArgType.withConst();
5176 ArgType = Context.getLValueReferenceType(ArgType);
5177
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005178 // C++ [except.spec]p14:
5179 // An implicitly declared special member function (Clause 12) shall have an
5180 // exception-specification. [...]
5181 ImplicitExceptionSpecification ExceptSpec(Context);
5182 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5183 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5184 BaseEnd = ClassDecl->bases_end();
5185 Base != BaseEnd;
5186 ++Base) {
5187 // Virtual bases are handled below.
5188 if (Base->isVirtual())
5189 continue;
5190
Douglas Gregora6d69502010-07-02 23:41:54 +00005191 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005192 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005193 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5194 DeclareImplicitCopyConstructor(BaseClassDecl);
5195
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005196 if (CXXConstructorDecl *CopyConstructor
5197 = BaseClassDecl->getCopyConstructor(Context, Quals))
5198 ExceptSpec.CalledDecl(CopyConstructor);
5199 }
5200 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5201 BaseEnd = ClassDecl->vbases_end();
5202 Base != BaseEnd;
5203 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005204 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005205 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005206 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5207 DeclareImplicitCopyConstructor(BaseClassDecl);
5208
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005209 if (CXXConstructorDecl *CopyConstructor
5210 = BaseClassDecl->getCopyConstructor(Context, Quals))
5211 ExceptSpec.CalledDecl(CopyConstructor);
5212 }
5213 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5214 FieldEnd = ClassDecl->field_end();
5215 Field != FieldEnd;
5216 ++Field) {
5217 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5218 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005219 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005220 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005221 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5222 DeclareImplicitCopyConstructor(FieldClassDecl);
5223
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005224 if (CXXConstructorDecl *CopyConstructor
5225 = FieldClassDecl->getCopyConstructor(Context, Quals))
5226 ExceptSpec.CalledDecl(CopyConstructor);
5227 }
5228 }
5229
Douglas Gregor54be3392010-07-01 17:57:27 +00005230 // An implicitly-declared copy constructor is an inline public
5231 // member of its class.
5232 DeclarationName Name
5233 = Context.DeclarationNames.getCXXConstructorName(
5234 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005235 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005236 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005237 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005238 Context.getFunctionType(Context.VoidTy,
5239 &ArgType, 1,
5240 false, 0,
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005241 ExceptSpec.hasExceptionSpecification(),
5242 ExceptSpec.hasAnyExceptionSpecification(),
5243 ExceptSpec.size(),
5244 ExceptSpec.data(),
Douglas Gregor54be3392010-07-01 17:57:27 +00005245 FunctionType::ExtInfo()),
5246 /*TInfo=*/0,
5247 /*isExplicit=*/false,
5248 /*isInline=*/true,
5249 /*isImplicitlyDeclared=*/true);
5250 CopyConstructor->setAccess(AS_public);
5251 CopyConstructor->setImplicit();
5252 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5253
Douglas Gregora6d69502010-07-02 23:41:54 +00005254 // Note that we have declared this constructor.
5255 ClassDecl->setDeclaredCopyConstructor(true);
5256 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5257
Douglas Gregor54be3392010-07-01 17:57:27 +00005258 // Add the parameter to the constructor.
5259 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5260 ClassDecl->getLocation(),
5261 /*IdentifierInfo=*/0,
5262 ArgType, /*TInfo=*/0,
5263 VarDecl::None,
5264 VarDecl::None, 0);
5265 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005266 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005267 PushOnScopeChains(CopyConstructor, S, false);
5268 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005269
5270 return CopyConstructor;
5271}
5272
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005273void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5274 CXXConstructorDecl *CopyConstructor,
5275 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005276 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005277 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005278 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005279 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005280
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005281 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005282 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005283
Douglas Gregora57478e2010-05-01 15:04:51 +00005284 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00005285 ErrorTrap Trap(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005286
Douglas Gregor54818f02010-05-12 16:39:35 +00005287 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5288 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005289 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005290 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005291 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005292 } else {
5293 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5294 CopyConstructor->getLocation(),
5295 MultiStmtArg(*this, 0, 0),
5296 /*isStmtExpr=*/false)
5297 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005298 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005299
5300 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005301}
5302
Anders Carlsson6eb55572009-08-25 05:12:04 +00005303Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005304Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005305 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005306 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005307 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00005308 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005309 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005310
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005311 // C++0x [class.copy]p34:
5312 // When certain criteria are met, an implementation is allowed to
5313 // omit the copy/move construction of a class object, even if the
5314 // copy/move constructor and/or destructor for the object have
5315 // side effects. [...]
5316 // - when a temporary class object that has not been bound to a
5317 // reference (12.2) would be copied/moved to a class object
5318 // with the same cv-unqualified type, the copy/move operation
5319 // can be omitted by constructing the temporary object
5320 // directly into the target of the omitted copy/move
5321 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
5322 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
5323 Elidable = SubExpr->isTemporaryObject() &&
5324 Context.hasSameUnqualifiedType(SubExpr->getType(),
5325 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson250aada2009-08-16 05:13:48 +00005326 }
Mike Stump11289f42009-09-09 15:08:12 +00005327
5328 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005329 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00005330 ConstructKind);
Anders Carlsson250aada2009-08-16 05:13:48 +00005331}
5332
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005333/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5334/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00005335Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005336Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5337 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005338 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005339 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00005340 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005341 unsigned NumExprs = ExprArgs.size();
5342 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005343
Douglas Gregor27381f32009-11-23 12:27:39 +00005344 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005345 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005346 Constructor, Elidable, Exprs, NumExprs,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00005347 RequiresZeroInit, ConstructKind));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005348}
5349
Mike Stump11289f42009-09-09 15:08:12 +00005350bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005351 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005352 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00005353 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005354 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005355 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005356 if (TempResult.isInvalid())
5357 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005358
Anders Carlsson6eb55572009-08-25 05:12:04 +00005359 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00005360 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00005361 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005362 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005363
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005364 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005365}
5366
John McCall03c48482010-02-02 09:10:11 +00005367void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5368 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005369 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005370 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005371 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005372 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005373 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005374 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005375 << VD->getDeclName()
5376 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005377
5378 if (!VD->isInvalidDecl() && VD->hasGlobalStorage())
5379 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005380 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005381}
5382
Mike Stump11289f42009-09-09 15:08:12 +00005383/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005384/// ActOnDeclarator, when a C++ direct initializer is present.
5385/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00005386void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
5387 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005388 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005389 SourceLocation *CommaLocs,
5390 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005391 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00005392 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005393
5394 // If there is no declaration, there was an error parsing it. Just ignore
5395 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005396 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005397 return;
Mike Stump11289f42009-09-09 15:08:12 +00005398
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005399 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5400 if (!VDecl) {
5401 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5402 RealDecl->setInvalidDecl();
5403 return;
5404 }
5405
Douglas Gregor402250f2009-08-26 21:14:46 +00005406 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005407 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005408 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5409 //
5410 // Clients that want to distinguish between the two forms, can check for
5411 // direct initializer using VarDecl::hasCXXDirectInitializer().
5412 // A major benefit is that clients that don't particularly care about which
5413 // exactly form was it (like the CodeGen) can handle both cases without
5414 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005415
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005416 // C++ 8.5p11:
5417 // The form of initialization (using parentheses or '=') is generally
5418 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005419 // class type.
5420
Douglas Gregor50dc2192010-02-11 22:55:30 +00005421 if (!VDecl->getType()->isDependentType() &&
5422 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005423 diag::err_typecheck_decl_incomplete_type)) {
5424 VDecl->setInvalidDecl();
5425 return;
5426 }
5427
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005428 // The variable can not have an abstract class type.
5429 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5430 diag::err_abstract_type_in_decl,
5431 AbstractVariableType))
5432 VDecl->setInvalidDecl();
5433
Sebastian Redl5ca79842010-02-01 20:16:42 +00005434 const VarDecl *Def;
5435 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005436 Diag(VDecl->getLocation(), diag::err_redefinition)
5437 << VDecl->getDeclName();
5438 Diag(Def->getLocation(), diag::note_previous_definition);
5439 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005440 return;
5441 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005442
5443 // If either the declaration has a dependent type or if any of the
5444 // expressions is type-dependent, we represent the initialization
5445 // via a ParenListExpr for later use during template instantiation.
5446 if (VDecl->getType()->isDependentType() ||
5447 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5448 // Let clients know that initialization was done with a direct initializer.
5449 VDecl->setCXXDirectInitializer(true);
5450
5451 // Store the initialization expressions as a ParenListExpr.
5452 unsigned NumExprs = Exprs.size();
5453 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5454 (Expr **)Exprs.release(),
5455 NumExprs, RParenLoc));
5456 return;
5457 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005458
5459 // Capture the variable that is being initialized and the style of
5460 // initialization.
5461 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5462
5463 // FIXME: Poor source location information.
5464 InitializationKind Kind
5465 = InitializationKind::CreateDirect(VDecl->getLocation(),
5466 LParenLoc, RParenLoc);
5467
5468 InitializationSequence InitSeq(*this, Entity, Kind,
5469 (Expr**)Exprs.get(), Exprs.size());
5470 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
5471 if (Result.isInvalid()) {
5472 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005473 return;
5474 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005475
5476 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregord5058122010-02-11 01:19:42 +00005477 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005478 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005479
John McCall8b0f4ff2010-08-02 21:13:48 +00005480 if (!VDecl->isInvalidDecl() &&
5481 !VDecl->getDeclContext()->isDependentContext() &&
5482 VDecl->hasGlobalStorage() &&
5483 !VDecl->getInit()->isConstantInitializer(Context,
5484 VDecl->getType()->isReferenceType()))
5485 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5486 << VDecl->getInit()->getSourceRange();
5487
John McCall03c48482010-02-02 09:10:11 +00005488 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5489 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005490}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005491
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005492/// \brief Given a constructor and the set of arguments provided for the
5493/// constructor, convert the arguments and add any required default arguments
5494/// to form a proper call to this constructor.
5495///
5496/// \returns true if an error occurred, false otherwise.
5497bool
5498Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5499 MultiExprArg ArgsPtr,
5500 SourceLocation Loc,
5501 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
5502 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5503 unsigned NumArgs = ArgsPtr.size();
5504 Expr **Args = (Expr **)ArgsPtr.get();
5505
5506 const FunctionProtoType *Proto
5507 = Constructor->getType()->getAs<FunctionProtoType>();
5508 assert(Proto && "Constructor without a prototype?");
5509 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005510
5511 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005512 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005513 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005514 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005515 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005516
5517 VariadicCallType CallType =
5518 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5519 llvm::SmallVector<Expr *, 8> AllArgs;
5520 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5521 Proto, 0, Args, NumArgs, AllArgs,
5522 CallType);
5523 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5524 ConvertedArgs.push_back(AllArgs[i]);
5525 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005526}
5527
Anders Carlssone363c8e2009-12-12 00:32:00 +00005528static inline bool
5529CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5530 const FunctionDecl *FnDecl) {
5531 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
5532 if (isa<NamespaceDecl>(DC)) {
5533 return SemaRef.Diag(FnDecl->getLocation(),
5534 diag::err_operator_new_delete_declared_in_namespace)
5535 << FnDecl->getDeclName();
5536 }
5537
5538 if (isa<TranslationUnitDecl>(DC) &&
5539 FnDecl->getStorageClass() == FunctionDecl::Static) {
5540 return SemaRef.Diag(FnDecl->getLocation(),
5541 diag::err_operator_new_delete_declared_static)
5542 << FnDecl->getDeclName();
5543 }
5544
Anders Carlsson60659a82009-12-12 02:43:16 +00005545 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005546}
5547
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005548static inline bool
5549CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5550 CanQualType ExpectedResultType,
5551 CanQualType ExpectedFirstParamType,
5552 unsigned DependentParamTypeDiag,
5553 unsigned InvalidParamTypeDiag) {
5554 QualType ResultType =
5555 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5556
5557 // Check that the result type is not dependent.
5558 if (ResultType->isDependentType())
5559 return SemaRef.Diag(FnDecl->getLocation(),
5560 diag::err_operator_new_delete_dependent_result_type)
5561 << FnDecl->getDeclName() << ExpectedResultType;
5562
5563 // Check that the result type is what we expect.
5564 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5565 return SemaRef.Diag(FnDecl->getLocation(),
5566 diag::err_operator_new_delete_invalid_result_type)
5567 << FnDecl->getDeclName() << ExpectedResultType;
5568
5569 // A function template must have at least 2 parameters.
5570 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5571 return SemaRef.Diag(FnDecl->getLocation(),
5572 diag::err_operator_new_delete_template_too_few_parameters)
5573 << FnDecl->getDeclName();
5574
5575 // The function decl must have at least 1 parameter.
5576 if (FnDecl->getNumParams() == 0)
5577 return SemaRef.Diag(FnDecl->getLocation(),
5578 diag::err_operator_new_delete_too_few_parameters)
5579 << FnDecl->getDeclName();
5580
5581 // Check the the first parameter type is not dependent.
5582 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5583 if (FirstParamType->isDependentType())
5584 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5585 << FnDecl->getDeclName() << ExpectedFirstParamType;
5586
5587 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005588 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005589 ExpectedFirstParamType)
5590 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5591 << FnDecl->getDeclName() << ExpectedFirstParamType;
5592
5593 return false;
5594}
5595
Anders Carlsson12308f42009-12-11 23:23:22 +00005596static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005597CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005598 // C++ [basic.stc.dynamic.allocation]p1:
5599 // A program is ill-formed if an allocation function is declared in a
5600 // namespace scope other than global scope or declared static in global
5601 // scope.
5602 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5603 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005604
5605 CanQualType SizeTy =
5606 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5607
5608 // C++ [basic.stc.dynamic.allocation]p1:
5609 // The return type shall be void*. The first parameter shall have type
5610 // std::size_t.
5611 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5612 SizeTy,
5613 diag::err_operator_new_dependent_param_type,
5614 diag::err_operator_new_param_type))
5615 return true;
5616
5617 // C++ [basic.stc.dynamic.allocation]p1:
5618 // The first parameter shall not have an associated default argument.
5619 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005620 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005621 diag::err_operator_new_default_arg)
5622 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5623
5624 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005625}
5626
5627static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005628CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5629 // C++ [basic.stc.dynamic.deallocation]p1:
5630 // A program is ill-formed if deallocation functions are declared in a
5631 // namespace scope other than global scope or declared static in global
5632 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005633 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5634 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005635
5636 // C++ [basic.stc.dynamic.deallocation]p2:
5637 // Each deallocation function shall return void and its first parameter
5638 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005639 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5640 SemaRef.Context.VoidPtrTy,
5641 diag::err_operator_delete_dependent_param_type,
5642 diag::err_operator_delete_param_type))
5643 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005644
Anders Carlsson12308f42009-12-11 23:23:22 +00005645 return false;
5646}
5647
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005648/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5649/// of this overloaded operator is well-formed. If so, returns false;
5650/// otherwise, emits appropriate diagnostics and returns true.
5651bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005652 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005653 "Expected an overloaded operator declaration");
5654
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005655 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5656
Mike Stump11289f42009-09-09 15:08:12 +00005657 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005658 // The allocation and deallocation functions, operator new,
5659 // operator new[], operator delete and operator delete[], are
5660 // described completely in 3.7.3. The attributes and restrictions
5661 // found in the rest of this subclause do not apply to them unless
5662 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005663 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005664 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005665
Anders Carlsson22f443f2009-12-12 00:26:23 +00005666 if (Op == OO_New || Op == OO_Array_New)
5667 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005668
5669 // C++ [over.oper]p6:
5670 // An operator function shall either be a non-static member
5671 // function or be a non-member function and have at least one
5672 // parameter whose type is a class, a reference to a class, an
5673 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005674 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5675 if (MethodDecl->isStatic())
5676 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005677 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005678 } else {
5679 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005680 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5681 ParamEnd = FnDecl->param_end();
5682 Param != ParamEnd; ++Param) {
5683 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005684 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5685 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005686 ClassOrEnumParam = true;
5687 break;
5688 }
5689 }
5690
Douglas Gregord69246b2008-11-17 16:14:12 +00005691 if (!ClassOrEnumParam)
5692 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005693 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005694 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005695 }
5696
5697 // C++ [over.oper]p8:
5698 // An operator function cannot have default arguments (8.3.6),
5699 // except where explicitly stated below.
5700 //
Mike Stump11289f42009-09-09 15:08:12 +00005701 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005702 // (C++ [over.call]p1).
5703 if (Op != OO_Call) {
5704 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5705 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005706 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005707 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005708 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005709 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005710 }
5711 }
5712
Douglas Gregor6cf08062008-11-10 13:38:07 +00005713 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5714 { false, false, false }
5715#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5716 , { Unary, Binary, MemberOnly }
5717#include "clang/Basic/OperatorKinds.def"
5718 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005719
Douglas Gregor6cf08062008-11-10 13:38:07 +00005720 bool CanBeUnaryOperator = OperatorUses[Op][0];
5721 bool CanBeBinaryOperator = OperatorUses[Op][1];
5722 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005723
5724 // C++ [over.oper]p8:
5725 // [...] Operator functions cannot have more or fewer parameters
5726 // than the number required for the corresponding operator, as
5727 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005728 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005729 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005730 if (Op != OO_Call &&
5731 ((NumParams == 1 && !CanBeUnaryOperator) ||
5732 (NumParams == 2 && !CanBeBinaryOperator) ||
5733 (NumParams < 1) || (NumParams > 2))) {
5734 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005735 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005736 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005737 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005738 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005739 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005740 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005741 assert(CanBeBinaryOperator &&
5742 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005743 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005744 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005745
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005746 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005747 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005748 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005749
Douglas Gregord69246b2008-11-17 16:14:12 +00005750 // Overloaded operators other than operator() cannot be variadic.
5751 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005752 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005753 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005754 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005755 }
5756
5757 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005758 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5759 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005760 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005761 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005762 }
5763
5764 // C++ [over.inc]p1:
5765 // The user-defined function called operator++ implements the
5766 // prefix and postfix ++ operator. If this function is a member
5767 // function with no parameters, or a non-member function with one
5768 // parameter of class or enumeration type, it defines the prefix
5769 // increment operator ++ for objects of that type. If the function
5770 // is a member function with one parameter (which shall be of type
5771 // int) or a non-member function with two parameters (the second
5772 // of which shall be of type int), it defines the postfix
5773 // increment operator ++ for objects of that type.
5774 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5775 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5776 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005777 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005778 ParamIsInt = BT->getKind() == BuiltinType::Int;
5779
Chris Lattner2b786902008-11-21 07:50:02 +00005780 if (!ParamIsInt)
5781 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005782 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005783 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005784 }
5785
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005786 // Notify the class if it got an assignment operator.
5787 if (Op == OO_Equal) {
5788 // Would have returned earlier otherwise.
5789 assert(isa<CXXMethodDecl>(FnDecl) &&
5790 "Overloaded = not member, but not filtered.");
5791 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5792 Method->getParent()->addedAssignmentOperator(Context, Method);
5793 }
5794
Douglas Gregord69246b2008-11-17 16:14:12 +00005795 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005796}
Chris Lattner3b024a32008-12-17 07:09:26 +00005797
Alexis Huntc88db062010-01-13 09:01:02 +00005798/// CheckLiteralOperatorDeclaration - Check whether the declaration
5799/// of this literal operator function is well-formed. If so, returns
5800/// false; otherwise, emits appropriate diagnostics and returns true.
5801bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5802 DeclContext *DC = FnDecl->getDeclContext();
5803 Decl::Kind Kind = DC->getDeclKind();
5804 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5805 Kind != Decl::LinkageSpec) {
5806 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5807 << FnDecl->getDeclName();
5808 return true;
5809 }
5810
5811 bool Valid = false;
5812
Alexis Hunt7dd26172010-04-07 23:11:06 +00005813 // template <char...> type operator "" name() is the only valid template
5814 // signature, and the only valid signature with no parameters.
5815 if (FnDecl->param_size() == 0) {
5816 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5817 // Must have only one template parameter
5818 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5819 if (Params->size() == 1) {
5820 NonTypeTemplateParmDecl *PmDecl =
5821 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005822
Alexis Hunt7dd26172010-04-07 23:11:06 +00005823 // The template parameter must be a char parameter pack.
5824 // FIXME: This test will always fail because non-type parameter packs
5825 // have not been implemented.
5826 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5827 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5828 Valid = true;
5829 }
5830 }
5831 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005832 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005833 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5834
Alexis Huntc88db062010-01-13 09:01:02 +00005835 QualType T = (*Param)->getType();
5836
Alexis Hunt079a6f72010-04-07 22:57:35 +00005837 // unsigned long long int, long double, and any character type are allowed
5838 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005839 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5840 Context.hasSameType(T, Context.LongDoubleTy) ||
5841 Context.hasSameType(T, Context.CharTy) ||
5842 Context.hasSameType(T, Context.WCharTy) ||
5843 Context.hasSameType(T, Context.Char16Ty) ||
5844 Context.hasSameType(T, Context.Char32Ty)) {
5845 if (++Param == FnDecl->param_end())
5846 Valid = true;
5847 goto FinishedParams;
5848 }
5849
Alexis Hunt079a6f72010-04-07 22:57:35 +00005850 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005851 const PointerType *PT = T->getAs<PointerType>();
5852 if (!PT)
5853 goto FinishedParams;
5854 T = PT->getPointeeType();
5855 if (!T.isConstQualified())
5856 goto FinishedParams;
5857 T = T.getUnqualifiedType();
5858
5859 // Move on to the second parameter;
5860 ++Param;
5861
5862 // If there is no second parameter, the first must be a const char *
5863 if (Param == FnDecl->param_end()) {
5864 if (Context.hasSameType(T, Context.CharTy))
5865 Valid = true;
5866 goto FinishedParams;
5867 }
5868
5869 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5870 // are allowed as the first parameter to a two-parameter function
5871 if (!(Context.hasSameType(T, Context.CharTy) ||
5872 Context.hasSameType(T, Context.WCharTy) ||
5873 Context.hasSameType(T, Context.Char16Ty) ||
5874 Context.hasSameType(T, Context.Char32Ty)))
5875 goto FinishedParams;
5876
5877 // The second and final parameter must be an std::size_t
5878 T = (*Param)->getType().getUnqualifiedType();
5879 if (Context.hasSameType(T, Context.getSizeType()) &&
5880 ++Param == FnDecl->param_end())
5881 Valid = true;
5882 }
5883
5884 // FIXME: This diagnostic is absolutely terrible.
5885FinishedParams:
5886 if (!Valid) {
5887 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5888 << FnDecl->getDeclName();
5889 return true;
5890 }
5891
5892 return false;
5893}
5894
Douglas Gregor07665a62009-01-05 19:45:36 +00005895/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5896/// linkage specification, including the language and (if present)
5897/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5898/// the location of the language string literal, which is provided
5899/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5900/// the '{' brace. Otherwise, this linkage specification does not
5901/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005902Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5903 SourceLocation ExternLoc,
5904 SourceLocation LangLoc,
Benjamin Kramerbebee842010-05-03 13:08:54 +00005905 llvm::StringRef Lang,
Chris Lattner83f095c2009-03-28 19:18:32 +00005906 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005907 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005908 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005909 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005910 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005911 Language = LinkageSpecDecl::lang_cxx;
5912 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005913 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00005914 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00005915 }
Mike Stump11289f42009-09-09 15:08:12 +00005916
Chris Lattner438e5012008-12-17 07:13:27 +00005917 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005918
Douglas Gregor07665a62009-01-05 19:45:36 +00005919 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005920 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005921 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005922 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005923 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005924 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00005925}
5926
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00005927/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00005928/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5929/// valid, it's the position of the closing '}' brace in a linkage
5930/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005931Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5932 DeclPtrTy LinkageSpec,
5933 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005934 if (LinkageSpec)
5935 PopDeclContext();
5936 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005937}
5938
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005939/// \brief Perform semantic analysis for the variable declaration that
5940/// occurs within a C++ catch clause, returning the newly-created
5941/// variable.
5942VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00005943 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005944 IdentifierInfo *Name,
5945 SourceLocation Loc,
5946 SourceRange Range) {
5947 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005948
5949 // Arrays and functions decay.
5950 if (ExDeclType->isArrayType())
5951 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5952 else if (ExDeclType->isFunctionType())
5953 ExDeclType = Context.getPointerType(ExDeclType);
5954
5955 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5956 // The exception-declaration shall not denote a pointer or reference to an
5957 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005958 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005959 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005960 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00005961 Invalid = true;
5962 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005963
Douglas Gregor104ee002010-03-08 01:47:36 +00005964 // GCC allows catching pointers and references to incomplete types
5965 // as an extension; so do we, but we warn by default.
5966
Sebastian Redl54c04d42008-12-22 19:15:10 +00005967 QualType BaseType = ExDeclType;
5968 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005969 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00005970 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005971 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005972 BaseType = Ptr->getPointeeType();
5973 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00005974 DK = diag::ext_catch_incomplete_ptr;
5975 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00005976 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005977 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005978 BaseType = Ref->getPointeeType();
5979 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00005980 DK = diag::ext_catch_incomplete_ref;
5981 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005982 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005983 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00005984 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5985 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00005986 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005987
Mike Stump11289f42009-09-09 15:08:12 +00005988 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005989 RequireNonAbstractType(Loc, ExDeclType,
5990 diag::err_abstract_type_in_decl,
5991 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005992 Invalid = true;
5993
John McCall2ca705e2010-07-24 00:37:23 +00005994 // Only the non-fragile NeXT runtime currently supports C++ catches
5995 // of ObjC types, and no runtime supports catching ObjC types by value.
5996 if (!Invalid && getLangOptions().ObjC1) {
5997 QualType T = ExDeclType;
5998 if (const ReferenceType *RT = T->getAs<ReferenceType>())
5999 T = RT->getPointeeType();
6000
6001 if (T->isObjCObjectType()) {
6002 Diag(Loc, diag::err_objc_object_catch);
6003 Invalid = true;
6004 } else if (T->isObjCObjectPointerType()) {
6005 if (!getLangOptions().NeXTRuntime) {
6006 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6007 Invalid = true;
6008 } else if (!getLangOptions().ObjCNonFragileABI) {
6009 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6010 Invalid = true;
6011 }
6012 }
6013 }
6014
Mike Stump11289f42009-09-09 15:08:12 +00006015 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006016 Name, ExDeclType, TInfo, VarDecl::None,
6017 VarDecl::None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006018 ExDecl->setExceptionVariable(true);
6019
Douglas Gregor6de584c2010-03-05 23:38:39 +00006020 if (!Invalid) {
6021 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6022 // C++ [except.handle]p16:
6023 // The object declared in an exception-declaration or, if the
6024 // exception-declaration does not specify a name, a temporary (12.2) is
6025 // copy-initialized (8.5) from the exception object. [...]
6026 // The object is destroyed when the handler exits, after the destruction
6027 // of any automatic objects initialized within the handler.
6028 //
6029 // We just pretend to initialize the object with itself, then make sure
6030 // it can be destroyed later.
6031 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6032 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6033 Loc, ExDeclType, 0);
6034 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6035 SourceLocation());
6036 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
6037 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6038 MultiExprArg(*this, (void**)&ExDeclRef, 1));
6039 if (Result.isInvalid())
6040 Invalid = true;
6041 else
6042 FinalizeVarWithDestructor(ExDecl, RecordTy);
6043 }
6044 }
6045
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006046 if (Invalid)
6047 ExDecl->setInvalidDecl();
6048
6049 return ExDecl;
6050}
6051
6052/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6053/// handler.
6054Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006055 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6056 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006057
6058 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00006059 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006060 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006061 LookupOrdinaryName,
6062 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006063 // The scope should be freshly made just for us. There is just no way
6064 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00006065 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006066 if (PrevDecl->isTemplateParameter()) {
6067 // Maybe we will complain about the shadowed template parameter.
6068 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006069 }
6070 }
6071
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006072 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006073 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6074 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006075 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006076 }
6077
John McCallbcd03502009-12-07 02:54:59 +00006078 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006079 D.getIdentifier(),
6080 D.getIdentifierLoc(),
6081 D.getDeclSpec().getSourceRange());
6082
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006083 if (Invalid)
6084 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006085
Sebastian Redl54c04d42008-12-22 19:15:10 +00006086 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006087 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006088 PushOnScopeChains(ExDecl, S);
6089 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006090 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006091
Douglas Gregor758a8692009-06-17 21:51:59 +00006092 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00006093 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006094}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006095
Mike Stump11289f42009-09-09 15:08:12 +00006096Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00006097 ExprArg assertexpr,
6098 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006099 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00006100 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006101 cast<StringLiteral>((Expr *)assertmessageexpr.get());
6102
Anders Carlsson54b26982009-03-14 00:33:21 +00006103 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6104 llvm::APSInt Value(32);
6105 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6106 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6107 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00006108 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00006109 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006110
Anders Carlsson54b26982009-03-14 00:33:21 +00006111 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006112 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006113 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006114 }
6115 }
Mike Stump11289f42009-09-09 15:08:12 +00006116
Anders Carlsson78e2bc02009-03-15 17:35:16 +00006117 assertexpr.release();
6118 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00006119 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006120 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006121
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006122 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00006123 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006124}
Sebastian Redlf769df52009-03-24 22:27:57 +00006125
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006126/// \brief Perform semantic analysis of the given friend type declaration.
6127///
6128/// \returns A friend declaration that.
6129FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6130 TypeSourceInfo *TSInfo) {
6131 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6132
6133 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006134 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006135
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006136 if (!getLangOptions().CPlusPlus0x) {
6137 // C++03 [class.friend]p2:
6138 // An elaborated-type-specifier shall be used in a friend declaration
6139 // for a class.*
6140 //
6141 // * The class-key of the elaborated-type-specifier is required.
6142 if (!ActiveTemplateInstantiations.empty()) {
6143 // Do not complain about the form of friend template types during
6144 // template instantiation; we will already have complained when the
6145 // template was declared.
6146 } else if (!T->isElaboratedTypeSpecifier()) {
6147 // If we evaluated the type to a record type, suggest putting
6148 // a tag in front.
6149 if (const RecordType *RT = T->getAs<RecordType>()) {
6150 RecordDecl *RD = RT->getDecl();
6151
6152 std::string InsertionText = std::string(" ") + RD->getKindName();
6153
6154 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6155 << (unsigned) RD->getTagKind()
6156 << T
6157 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6158 InsertionText);
6159 } else {
6160 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6161 << T
6162 << SourceRange(FriendLoc, TypeRange.getEnd());
6163 }
6164 } else if (T->getAs<EnumType>()) {
6165 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006166 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006167 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006168 }
6169 }
6170
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006171 // C++0x [class.friend]p3:
6172 // If the type specifier in a friend declaration designates a (possibly
6173 // cv-qualified) class type, that class is declared as a friend; otherwise,
6174 // the friend declaration is ignored.
6175
6176 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6177 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006178
6179 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6180}
6181
John McCall11083da2009-09-16 22:47:08 +00006182/// Handle a friend type declaration. This works in tandem with
6183/// ActOnTag.
6184///
6185/// Notes on friend class templates:
6186///
6187/// We generally treat friend class declarations as if they were
6188/// declaring a class. So, for example, the elaborated type specifier
6189/// in a friend declaration is required to obey the restrictions of a
6190/// class-head (i.e. no typedefs in the scope chain), template
6191/// parameters are required to match up with simple template-ids, &c.
6192/// However, unlike when declaring a template specialization, it's
6193/// okay to refer to a template specialization without an empty
6194/// template parameter declaration, e.g.
6195/// friend class A<T>::B<unsigned>;
6196/// We permit this as a special case; if there are any template
6197/// parameters present at all, require proper matching, i.e.
6198/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00006199Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00006200 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006201 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006202
6203 assert(DS.isFriendSpecified());
6204 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6205
John McCall11083da2009-09-16 22:47:08 +00006206 // Try to convert the decl specifier to a type. This works for
6207 // friend templates because ActOnTag never produces a ClassTemplateDecl
6208 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006209 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006210 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6211 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006212 if (TheDeclarator.isInvalidType())
6213 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00006214
John McCall11083da2009-09-16 22:47:08 +00006215 // This is definitely an error in C++98. It's probably meant to
6216 // be forbidden in C++0x, too, but the specification is just
6217 // poorly written.
6218 //
6219 // The problem is with declarations like the following:
6220 // template <T> friend A<T>::foo;
6221 // where deciding whether a class C is a friend or not now hinges
6222 // on whether there exists an instantiation of A that causes
6223 // 'foo' to equal C. There are restrictions on class-heads
6224 // (which we declare (by fiat) elaborated friend declarations to
6225 // be) that makes this tractable.
6226 //
6227 // FIXME: handle "template <> friend class A<T>;", which
6228 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006229 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006230 Diag(Loc, diag::err_tagless_friend_type_template)
6231 << DS.getSourceRange();
6232 return DeclPtrTy();
6233 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006234
John McCallaa74a0c2009-08-28 07:59:38 +00006235 // C++98 [class.friend]p1: A friend of a class is a function
6236 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006237 // This is fixed in DR77, which just barely didn't make the C++03
6238 // deadline. It's also a very silly restriction that seriously
6239 // affects inner classes and which nobody else seems to implement;
6240 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006241 //
6242 // But note that we could warn about it: it's always useless to
6243 // friend one of your own members (it's not, however, worthless to
6244 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006245
John McCall11083da2009-09-16 22:47:08 +00006246 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006247 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006248 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006249 NumTempParamLists,
John McCall11083da2009-09-16 22:47:08 +00006250 (TemplateParameterList**) TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006251 TSI,
John McCall11083da2009-09-16 22:47:08 +00006252 DS.getFriendSpecLoc());
6253 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006254 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6255
6256 if (!D)
6257 return DeclPtrTy();
6258
John McCall11083da2009-09-16 22:47:08 +00006259 D->setAccess(AS_public);
6260 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006261
John McCall11083da2009-09-16 22:47:08 +00006262 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006263}
6264
John McCall2f212b32009-09-11 21:02:39 +00006265Sema::DeclPtrTy
6266Sema::ActOnFriendFunctionDecl(Scope *S,
6267 Declarator &D,
6268 bool IsDefinition,
6269 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006270 const DeclSpec &DS = D.getDeclSpec();
6271
6272 assert(DS.isFriendSpecified());
6273 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6274
6275 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006276 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6277 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006278
6279 // C++ [class.friend]p1
6280 // A friend of a class is a function or class....
6281 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006282 // It *doesn't* see through dependent types, which is correct
6283 // according to [temp.arg.type]p3:
6284 // If a declaration acquires a function type through a
6285 // type dependent on a template-parameter and this causes
6286 // a declaration that does not use the syntactic form of a
6287 // function declarator to have a function type, the program
6288 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006289 if (!T->isFunctionType()) {
6290 Diag(Loc, diag::err_unexpected_friend);
6291
6292 // It might be worthwhile to try to recover by creating an
6293 // appropriate declaration.
6294 return DeclPtrTy();
6295 }
6296
6297 // C++ [namespace.memdef]p3
6298 // - If a friend declaration in a non-local class first declares a
6299 // class or function, the friend class or function is a member
6300 // of the innermost enclosing namespace.
6301 // - The name of the friend is not found by simple name lookup
6302 // until a matching declaration is provided in that namespace
6303 // scope (either before or after the class declaration granting
6304 // friendship).
6305 // - If a friend function is called, its name may be found by the
6306 // name lookup that considers functions from namespaces and
6307 // classes associated with the types of the function arguments.
6308 // - When looking for a prior declaration of a class or a function
6309 // declared as a friend, scopes outside the innermost enclosing
6310 // namespace scope are not considered.
6311
John McCallaa74a0c2009-08-28 07:59:38 +00006312 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006313 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6314 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006315 assert(Name);
6316
John McCall07e91c02009-08-06 02:15:43 +00006317 // The context we found the declaration in, or in which we should
6318 // create the declaration.
6319 DeclContext *DC;
6320
6321 // FIXME: handle local classes
6322
6323 // Recover from invalid scope qualifiers as if they just weren't there.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006324 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006325 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006326 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
6327 DC = computeDeclContext(ScopeQual);
6328
6329 // FIXME: handle dependent contexts
6330 if (!DC) return DeclPtrTy();
John McCall0b66eb32010-05-01 00:40:08 +00006331 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00006332
John McCall1f82f242009-11-18 22:49:29 +00006333 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006334
John McCall45831862010-05-28 01:41:47 +00006335 // Ignore things found implicitly in the wrong scope.
John McCall07e91c02009-08-06 02:15:43 +00006336 // TODO: better diagnostics for this case. Suggesting the right
6337 // qualified scope would be nice...
John McCall45831862010-05-28 01:41:47 +00006338 LookupResult::Filter F = Previous.makeFilter();
6339 while (F.hasNext()) {
6340 NamedDecl *D = F.next();
6341 if (!D->getDeclContext()->getLookupContext()->Equals(DC))
6342 F.erase();
6343 }
6344 F.done();
6345
6346 if (Previous.empty()) {
John McCallaa74a0c2009-08-28 07:59:38 +00006347 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00006348 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6349 return DeclPtrTy();
6350 }
6351
6352 // C++ [class.friend]p1: A friend of a class is a function or
6353 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006354 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00006355 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6356
John McCall07e91c02009-08-06 02:15:43 +00006357 // Otherwise walk out to the nearest namespace scope looking for matches.
6358 } else {
6359 // TODO: handle local class contexts.
6360
6361 DC = CurContext;
6362 while (true) {
6363 // Skip class contexts. If someone can cite chapter and verse
6364 // for this behavior, that would be nice --- it's what GCC and
6365 // EDG do, and it seems like a reasonable intent, but the spec
6366 // really only says that checks for unqualified existing
6367 // declarations should stop at the nearest enclosing namespace,
6368 // not that they should only consider the nearest enclosing
6369 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006370 while (DC->isRecord())
6371 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006372
John McCall1f82f242009-11-18 22:49:29 +00006373 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006374
6375 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00006376 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006377 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006378
John McCall07e91c02009-08-06 02:15:43 +00006379 if (DC->isFileContext()) break;
6380 DC = DC->getParent();
6381 }
6382
6383 // C++ [class.friend]p1: A friend of a class is a function or
6384 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006385 // C++0x changes this for both friend types and functions.
6386 // Most C++ 98 compilers do seem to give an error here, so
6387 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006388 if (!Previous.empty() && DC->Equals(CurContext)
6389 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006390 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6391 }
6392
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006393 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00006394 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006395 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6396 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6397 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006398 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006399 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6400 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00006401 return DeclPtrTy();
6402 }
John McCall07e91c02009-08-06 02:15:43 +00006403 }
6404
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006405 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00006406 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006407 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006408 IsDefinition,
6409 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00006410 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00006411
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006412 assert(ND->getDeclContext() == DC);
6413 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006414
John McCall759e32b2009-08-31 22:39:49 +00006415 // Add the function declaration to the appropriate lookup tables,
6416 // adjusting the redeclarations list as necessary. We don't
6417 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006418 //
John McCall759e32b2009-08-31 22:39:49 +00006419 // Also update the scope-based lookup if the target context's
6420 // lookup context is in lexical scope.
6421 if (!CurContext->isDependentContext()) {
6422 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006423 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006424 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006425 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006426 }
John McCallaa74a0c2009-08-28 07:59:38 +00006427
6428 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006429 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006430 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006431 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006432 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006433
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006434 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00006435}
6436
Chris Lattner83f095c2009-03-28 19:18:32 +00006437void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006438 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006439
Chris Lattner83f095c2009-03-28 19:18:32 +00006440 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00006441 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6442 if (!Fn) {
6443 Diag(DelLoc, diag::err_deleted_non_function);
6444 return;
6445 }
6446 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6447 Diag(DelLoc, diag::err_deleted_decl_not_first);
6448 Diag(Prev->getLocation(), diag::note_previous_declaration);
6449 // If the declaration wasn't the first, we delete the function anyway for
6450 // recovery.
6451 }
6452 Fn->setDeleted();
6453}
Sebastian Redl4c018662009-04-27 21:33:24 +00006454
6455static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6456 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6457 ++CI) {
6458 Stmt *SubStmt = *CI;
6459 if (!SubStmt)
6460 continue;
6461 if (isa<ReturnStmt>(SubStmt))
6462 Self.Diag(SubStmt->getSourceRange().getBegin(),
6463 diag::err_return_in_constructor_handler);
6464 if (!isa<Expr>(SubStmt))
6465 SearchForReturnInStmt(Self, SubStmt);
6466 }
6467}
6468
6469void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6470 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6471 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6472 SearchForReturnInStmt(*this, Handler);
6473 }
6474}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006475
Mike Stump11289f42009-09-09 15:08:12 +00006476bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006477 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006478 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6479 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006480
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006481 if (Context.hasSameType(NewTy, OldTy) ||
6482 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006483 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006484
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006485 // Check if the return types are covariant
6486 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006487
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006488 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006489 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6490 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006491 NewClassTy = NewPT->getPointeeType();
6492 OldClassTy = OldPT->getPointeeType();
6493 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006494 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6495 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6496 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6497 NewClassTy = NewRT->getPointeeType();
6498 OldClassTy = OldRT->getPointeeType();
6499 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006500 }
6501 }
Mike Stump11289f42009-09-09 15:08:12 +00006502
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006503 // The return types aren't either both pointers or references to a class type.
6504 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006505 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006506 diag::err_different_return_type_for_overriding_virtual_function)
6507 << New->getDeclName() << NewTy << OldTy;
6508 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006509
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006510 return true;
6511 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006512
Anders Carlssone60365b2009-12-31 18:34:24 +00006513 // C++ [class.virtual]p6:
6514 // If the return type of D::f differs from the return type of B::f, the
6515 // class type in the return type of D::f shall be complete at the point of
6516 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006517 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6518 if (!RT->isBeingDefined() &&
6519 RequireCompleteType(New->getLocation(), NewClassTy,
6520 PDiag(diag::err_covariant_return_incomplete)
6521 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006522 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006523 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006524
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006525 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006526 // Check if the new class derives from the old class.
6527 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6528 Diag(New->getLocation(),
6529 diag::err_covariant_return_not_derived)
6530 << New->getDeclName() << NewTy << OldTy;
6531 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6532 return true;
6533 }
Mike Stump11289f42009-09-09 15:08:12 +00006534
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006535 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006536 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006537 diag::err_covariant_return_inaccessible_base,
6538 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6539 // FIXME: Should this point to the return type?
6540 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006541 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6542 return true;
6543 }
6544 }
Mike Stump11289f42009-09-09 15:08:12 +00006545
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006546 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006547 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006548 Diag(New->getLocation(),
6549 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006550 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006551 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6552 return true;
6553 };
Mike Stump11289f42009-09-09 15:08:12 +00006554
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006555
6556 // The new class type must have the same or less qualifiers as the old type.
6557 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6558 Diag(New->getLocation(),
6559 diag::err_covariant_return_type_class_type_more_qualified)
6560 << New->getDeclName() << NewTy << OldTy;
6561 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6562 return true;
6563 };
Mike Stump11289f42009-09-09 15:08:12 +00006564
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006565 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006566}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006567
Alexis Hunt96d5c762009-11-21 08:43:09 +00006568bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6569 const CXXMethodDecl *Old)
6570{
6571 if (Old->hasAttr<FinalAttr>()) {
6572 Diag(New->getLocation(), diag::err_final_function_overridden)
6573 << New->getDeclName();
6574 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6575 return true;
6576 }
6577
6578 return false;
6579}
6580
Douglas Gregor21920e372009-12-01 17:24:26 +00006581/// \brief Mark the given method pure.
6582///
6583/// \param Method the method to be marked pure.
6584///
6585/// \param InitRange the source range that covers the "0" initializer.
6586bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6587 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6588 Method->setPure();
6589
6590 // A class is abstract if at least one function is pure virtual.
6591 Method->getParent()->setAbstract(true);
6592 return false;
6593 }
6594
6595 if (!Method->isInvalidDecl())
6596 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6597 << Method->getDeclName() << InitRange;
6598 return true;
6599}
6600
John McCall1f4ee7b2009-12-19 09:28:58 +00006601/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6602/// an initializer for the out-of-line declaration 'Dcl'. The scope
6603/// is a fresh scope pushed for just this purpose.
6604///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006605/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6606/// static data member of class X, names should be looked up in the scope of
6607/// class X.
6608void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006609 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006610 Decl *D = Dcl.getAs<Decl>();
6611 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006612
John McCall1f4ee7b2009-12-19 09:28:58 +00006613 // We should only get called for declarations with scope specifiers, like:
6614 // int foo::bar;
6615 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006616 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006617}
6618
6619/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall1f4ee7b2009-12-19 09:28:58 +00006620/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006621void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006622 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006623 Decl *D = Dcl.getAs<Decl>();
6624 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006625
John McCall1f4ee7b2009-12-19 09:28:58 +00006626 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006627 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006628}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006629
6630/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6631/// C++ if/switch/while/for statement.
6632/// e.g: "if (int x = f()) {...}"
6633Action::DeclResult
6634Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
6635 // C++ 6.4p2:
6636 // The declarator shall not specify a function or an array.
6637 // The type-specifier-seq shall not contain typedef and shall not declare a
6638 // new class or enumeration.
6639 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6640 "Parser allowed 'typedef' as storage class of condition decl.");
6641
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006642 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006643 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6644 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006645
6646 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6647 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6648 // would be created and CXXConditionDeclExpr wants a VarDecl.
6649 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6650 << D.getSourceRange();
6651 return DeclResult();
6652 } else if (OwnedTag && OwnedTag->isDefinition()) {
6653 // The type-specifier-seq shall not declare a new class or enumeration.
6654 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6655 }
6656
6657 DeclPtrTy Dcl = ActOnDeclarator(S, D);
6658 if (!Dcl)
6659 return DeclResult();
6660
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006661 return Dcl;
6662}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006663
Douglas Gregor88d292c2010-05-13 16:44:06 +00006664void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6665 bool DefinitionRequired) {
6666 // Ignore any vtable uses in unevaluated operands or for classes that do
6667 // not have a vtable.
6668 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6669 CurContext->isDependentContext() ||
6670 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006671 return;
6672
Douglas Gregor88d292c2010-05-13 16:44:06 +00006673 // Try to insert this class into the map.
6674 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6675 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6676 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6677 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006678 // If we already had an entry, check to see if we are promoting this vtable
6679 // to required a definition. If so, we need to reappend to the VTableUses
6680 // list, since we may have already processed the first entry.
6681 if (DefinitionRequired && !Pos.first->second) {
6682 Pos.first->second = true;
6683 } else {
6684 // Otherwise, we can early exit.
6685 return;
6686 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006687 }
6688
6689 // Local classes need to have their virtual members marked
6690 // immediately. For all other classes, we mark their virtual members
6691 // at the end of the translation unit.
6692 if (Class->isLocalClass())
6693 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006694 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006695 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006696}
6697
Douglas Gregor88d292c2010-05-13 16:44:06 +00006698bool Sema::DefineUsedVTables() {
6699 // If any dynamic classes have their key function defined within
6700 // this translation unit, then those vtables are considered "used" and must
6701 // be emitted.
6702 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6703 if (const CXXMethodDecl *KeyFunction
6704 = Context.getKeyFunction(DynamicClasses[I])) {
6705 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006706 if (KeyFunction->hasBody(Definition))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006707 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6708 }
6709 }
6710
6711 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006712 return false;
6713
Douglas Gregor88d292c2010-05-13 16:44:06 +00006714 // Note: The VTableUses vector could grow as a result of marking
6715 // the members of a class as "used", so we check the size each
6716 // time through the loop and prefer indices (with are stable) to
6717 // iterators (which are not).
6718 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00006719 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006720 if (!Class)
6721 continue;
6722
6723 SourceLocation Loc = VTableUses[I].second;
6724
6725 // If this class has a key function, but that key function is
6726 // defined in another translation unit, we don't need to emit the
6727 // vtable even though we're using it.
6728 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006729 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006730 switch (KeyFunction->getTemplateSpecializationKind()) {
6731 case TSK_Undeclared:
6732 case TSK_ExplicitSpecialization:
6733 case TSK_ExplicitInstantiationDeclaration:
6734 // The key function is in another translation unit.
6735 continue;
6736
6737 case TSK_ExplicitInstantiationDefinition:
6738 case TSK_ImplicitInstantiation:
6739 // We will be instantiating the key function.
6740 break;
6741 }
6742 } else if (!KeyFunction) {
6743 // If we have a class with no key function that is the subject
6744 // of an explicit instantiation declaration, suppress the
6745 // vtable; it will live with the explicit instantiation
6746 // definition.
6747 bool IsExplicitInstantiationDeclaration
6748 = Class->getTemplateSpecializationKind()
6749 == TSK_ExplicitInstantiationDeclaration;
6750 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6751 REnd = Class->redecls_end();
6752 R != REnd; ++R) {
6753 TemplateSpecializationKind TSK
6754 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6755 if (TSK == TSK_ExplicitInstantiationDeclaration)
6756 IsExplicitInstantiationDeclaration = true;
6757 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6758 IsExplicitInstantiationDeclaration = false;
6759 break;
6760 }
6761 }
6762
6763 if (IsExplicitInstantiationDeclaration)
6764 continue;
6765 }
6766
6767 // Mark all of the virtual members of this class as referenced, so
6768 // that we can build a vtable. Then, tell the AST consumer that a
6769 // vtable for this class is required.
6770 MarkVirtualMembersReferenced(Loc, Class);
6771 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6772 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6773
6774 // Optionally warn if we're emitting a weak vtable.
6775 if (Class->getLinkage() == ExternalLinkage &&
6776 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006777 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006778 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6779 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00006780 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006781 VTableUses.clear();
6782
Anders Carlsson82fccd02009-12-07 08:24:59 +00006783 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006784}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006785
Rafael Espindola5b334082010-03-26 00:36:59 +00006786void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6787 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006788 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6789 e = RD->method_end(); i != e; ++i) {
6790 CXXMethodDecl *MD = *i;
6791
6792 // C++ [basic.def.odr]p2:
6793 // [...] A virtual member function is used if it is not pure. [...]
6794 if (MD->isVirtual() && !MD->isPure())
6795 MarkDeclarationReferenced(Loc, MD);
6796 }
Rafael Espindola5b334082010-03-26 00:36:59 +00006797
6798 // Only classes that have virtual bases need a VTT.
6799 if (RD->getNumVBases() == 0)
6800 return;
6801
6802 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6803 e = RD->bases_end(); i != e; ++i) {
6804 const CXXRecordDecl *Base =
6805 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00006806 if (Base->getNumVBases() == 0)
6807 continue;
6808 MarkVirtualMembersReferenced(Loc, Base);
6809 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006810}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006811
6812/// SetIvarInitializers - This routine builds initialization ASTs for the
6813/// Objective-C implementation whose ivars need be initialized.
6814void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6815 if (!getLangOptions().CPlusPlus)
6816 return;
6817 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
6818 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6819 CollectIvarsToConstructOrDestruct(OID, ivars);
6820 if (ivars.empty())
6821 return;
6822 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6823 for (unsigned i = 0; i < ivars.size(); i++) {
6824 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00006825 if (Field->isInvalidDecl())
6826 continue;
6827
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006828 CXXBaseOrMemberInitializer *Member;
6829 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6830 InitializationKind InitKind =
6831 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6832
6833 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6834 Sema::OwningExprResult MemberInit =
6835 InitSeq.Perform(*this, InitEntity, InitKind,
6836 Sema::MultiExprArg(*this, 0, 0));
6837 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6838 // Note, MemberInit could actually come back empty if no initialization
6839 // is required (e.g., because it would call a trivial default constructor)
6840 if (!MemberInit.get() || MemberInit.isInvalid())
6841 continue;
6842
6843 Member =
6844 new (Context) CXXBaseOrMemberInitializer(Context,
6845 Field, SourceLocation(),
6846 SourceLocation(),
6847 MemberInit.takeAs<Expr>(),
6848 SourceLocation());
6849 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00006850
6851 // Be sure that the destructor is accessible and is marked as referenced.
6852 if (const RecordType *RecordTy
6853 = Context.getBaseElementType(Field->getType())
6854 ->getAs<RecordType>()) {
6855 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00006856 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00006857 MarkDeclarationReferenced(Field->getLocation(), Destructor);
6858 CheckDestructorAccess(Field->getLocation(), Destructor,
6859 PDiag(diag::err_access_dtor_ivar)
6860 << Context.getBaseElementType(Field->getType()));
6861 }
6862 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006863 }
6864 ObjCImplementation->setIvarInitializers(Context,
6865 AllToInit.data(), AllToInit.size());
6866 }
6867}