blob: a1a84667595f799da3070817a16af184b9973d96 [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;
1801 }
1802 }
1803
1804 // Fallthrough and construct a default initializer for the union as
1805 // a whole, which can call its default constructor if such a thing exists
1806 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1807 // behavior going forward with C++0x, when anonymous unions there are
1808 // finalized, we should revisit this.
1809 } else {
1810 // For structs, we simply descend through to initialize all members where
1811 // necessary.
1812 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1813 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1814 if (CollectFieldInitializer(Info, Top, *FA))
1815 return true;
1816 }
1817 }
John McCallbc83b3f2010-05-20 23:23:51 +00001818 }
1819
1820 // Don't try to build an implicit initializer if there were semantic
1821 // errors in any of the initializers (and therefore we might be
1822 // missing some that the user actually wrote).
1823 if (Info.AnyErrorsInInits)
1824 return false;
1825
1826 CXXBaseOrMemberInitializer *Init = 0;
1827 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1828 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001829
Chandler Carruth139e9622010-06-30 02:59:29 +00001830 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001831 return false;
1832}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001833
Eli Friedman9cf6b592009-11-09 19:20:36 +00001834bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001835Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001836 CXXBaseOrMemberInitializer **Initializers,
1837 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001838 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001839 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001840 // Just store the initializers as written, they will be checked during
1841 // instantiation.
1842 if (NumInitializers > 0) {
1843 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1844 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1845 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1846 memcpy(baseOrMemberInitializers, Initializers,
1847 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1848 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1849 }
1850
1851 return false;
1852 }
1853
John McCallbc83b3f2010-05-20 23:23:51 +00001854 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001855
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001856 // We need to build the initializer AST according to order of construction
1857 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001858 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001859 if (!ClassDecl)
1860 return true;
1861
Eli Friedman9cf6b592009-11-09 19:20:36 +00001862 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001863
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001864 for (unsigned i = 0; i < NumInitializers; i++) {
1865 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001866
1867 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001868 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001869 else
John McCallbc83b3f2010-05-20 23:23:51 +00001870 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001871 }
1872
Anders Carlsson43c64af2010-04-21 19:52:01 +00001873 // Keep track of the direct virtual bases.
1874 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1875 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1876 E = ClassDecl->bases_end(); I != E; ++I) {
1877 if (I->isVirtual())
1878 DirectVBases.insert(I);
1879 }
1880
Anders Carlssondb0a9652010-04-02 06:26:44 +00001881 // Push virtual bases before others.
1882 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1883 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1884
1885 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001886 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1887 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001888 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001889 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001890 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001891 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001892 VBase, IsInheritedVirtualBase,
1893 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001894 HadError = true;
1895 continue;
1896 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001897
John McCallbc83b3f2010-05-20 23:23:51 +00001898 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001899 }
1900 }
Mike Stump11289f42009-09-09 15:08:12 +00001901
John McCallbc83b3f2010-05-20 23:23:51 +00001902 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001903 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1904 E = ClassDecl->bases_end(); Base != E; ++Base) {
1905 // Virtuals are in the virtual base list and already constructed.
1906 if (Base->isVirtual())
1907 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001908
Anders Carlssondb0a9652010-04-02 06:26:44 +00001909 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001910 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1911 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001912 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001913 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001914 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001915 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001916 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001917 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001918 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001919 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001920
John McCallbc83b3f2010-05-20 23:23:51 +00001921 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001922 }
1923 }
Mike Stump11289f42009-09-09 15:08:12 +00001924
John McCallbc83b3f2010-05-20 23:23:51 +00001925 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001926 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001927 E = ClassDecl->field_end(); Field != E; ++Field) {
1928 if ((*Field)->getType()->isIncompleteArrayType()) {
1929 assert(ClassDecl->hasFlexibleArrayMember() &&
1930 "Incomplete array type is not valid");
1931 continue;
1932 }
John McCallbc83b3f2010-05-20 23:23:51 +00001933 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001934 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001935 }
Mike Stump11289f42009-09-09 15:08:12 +00001936
John McCallbc83b3f2010-05-20 23:23:51 +00001937 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001938 if (NumInitializers > 0) {
1939 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1940 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1941 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001942 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001943 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001944 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001945
John McCalla6309952010-03-16 21:39:52 +00001946 // Constructors implicitly reference the base and member
1947 // destructors.
1948 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1949 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001950 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001951
1952 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001953}
1954
Eli Friedman952c15d2009-07-21 19:28:10 +00001955static void *GetKeyForTopLevelField(FieldDecl *Field) {
1956 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001957 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001958 if (RT->getDecl()->isAnonymousStructOrUnion())
1959 return static_cast<void *>(RT->getDecl());
1960 }
1961 return static_cast<void *>(Field);
1962}
1963
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001964static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1965 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001966}
1967
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001968static void *GetKeyForMember(ASTContext &Context,
1969 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001970 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001971 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001972 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001973
Eli Friedman952c15d2009-07-21 19:28:10 +00001974 // For fields injected into the class via declaration of an anonymous union,
1975 // use its anonymous union class declaration as the unique key.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001976 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001977
Anders Carlssona942dcd2010-03-30 15:39:27 +00001978 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1979 // data member of the class. Data member used in the initializer list is
1980 // in AnonUnionMember field.
1981 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1982 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001983
John McCall23eebd92010-04-10 09:28:51 +00001984 // If the field is a member of an anonymous struct or union, our key
1985 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001986 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001987 if (RD->isAnonymousStructOrUnion()) {
1988 while (true) {
1989 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1990 if (Parent->isAnonymousStructOrUnion())
1991 RD = Parent;
1992 else
1993 break;
1994 }
1995
Anders Carlsson83ac3122010-03-30 16:19:37 +00001996 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001997 }
Mike Stump11289f42009-09-09 15:08:12 +00001998
Anders Carlssona942dcd2010-03-30 15:39:27 +00001999 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00002000}
2001
Anders Carlssone857b292010-04-02 03:37:03 +00002002static void
2003DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002004 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00002005 CXXBaseOrMemberInitializer **Inits,
2006 unsigned NumInits) {
2007 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00002008 return;
Mike Stump11289f42009-09-09 15:08:12 +00002009
John McCallbb7b6582010-04-10 07:37:23 +00002010 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
2011 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00002012 return;
Anders Carlssone857b292010-04-02 03:37:03 +00002013
John McCallbb7b6582010-04-10 07:37:23 +00002014 // Build the list of bases and members in the order that they'll
2015 // actually be initialized. The explicit initializers should be in
2016 // this same order but may be missing things.
2017 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00002018
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002019 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2020
John McCallbb7b6582010-04-10 07:37:23 +00002021 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002022 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00002023 ClassDecl->vbases_begin(),
2024 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00002025 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00002026
John McCallbb7b6582010-04-10 07:37:23 +00002027 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00002028 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00002029 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00002030 if (Base->isVirtual())
2031 continue;
John McCallbb7b6582010-04-10 07:37:23 +00002032 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00002033 }
Mike Stump11289f42009-09-09 15:08:12 +00002034
John McCallbb7b6582010-04-10 07:37:23 +00002035 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00002036 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2037 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00002038 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00002039
John McCallbb7b6582010-04-10 07:37:23 +00002040 unsigned NumIdealInits = IdealInitKeys.size();
2041 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002042
John McCallbb7b6582010-04-10 07:37:23 +00002043 CXXBaseOrMemberInitializer *PrevInit = 0;
2044 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2045 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2046 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2047
2048 // Scan forward to try to find this initializer in the idealized
2049 // initializers list.
2050 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2051 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002052 break;
John McCallbb7b6582010-04-10 07:37:23 +00002053
2054 // If we didn't find this initializer, it must be because we
2055 // scanned past it on a previous iteration. That can only
2056 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002057 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002058 Sema::SemaDiagnosticBuilder D =
2059 SemaRef.Diag(PrevInit->getSourceLocation(),
2060 diag::warn_initializer_out_of_order);
2061
2062 if (PrevInit->isMemberInitializer())
2063 D << 0 << PrevInit->getMember()->getDeclName();
2064 else
2065 D << 1 << PrevInit->getBaseClassInfo()->getType();
2066
2067 if (Init->isMemberInitializer())
2068 D << 0 << Init->getMember()->getDeclName();
2069 else
2070 D << 1 << Init->getBaseClassInfo()->getType();
2071
2072 // Move back to the initializer's location in the ideal list.
2073 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2074 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002075 break;
John McCallbb7b6582010-04-10 07:37:23 +00002076
2077 assert(IdealIndex != NumIdealInits &&
2078 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002079 }
John McCallbb7b6582010-04-10 07:37:23 +00002080
2081 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002082 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002083}
2084
John McCall23eebd92010-04-10 09:28:51 +00002085namespace {
2086bool CheckRedundantInit(Sema &S,
2087 CXXBaseOrMemberInitializer *Init,
2088 CXXBaseOrMemberInitializer *&PrevInit) {
2089 if (!PrevInit) {
2090 PrevInit = Init;
2091 return false;
2092 }
2093
2094 if (FieldDecl *Field = Init->getMember())
2095 S.Diag(Init->getSourceLocation(),
2096 diag::err_multiple_mem_initialization)
2097 << Field->getDeclName()
2098 << Init->getSourceRange();
2099 else {
2100 Type *BaseClass = Init->getBaseClass();
2101 assert(BaseClass && "neither field nor base");
2102 S.Diag(Init->getSourceLocation(),
2103 diag::err_multiple_base_initialization)
2104 << QualType(BaseClass, 0)
2105 << Init->getSourceRange();
2106 }
2107 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2108 << 0 << PrevInit->getSourceRange();
2109
2110 return true;
2111}
2112
2113typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2114typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2115
2116bool CheckRedundantUnionInit(Sema &S,
2117 CXXBaseOrMemberInitializer *Init,
2118 RedundantUnionMap &Unions) {
2119 FieldDecl *Field = Init->getMember();
2120 RecordDecl *Parent = Field->getParent();
2121 if (!Parent->isAnonymousStructOrUnion())
2122 return false;
2123
2124 NamedDecl *Child = Field;
2125 do {
2126 if (Parent->isUnion()) {
2127 UnionEntry &En = Unions[Parent];
2128 if (En.first && En.first != Child) {
2129 S.Diag(Init->getSourceLocation(),
2130 diag::err_multiple_mem_union_initialization)
2131 << Field->getDeclName()
2132 << Init->getSourceRange();
2133 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2134 << 0 << En.second->getSourceRange();
2135 return true;
2136 } else if (!En.first) {
2137 En.first = Child;
2138 En.second = Init;
2139 }
2140 }
2141
2142 Child = Parent;
2143 Parent = cast<RecordDecl>(Parent->getDeclContext());
2144 } while (Parent->isAnonymousStructOrUnion());
2145
2146 return false;
2147}
2148}
2149
Anders Carlssone857b292010-04-02 03:37:03 +00002150/// ActOnMemInitializers - Handle the member initializers for a constructor.
2151void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
2152 SourceLocation ColonLoc,
2153 MemInitTy **meminits, unsigned NumMemInits,
2154 bool AnyErrors) {
2155 if (!ConstructorDecl)
2156 return;
2157
2158 AdjustDeclIfTemplate(ConstructorDecl);
2159
2160 CXXConstructorDecl *Constructor
2161 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2162
2163 if (!Constructor) {
2164 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2165 return;
2166 }
2167
2168 CXXBaseOrMemberInitializer **MemInits =
2169 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002170
2171 // Mapping for the duplicate initializers check.
2172 // For member initializers, this is keyed with a FieldDecl*.
2173 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002174 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002175
2176 // Mapping for the inconsistent anonymous-union initializers check.
2177 RedundantUnionMap MemberUnions;
2178
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002179 bool HadError = false;
2180 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002181 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002182
Abramo Bagnara341d7832010-05-26 18:09:23 +00002183 // Set the source order index.
2184 Init->setSourceOrder(i);
2185
John McCall23eebd92010-04-10 09:28:51 +00002186 if (Init->isMemberInitializer()) {
2187 FieldDecl *Field = Init->getMember();
2188 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2189 CheckRedundantUnionInit(*this, Init, MemberUnions))
2190 HadError = true;
2191 } else {
2192 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2193 if (CheckRedundantInit(*this, Init, Members[Key]))
2194 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002195 }
Anders Carlssone857b292010-04-02 03:37:03 +00002196 }
2197
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002198 if (HadError)
2199 return;
2200
Anders Carlssone857b292010-04-02 03:37:03 +00002201 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002202
2203 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002204}
2205
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002206void
John McCalla6309952010-03-16 21:39:52 +00002207Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2208 CXXRecordDecl *ClassDecl) {
2209 // Ignore dependent contexts.
2210 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002211 return;
John McCall1064d7e2010-03-16 05:22:47 +00002212
2213 // FIXME: all the access-control diagnostics are positioned on the
2214 // field/base declaration. That's probably good; that said, the
2215 // user might reasonably want to know why the destructor is being
2216 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002217
Anders Carlssondee9a302009-11-17 04:44:12 +00002218 // Non-static data members.
2219 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2220 E = ClassDecl->field_end(); I != E; ++I) {
2221 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002222 if (Field->isInvalidDecl())
2223 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002224 QualType FieldType = Context.getBaseElementType(Field->getType());
2225
2226 const RecordType* RT = FieldType->getAs<RecordType>();
2227 if (!RT)
2228 continue;
2229
2230 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2231 if (FieldClassDecl->hasTrivialDestructor())
2232 continue;
2233
Douglas Gregore71edda2010-07-01 22:47:18 +00002234 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002235 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002236 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002237 << Field->getDeclName()
2238 << FieldType);
2239
John McCalla6309952010-03-16 21:39:52 +00002240 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002241 }
2242
John McCall1064d7e2010-03-16 05:22:47 +00002243 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2244
Anders Carlssondee9a302009-11-17 04:44:12 +00002245 // Bases.
2246 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2247 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002248 // Bases are always records in a well-formed non-dependent class.
2249 const RecordType *RT = Base->getType()->getAs<RecordType>();
2250
2251 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002252 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002253 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002254
2255 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002256 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002257 if (BaseClassDecl->hasTrivialDestructor())
2258 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002259
Douglas Gregore71edda2010-07-01 22:47:18 +00002260 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002261
2262 // FIXME: caret should be on the start of the class name
2263 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002264 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002265 << Base->getType()
2266 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002267
John McCalla6309952010-03-16 21:39:52 +00002268 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002269 }
2270
2271 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002272 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2273 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002274
2275 // Bases are always records in a well-formed non-dependent class.
2276 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2277
2278 // Ignore direct virtual bases.
2279 if (DirectVirtualBases.count(RT))
2280 continue;
2281
Anders Carlssondee9a302009-11-17 04:44:12 +00002282 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002283 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002284 if (BaseClassDecl->hasTrivialDestructor())
2285 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002286
Douglas Gregore71edda2010-07-01 22:47:18 +00002287 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002288 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002289 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002290 << VBase->getType());
2291
John McCalla6309952010-03-16 21:39:52 +00002292 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002293 }
2294}
2295
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00002296void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002297 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002298 return;
Mike Stump11289f42009-09-09 15:08:12 +00002299
Mike Stump11289f42009-09-09 15:08:12 +00002300 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002301 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002302 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002303}
2304
Mike Stump11289f42009-09-09 15:08:12 +00002305bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002306 unsigned DiagID, AbstractDiagSelID SelID,
2307 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002308 if (SelID == -1)
2309 return RequireNonAbstractType(Loc, T,
2310 PDiag(DiagID), CurrentRD);
2311 else
2312 return RequireNonAbstractType(Loc, T,
2313 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002314}
2315
Anders Carlssoneabf7702009-08-27 00:13:57 +00002316bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2317 const PartialDiagnostic &PD,
2318 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002319 if (!getLangOptions().CPlusPlus)
2320 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002321
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002322 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002323 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002324 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002325
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002326 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002327 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002328 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002329 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002330
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002331 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002332 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002333 }
Mike Stump11289f42009-09-09 15:08:12 +00002334
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002335 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002336 if (!RT)
2337 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002338
John McCall67da35c2010-02-04 22:26:26 +00002339 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002340
Anders Carlssonb57738b2009-03-24 17:23:42 +00002341 if (CurrentRD && CurrentRD != RD)
2342 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002343
John McCall67da35c2010-02-04 22:26:26 +00002344 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002345 if (!RD->getDefinition())
John McCall67da35c2010-02-04 22:26:26 +00002346 return false;
2347
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002348 if (!RD->isAbstract())
2349 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002350
Anders Carlssoneabf7702009-08-27 00:13:57 +00002351 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002352
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002353 // Check if we've already emitted the list of pure virtual functions for this
2354 // class.
2355 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2356 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002357
Douglas Gregor4165bd62010-03-23 23:47:56 +00002358 CXXFinalOverriderMap FinalOverriders;
2359 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002360
Anders Carlssona2f74f32010-06-03 01:00:02 +00002361 // Keep a set of seen pure methods so we won't diagnose the same method
2362 // more than once.
2363 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2364
Douglas Gregor4165bd62010-03-23 23:47:56 +00002365 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2366 MEnd = FinalOverriders.end();
2367 M != MEnd;
2368 ++M) {
2369 for (OverridingMethods::iterator SO = M->second.begin(),
2370 SOEnd = M->second.end();
2371 SO != SOEnd; ++SO) {
2372 // C++ [class.abstract]p4:
2373 // A class is abstract if it contains or inherits at least one
2374 // pure virtual function for which the final overrider is pure
2375 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002376
Douglas Gregor4165bd62010-03-23 23:47:56 +00002377 //
2378 if (SO->second.size() != 1)
2379 continue;
2380
2381 if (!SO->second.front().Method->isPure())
2382 continue;
2383
Anders Carlssona2f74f32010-06-03 01:00:02 +00002384 if (!SeenPureMethods.insert(SO->second.front().Method))
2385 continue;
2386
Douglas Gregor4165bd62010-03-23 23:47:56 +00002387 Diag(SO->second.front().Method->getLocation(),
2388 diag::note_pure_virtual_function)
2389 << SO->second.front().Method->getDeclName();
2390 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002391 }
2392
2393 if (!PureVirtualClassDiagSet)
2394 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2395 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002396
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002397 return true;
2398}
2399
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002400namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00002401 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002402 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2403 Sema &SemaRef;
2404 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00002405
Anders Carlssonb57738b2009-03-24 17:23:42 +00002406 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002407 bool Invalid = false;
2408
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002409 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2410 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002411 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002412
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002413 return Invalid;
2414 }
Mike Stump11289f42009-09-09 15:08:12 +00002415
Anders Carlssonb57738b2009-03-24 17:23:42 +00002416 public:
2417 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2418 : SemaRef(SemaRef), AbstractClass(ac) {
2419 Visit(SemaRef.Context.getTranslationUnitDecl());
2420 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002421
Anders Carlssonb57738b2009-03-24 17:23:42 +00002422 bool VisitFunctionDecl(const FunctionDecl *FD) {
2423 if (FD->isThisDeclarationADefinition()) {
2424 // No need to do the check if we're in a definition, because it requires
2425 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00002426 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00002427 return VisitDeclContext(FD);
2428 }
Mike Stump11289f42009-09-09 15:08:12 +00002429
Anders Carlssonb57738b2009-03-24 17:23:42 +00002430 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00002431 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00002432 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00002433 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2434 diag::err_abstract_type_in_decl,
2435 Sema::AbstractReturnType,
2436 AbstractClass);
2437
Mike Stump11289f42009-09-09 15:08:12 +00002438 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00002439 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002440 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002441 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002442 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002443 VD->getOriginalType(),
2444 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002445 Sema::AbstractParamType,
2446 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002447 }
2448
2449 return Invalid;
2450 }
Mike Stump11289f42009-09-09 15:08:12 +00002451
Anders Carlssonb57738b2009-03-24 17:23:42 +00002452 bool VisitDecl(const Decl* D) {
2453 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2454 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00002455
Anders Carlssonb57738b2009-03-24 17:23:42 +00002456 return false;
2457 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002458 };
2459}
2460
Douglas Gregorc99f1552009-12-03 18:33:45 +00002461/// \brief Perform semantic checks on a class definition that has been
2462/// completing, introducing implicitly-declared members, checking for
2463/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002464void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregorc99f1552009-12-03 18:33:45 +00002465 if (!Record || Record->isInvalidDecl())
2466 return;
2467
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002468 if (!Record->isDependentType())
Douglas Gregor0be31a22010-07-02 17:43:08 +00002469 AddImplicitlyDeclaredMembersToClass(Record);
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00002470
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002471 if (Record->isInvalidDecl())
2472 return;
2473
John McCall2cb94162010-01-28 07:38:46 +00002474 // Set access bits correctly on the directly-declared conversions.
2475 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2476 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2477 Convs->setAccess(I, (*I)->getAccess());
2478
Douglas Gregor4165bd62010-03-23 23:47:56 +00002479 // Determine whether we need to check for final overriders. We do
2480 // this either when there are virtual base classes (in which case we
2481 // may end up finding multiple final overriders for a given virtual
2482 // function) or any of the base classes is abstract (in which case
2483 // we might detect that this class is abstract).
2484 bool CheckFinalOverriders = false;
2485 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2486 !Record->isDependentType()) {
2487 if (Record->getNumVBases())
2488 CheckFinalOverriders = true;
2489 else if (!Record->isAbstract()) {
2490 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2491 BEnd = Record->bases_end();
2492 B != BEnd; ++B) {
2493 CXXRecordDecl *BaseDecl
2494 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2495 if (BaseDecl->isAbstract()) {
2496 CheckFinalOverriders = true;
2497 break;
2498 }
2499 }
2500 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002501 }
2502
Douglas Gregor4165bd62010-03-23 23:47:56 +00002503 if (CheckFinalOverriders) {
2504 CXXFinalOverriderMap FinalOverriders;
2505 Record->getFinalOverriders(FinalOverriders);
2506
2507 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2508 MEnd = FinalOverriders.end();
2509 M != MEnd; ++M) {
2510 for (OverridingMethods::iterator SO = M->second.begin(),
2511 SOEnd = M->second.end();
2512 SO != SOEnd; ++SO) {
2513 assert(SO->second.size() > 0 &&
2514 "All virtual functions have overridding virtual functions");
2515 if (SO->second.size() == 1) {
2516 // C++ [class.abstract]p4:
2517 // A class is abstract if it contains or inherits at least one
2518 // pure virtual function for which the final overrider is pure
2519 // virtual.
2520 if (SO->second.front().Method->isPure())
2521 Record->setAbstract(true);
2522 continue;
2523 }
2524
2525 // C++ [class.virtual]p2:
2526 // In a derived class, if a virtual member function of a base
2527 // class subobject has more than one final overrider the
2528 // program is ill-formed.
2529 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2530 << (NamedDecl *)M->first << Record;
2531 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2532 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2533 OMEnd = SO->second.end();
2534 OM != OMEnd; ++OM)
2535 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2536 << (NamedDecl *)M->first << OM->Method->getParent();
2537
2538 Record->setInvalidDecl();
2539 }
2540 }
2541 }
2542
2543 if (Record->isAbstract() && !Record->isInvalidDecl())
Douglas Gregorc99f1552009-12-03 18:33:45 +00002544 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor454a5b62010-04-15 00:00:53 +00002545
2546 // If this is not an aggregate type and has no user-declared constructor,
2547 // complain about any non-static data members of reference or const scalar
2548 // type, since they will never get initializers.
2549 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2550 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2551 bool Complained = false;
2552 for (RecordDecl::field_iterator F = Record->field_begin(),
2553 FEnd = Record->field_end();
2554 F != FEnd; ++F) {
2555 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002556 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002557 if (!Complained) {
2558 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2559 << Record->getTagKind() << Record;
2560 Complained = true;
2561 }
2562
2563 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2564 << F->getType()->isReferenceType()
2565 << F->getDeclName();
2566 }
2567 }
2568 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002569
2570 if (Record->isDynamicClass())
2571 DynamicClasses.push_back(Record);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002572}
2573
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002574void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002575 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002576 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002577 SourceLocation RBrac,
2578 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002579 if (!TagDecl)
2580 return;
Mike Stump11289f42009-09-09 15:08:12 +00002581
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002582 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002583
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002584 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002585 (DeclPtrTy*)FieldCollector->getCurFields(),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002586 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002587
Douglas Gregor0be31a22010-07-02 17:43:08 +00002588 CheckCompletedCXXClass(
2589 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002590}
2591
Douglas Gregor95755162010-07-01 05:10:53 +00002592namespace {
2593 /// \brief Helper class that collects exception specifications for
2594 /// implicitly-declared special member functions.
2595 class ImplicitExceptionSpecification {
2596 ASTContext &Context;
2597 bool AllowsAllExceptions;
2598 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2599 llvm::SmallVector<QualType, 4> Exceptions;
2600
2601 public:
2602 explicit ImplicitExceptionSpecification(ASTContext &Context)
2603 : Context(Context), AllowsAllExceptions(false) { }
2604
2605 /// \brief Whether the special member function should have any
2606 /// exception specification at all.
2607 bool hasExceptionSpecification() const {
2608 return !AllowsAllExceptions;
2609 }
2610
2611 /// \brief Whether the special member function should have a
2612 /// throw(...) exception specification (a Microsoft extension).
2613 bool hasAnyExceptionSpecification() const {
2614 return false;
2615 }
2616
2617 /// \brief The number of exceptions in the exception specification.
2618 unsigned size() const { return Exceptions.size(); }
2619
2620 /// \brief The set of exceptions in the exception specification.
2621 const QualType *data() const { return Exceptions.data(); }
2622
2623 /// \brief Note that
2624 void CalledDecl(CXXMethodDecl *Method) {
2625 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002626 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002627 return;
2628
2629 const FunctionProtoType *Proto
2630 = Method->getType()->getAs<FunctionProtoType>();
2631
2632 // If this function can throw any exceptions, make a note of that.
2633 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2634 AllowsAllExceptions = true;
2635 ExceptionsSeen.clear();
2636 Exceptions.clear();
2637 return;
2638 }
2639
2640 // Record the exceptions in this function's exception specification.
2641 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2642 EEnd = Proto->exception_end();
2643 E != EEnd; ++E)
2644 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2645 Exceptions.push_back(*E);
2646 }
2647 };
2648}
2649
2650
Douglas Gregor05379422008-11-03 17:51:48 +00002651/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2652/// special functions, such as the default constructor, copy
2653/// constructor, or destructor, to the given C++ class (C++
2654/// [special]p1). This routine can only be executed just before the
2655/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002656void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002657 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002658 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002659
Douglas Gregor54be3392010-07-01 17:57:27 +00002660 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002661 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002662
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002663 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2664 ++ASTContext::NumImplicitCopyAssignmentOperators;
2665
2666 // If we have a dynamic class, then the copy assignment operator may be
2667 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2668 // it shows up in the right place in the vtable and that we diagnose
2669 // problems with the implicit exception specification.
2670 if (ClassDecl->isDynamicClass())
2671 DeclareImplicitCopyAssignment(ClassDecl);
2672 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002673
Douglas Gregor7454c562010-07-02 20:37:36 +00002674 if (!ClassDecl->hasUserDeclaredDestructor()) {
2675 ++ASTContext::NumImplicitDestructors;
2676
2677 // If we have a dynamic class, then the destructor may be virtual, so we
2678 // have to declare the destructor immediately. This ensures that, e.g., it
2679 // shows up in the right place in the vtable and that we diagnose problems
2680 // with the implicit exception specification.
2681 if (ClassDecl->isDynamicClass())
2682 DeclareImplicitDestructor(ClassDecl);
2683 }
Douglas Gregor05379422008-11-03 17:51:48 +00002684}
2685
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002686void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002687 Decl *D = TemplateD.getAs<Decl>();
2688 if (!D)
2689 return;
2690
2691 TemplateParameterList *Params = 0;
2692 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2693 Params = Template->getTemplateParameters();
2694 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2695 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2696 Params = PartialSpec->getTemplateParameters();
2697 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002698 return;
2699
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002700 for (TemplateParameterList::iterator Param = Params->begin(),
2701 ParamEnd = Params->end();
2702 Param != ParamEnd; ++Param) {
2703 NamedDecl *Named = cast<NamedDecl>(*Param);
2704 if (Named->getDeclName()) {
2705 S->AddDecl(DeclPtrTy::make(Named));
2706 IdResolver.AddDecl(Named);
2707 }
2708 }
2709}
2710
John McCall6df5fef2009-12-19 10:49:29 +00002711void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2712 if (!RecordD) return;
2713 AdjustDeclIfTemplate(RecordD);
2714 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2715 PushDeclContext(S, Record);
2716}
2717
2718void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2719 if (!RecordD) return;
2720 PopDeclContext();
2721}
2722
Douglas Gregor4d87df52008-12-16 21:30:33 +00002723/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2724/// parsing a top-level (non-nested) C++ class, and we are now
2725/// parsing those parts of the given Method declaration that could
2726/// not be parsed earlier (C++ [class.mem]p2), such as default
2727/// arguments. This action should enter the scope of the given
2728/// Method declaration as if we had just parsed the qualified method
2729/// name. However, it should not bring the parameters into scope;
2730/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002731void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002732}
2733
2734/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2735/// C++ method declaration. We're (re-)introducing the given
2736/// function parameter into scope for use in parsing later parts of
2737/// the method declaration. For example, we could see an
2738/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002739void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002740 if (!ParamD)
2741 return;
Mike Stump11289f42009-09-09 15:08:12 +00002742
Chris Lattner83f095c2009-03-28 19:18:32 +00002743 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002744
2745 // If this parameter has an unparsed default argument, clear it out
2746 // to make way for the parsed default argument.
2747 if (Param->hasUnparsedDefaultArg())
2748 Param->setDefaultArg(0);
2749
Chris Lattner83f095c2009-03-28 19:18:32 +00002750 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002751 if (Param->getDeclName())
2752 IdResolver.AddDecl(Param);
2753}
2754
2755/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2756/// processing the delayed method declaration for Method. The method
2757/// declaration is now considered finished. There may be a separate
2758/// ActOnStartOfFunctionDef action later (not necessarily
2759/// immediately!) for this method, if it was also defined inside the
2760/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002761void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002762 if (!MethodD)
2763 return;
Mike Stump11289f42009-09-09 15:08:12 +00002764
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002765 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002766
Chris Lattner83f095c2009-03-28 19:18:32 +00002767 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002768
2769 // Now that we have our default arguments, check the constructor
2770 // again. It could produce additional diagnostics or affect whether
2771 // the class has implicitly-declared destructors, among other
2772 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002773 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2774 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002775
2776 // Check the default arguments, which we may have added.
2777 if (!Method->isInvalidDecl())
2778 CheckCXXDefaultArguments(Method);
2779}
2780
Douglas Gregor831c93f2008-11-05 20:51:48 +00002781/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002782/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002783/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002784/// emit diagnostics and set the invalid bit to true. In any case, the type
2785/// will be updated to reflect a well-formed type for the constructor and
2786/// returned.
2787QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2788 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002789 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002790
2791 // C++ [class.ctor]p3:
2792 // A constructor shall not be virtual (10.3) or static (9.4). A
2793 // constructor can be invoked for a const, volatile or const
2794 // volatile object. A constructor shall not be declared const,
2795 // volatile, or const volatile (9.3.2).
2796 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002797 if (!D.isInvalidType())
2798 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2799 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2800 << SourceRange(D.getIdentifierLoc());
2801 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002802 }
2803 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002804 if (!D.isInvalidType())
2805 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2806 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2807 << SourceRange(D.getIdentifierLoc());
2808 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002809 SC = FunctionDecl::None;
2810 }
Mike Stump11289f42009-09-09 15:08:12 +00002811
Chris Lattner38378bf2009-04-25 08:28:21 +00002812 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2813 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002814 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002815 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2816 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002817 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002818 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2819 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002820 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002821 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2822 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002823 }
Mike Stump11289f42009-09-09 15:08:12 +00002824
Douglas Gregor831c93f2008-11-05 20:51:48 +00002825 // Rebuild the function type "R" without any type qualifiers (in
2826 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002827 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002828 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002829 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2830 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002831 Proto->isVariadic(), 0,
2832 Proto->hasExceptionSpec(),
2833 Proto->hasAnyExceptionSpec(),
2834 Proto->getNumExceptions(),
2835 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002836 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002837}
2838
Douglas Gregor4d87df52008-12-16 21:30:33 +00002839/// CheckConstructor - Checks a fully-formed constructor for
2840/// well-formedness, issuing any diagnostics required. Returns true if
2841/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002842void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002843 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002844 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2845 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002846 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002847
2848 // C++ [class.copy]p3:
2849 // A declaration of a constructor for a class X is ill-formed if
2850 // its first parameter is of type (optionally cv-qualified) X and
2851 // either there are no other parameters or else all other
2852 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002853 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002854 ((Constructor->getNumParams() == 1) ||
2855 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002856 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2857 Constructor->getTemplateSpecializationKind()
2858 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002859 QualType ParamType = Constructor->getParamDecl(0)->getType();
2860 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2861 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002862 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002863 const char *ConstRef
2864 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2865 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002866 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002867 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002868
2869 // FIXME: Rather that making the constructor invalid, we should endeavor
2870 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002871 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002872 }
2873 }
Mike Stump11289f42009-09-09 15:08:12 +00002874
John McCall43314ab2010-04-13 07:45:41 +00002875 // Notify the class that we've added a constructor. In principle we
2876 // don't need to do this for out-of-line declarations; in practice
2877 // we only instantiate the most recent declaration of a method, so
2878 // we have to call this for everything but friends.
2879 if (!Constructor->getFriendObjectKind())
2880 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002881}
2882
John McCalldeb646e2010-08-04 01:04:25 +00002883/// CheckDestructor - Checks a fully-formed destructor definition for
2884/// well-formedness, issuing any diagnostics required. Returns true
2885/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002886bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002887 CXXRecordDecl *RD = Destructor->getParent();
2888
2889 if (Destructor->isVirtual()) {
2890 SourceLocation Loc;
2891
2892 if (!Destructor->isImplicit())
2893 Loc = Destructor->getLocation();
2894 else
2895 Loc = RD->getLocation();
2896
2897 // If we have a virtual destructor, look up the deallocation function
2898 FunctionDecl *OperatorDelete = 0;
2899 DeclarationName Name =
2900 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002901 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002902 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00002903
2904 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00002905
2906 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002907 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002908
2909 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002910}
2911
Mike Stump11289f42009-09-09 15:08:12 +00002912static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002913FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2914 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2915 FTI.ArgInfo[0].Param &&
2916 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2917}
2918
Douglas Gregor831c93f2008-11-05 20:51:48 +00002919/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2920/// the well-formednes of the destructor declarator @p D with type @p
2921/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002922/// emit diagnostics and set the declarator to invalid. Even if this happens,
2923/// will be updated to reflect a well-formed type for the destructor and
2924/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00002925QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
Chris Lattner38378bf2009-04-25 08:28:21 +00002926 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002927 // C++ [class.dtor]p1:
2928 // [...] A typedef-name that names a class is a class-name
2929 // (7.1.3); however, a typedef-name that names a class shall not
2930 // be used as the identifier in the declarator for a destructor
2931 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002932 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00002933 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00002934 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002935 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002936
2937 // C++ [class.dtor]p2:
2938 // A destructor is used to destroy objects of its class type. A
2939 // destructor takes no parameters, and no return type can be
2940 // specified for it (not even void). The address of a destructor
2941 // shall not be taken. A destructor shall not be static. A
2942 // destructor can be invoked for a const, volatile or const
2943 // volatile object. A destructor shall not be declared const,
2944 // volatile or const volatile (9.3.2).
2945 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002946 if (!D.isInvalidType())
2947 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2948 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00002949 << SourceRange(D.getIdentifierLoc())
2950 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2951
Douglas Gregor831c93f2008-11-05 20:51:48 +00002952 SC = FunctionDecl::None;
2953 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002954 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002955 // Destructors don't have return types, but the parser will
2956 // happily parse something like:
2957 //
2958 // class X {
2959 // float ~X();
2960 // };
2961 //
2962 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002963 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2964 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2965 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002966 }
Mike Stump11289f42009-09-09 15:08:12 +00002967
Chris Lattner38378bf2009-04-25 08:28:21 +00002968 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2969 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002970 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002971 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2972 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002973 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002974 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2975 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002976 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002977 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2978 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002979 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002980 }
2981
2982 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002983 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002984 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2985
2986 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002987 FTI.freeArgs();
2988 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002989 }
2990
Mike Stump11289f42009-09-09 15:08:12 +00002991 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002992 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002993 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002994 D.setInvalidType();
2995 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002996
2997 // Rebuild the function type "R" without any type qualifiers or
2998 // parameters (in case any of the errors above fired) and with
2999 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00003000 // types.
3001 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3002 if (!Proto)
3003 return QualType();
3004
Douglas Gregor36c569f2010-02-21 22:15:06 +00003005 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregor95755162010-07-01 05:10:53 +00003006 Proto->hasExceptionSpec(),
3007 Proto->hasAnyExceptionSpec(),
3008 Proto->getNumExceptions(),
3009 Proto->exception_begin(),
3010 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003011}
3012
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003013/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3014/// well-formednes of the conversion function declarator @p D with
3015/// type @p R. If there are any errors in the declarator, this routine
3016/// will emit diagnostics and return true. Otherwise, it will return
3017/// false. Either way, the type @p R will be updated to reflect a
3018/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003019void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003020 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003021 // C++ [class.conv.fct]p1:
3022 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003023 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003024 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003025 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003026 if (!D.isInvalidType())
3027 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3028 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3029 << SourceRange(D.getIdentifierLoc());
3030 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003031 SC = FunctionDecl::None;
3032 }
John McCall212fa2e2010-04-13 00:04:31 +00003033
3034 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3035
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003036 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003037 // Conversion functions don't have return types, but the parser will
3038 // happily parse something like:
3039 //
3040 // class X {
3041 // float operator bool();
3042 // };
3043 //
3044 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003045 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3046 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3047 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003048 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003049 }
3050
John McCall212fa2e2010-04-13 00:04:31 +00003051 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3052
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003053 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003054 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003055 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3056
3057 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003058 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003059 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003060 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003061 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003062 D.setInvalidType();
3063 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003064
John McCall212fa2e2010-04-13 00:04:31 +00003065 // Diagnose "&operator bool()" and other such nonsense. This
3066 // is actually a gcc extension which we don't support.
3067 if (Proto->getResultType() != ConvType) {
3068 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3069 << Proto->getResultType();
3070 D.setInvalidType();
3071 ConvType = Proto->getResultType();
3072 }
3073
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003074 // C++ [class.conv.fct]p4:
3075 // The conversion-type-id shall not represent a function type nor
3076 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003077 if (ConvType->isArrayType()) {
3078 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3079 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003080 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003081 } else if (ConvType->isFunctionType()) {
3082 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3083 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003084 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003085 }
3086
3087 // Rebuild the function type "R" without any parameters (in case any
3088 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003089 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003090 if (D.isInvalidType()) {
3091 R = Context.getFunctionType(ConvType, 0, 0, false,
3092 Proto->getTypeQuals(),
3093 Proto->hasExceptionSpec(),
3094 Proto->hasAnyExceptionSpec(),
3095 Proto->getNumExceptions(),
3096 Proto->exception_begin(),
3097 Proto->getExtInfo());
3098 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003099
Douglas Gregor5fb53972009-01-14 15:45:31 +00003100 // C++0x explicit conversion operators.
3101 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003102 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003103 diag::warn_explicit_conversion_functions)
3104 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003105}
3106
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003107/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3108/// the declaration of the given C++ conversion function. This routine
3109/// is responsible for recording the conversion function in the C++
3110/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00003111Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003112 assert(Conversion && "Expected to receive a conversion function declaration");
3113
Douglas Gregor4287b372008-12-12 08:25:50 +00003114 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003115
3116 // Make sure we aren't redeclaring the conversion function.
3117 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003118
3119 // C++ [class.conv.fct]p1:
3120 // [...] A conversion function is never used to convert a
3121 // (possibly cv-qualified) object to the (possibly cv-qualified)
3122 // same object type (or a reference to it), to a (possibly
3123 // cv-qualified) base class of that type (or a reference to it),
3124 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003125 // FIXME: Suppress this warning if the conversion function ends up being a
3126 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003127 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003128 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003129 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003130 ConvType = ConvTypeRef->getPointeeType();
3131 if (ConvType->isRecordType()) {
3132 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3133 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003134 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003135 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003136 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003137 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003138 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003139 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003140 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003141 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003142 }
3143
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003144 if (Conversion->getPrimaryTemplate()) {
3145 // ignore specializations
3146 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump11289f42009-09-09 15:08:12 +00003147 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor133bc742010-01-11 18:53:25 +00003148 = Conversion->getDescribedFunctionTemplate()) {
3149 if (ClassDecl->replaceConversion(
3150 ConversionTemplate->getPreviousDeclaration(),
3151 ConversionTemplate))
3152 return DeclPtrTy::make(ConversionTemplate);
3153 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3154 Conversion))
John McCalld14a8642009-11-21 08:51:07 +00003155 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00003156 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00003157 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003158 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003159 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003160 else
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003161 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003162
Chris Lattner83f095c2009-03-28 19:18:32 +00003163 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003164}
3165
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003166//===----------------------------------------------------------------------===//
3167// Namespace Handling
3168//===----------------------------------------------------------------------===//
3169
3170/// ActOnStartNamespaceDef - This is called at the start of a namespace
3171/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00003172Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3173 SourceLocation IdentLoc,
3174 IdentifierInfo *II,
Anders Carlssona7bcade2010-02-07 01:09:23 +00003175 SourceLocation LBrace,
3176 AttributeList *AttrList) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003177 NamespaceDecl *Namespc =
3178 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3179 Namespc->setLBracLoc(LBrace);
3180
3181 Scope *DeclRegionScope = NamespcScope->getParent();
3182
Anders Carlssona7bcade2010-02-07 01:09:23 +00003183 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3184
Eli Friedman570024a2010-08-05 06:57:20 +00003185 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
3186 PushPragmaVisibility(attr->getVisibility());
3187
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003188 if (II) {
3189 // C++ [namespace.def]p2:
3190 // The identifier in an original-namespace-definition shall not have been
3191 // previously defined in the declarative region in which the
3192 // original-namespace-definition appears. The identifier in an
3193 // original-namespace-definition is the name of the namespace. Subsequently
3194 // in that declarative region, it is treated as an original-namespace-name.
3195
John McCall9f3059a2009-10-09 21:13:30 +00003196 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003197 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003198 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00003199
Douglas Gregor91f84212008-12-11 16:49:14 +00003200 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3201 // This is an extended namespace definition.
3202 // Attach this namespace decl to the chain of extended namespace
3203 // definitions.
3204 OrigNS->setNextNamespace(Namespc);
3205 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003206
Mike Stump11289f42009-09-09 15:08:12 +00003207 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003208 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003209 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00003210 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003211 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003212 } else if (PrevDecl) {
3213 // This is an invalid name redefinition.
3214 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3215 << Namespc->getDeclName();
3216 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3217 Namespc->setInvalidDecl();
3218 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003219 } else if (II->isStr("std") &&
3220 CurContext->getLookupContext()->isTranslationUnit()) {
3221 // This is the first "real" definition of the namespace "std", so update
3222 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003223 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003224 // We had already defined a dummy namespace "std". Link this new
3225 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003226 StdNS->setNextNamespace(Namespc);
3227 StdNS->setLocation(IdentLoc);
3228 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003229 }
3230
3231 // Make our StdNamespace cache point at the first real definition of the
3232 // "std" namespace.
3233 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003234 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003235
3236 PushOnScopeChains(Namespc, DeclRegionScope);
3237 } else {
John McCall4fa53422009-10-01 00:25:31 +00003238 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003239 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003240
3241 // Link the anonymous namespace into its parent.
3242 NamespaceDecl *PrevDecl;
3243 DeclContext *Parent = CurContext->getLookupContext();
3244 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3245 PrevDecl = TU->getAnonymousNamespace();
3246 TU->setAnonymousNamespace(Namespc);
3247 } else {
3248 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3249 PrevDecl = ND->getAnonymousNamespace();
3250 ND->setAnonymousNamespace(Namespc);
3251 }
3252
3253 // Link the anonymous namespace with its previous declaration.
3254 if (PrevDecl) {
3255 assert(PrevDecl->isAnonymousNamespace());
3256 assert(!PrevDecl->getNextNamespace());
3257 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3258 PrevDecl->setNextNamespace(Namespc);
3259 }
John McCall4fa53422009-10-01 00:25:31 +00003260
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003261 CurContext->addDecl(Namespc);
3262
John McCall4fa53422009-10-01 00:25:31 +00003263 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3264 // behaves as if it were replaced by
3265 // namespace unique { /* empty body */ }
3266 // using namespace unique;
3267 // namespace unique { namespace-body }
3268 // where all occurrences of 'unique' in a translation unit are
3269 // replaced by the same identifier and this identifier differs
3270 // from all other identifiers in the entire program.
3271
3272 // We just create the namespace with an empty name and then add an
3273 // implicit using declaration, just like the standard suggests.
3274 //
3275 // CodeGen enforces the "universally unique" aspect by giving all
3276 // declarations semantically contained within an anonymous
3277 // namespace internal linkage.
3278
John McCall0db42252009-12-16 02:06:49 +00003279 if (!PrevDecl) {
3280 UsingDirectiveDecl* UD
3281 = UsingDirectiveDecl::Create(Context, CurContext,
3282 /* 'using' */ LBrace,
3283 /* 'namespace' */ SourceLocation(),
3284 /* qualifier */ SourceRange(),
3285 /* NNS */ NULL,
3286 /* identifier */ SourceLocation(),
3287 Namespc,
3288 /* Ancestor */ CurContext);
3289 UD->setImplicit();
3290 CurContext->addDecl(UD);
3291 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003292 }
3293
3294 // Although we could have an invalid decl (i.e. the namespace name is a
3295 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003296 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3297 // for the namespace has the declarations that showed up in that particular
3298 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003299 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00003300 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003301}
3302
Sebastian Redla6602e92009-11-23 15:34:23 +00003303/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3304/// is a namespace alias, returns the namespace it points to.
3305static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3306 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3307 return AD->getNamespace();
3308 return dyn_cast_or_null<NamespaceDecl>(D);
3309}
3310
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003311/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3312/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00003313void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3314 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003315 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3316 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3317 Namespc->setRBracLoc(RBrace);
3318 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003319 if (Namespc->hasAttr<VisibilityAttr>())
3320 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003321}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003322
Douglas Gregorcdf87022010-06-29 17:53:46 +00003323/// \brief Retrieve the special "std" namespace, which may require us to
3324/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003325NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003326 if (!StdNamespace) {
3327 // The "std" namespace has not yet been defined, so build one implicitly.
3328 StdNamespace = NamespaceDecl::Create(Context,
3329 Context.getTranslationUnitDecl(),
3330 SourceLocation(),
3331 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003332 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003333 }
3334
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003335 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003336}
3337
Chris Lattner83f095c2009-03-28 19:18:32 +00003338Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3339 SourceLocation UsingLoc,
3340 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003341 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003342 SourceLocation IdentLoc,
3343 IdentifierInfo *NamespcName,
3344 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003345 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3346 assert(NamespcName && "Invalid NamespcName.");
3347 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003348 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003349
Douglas Gregor889ceb72009-02-03 19:21:40 +00003350 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003351 NestedNameSpecifier *Qualifier = 0;
3352 if (SS.isSet())
3353 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3354
Douglas Gregor34074322009-01-14 22:20:51 +00003355 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003356 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3357 LookupParsedName(R, S, &SS);
3358 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003359 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00003360
Douglas Gregorcdf87022010-06-29 17:53:46 +00003361 if (R.empty()) {
3362 // Allow "using namespace std;" or "using namespace ::std;" even if
3363 // "std" hasn't been defined yet, for GCC compatibility.
3364 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3365 NamespcName->isStr("std")) {
3366 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003367 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003368 R.resolveKind();
3369 }
3370 // Otherwise, attempt typo correction.
3371 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3372 CTC_NoKeywords, 0)) {
3373 if (R.getAsSingle<NamespaceDecl>() ||
3374 R.getAsSingle<NamespaceAliasDecl>()) {
3375 if (DeclContext *DC = computeDeclContext(SS, false))
3376 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3377 << NamespcName << DC << Corrected << SS.getRange()
3378 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3379 else
3380 Diag(IdentLoc, diag::err_using_directive_suggest)
3381 << NamespcName << Corrected
3382 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3383 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3384 << Corrected;
3385
3386 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003387 } else {
3388 R.clear();
3389 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003390 }
3391 }
3392 }
3393
John McCall9f3059a2009-10-09 21:13:30 +00003394 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003395 NamedDecl *Named = R.getFoundDecl();
3396 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3397 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003398 // C++ [namespace.udir]p1:
3399 // A using-directive specifies that the names in the nominated
3400 // namespace can be used in the scope in which the
3401 // using-directive appears after the using-directive. During
3402 // unqualified name lookup (3.4.1), the names appear as if they
3403 // were declared in the nearest enclosing namespace which
3404 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003405 // namespace. [Note: in this context, "contains" means "contains
3406 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003407
3408 // Find enclosing context containing both using-directive and
3409 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003410 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003411 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3412 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3413 CommonAncestor = CommonAncestor->getParent();
3414
Sebastian Redla6602e92009-11-23 15:34:23 +00003415 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003416 SS.getRange(),
3417 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003418 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003419 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003420 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003421 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003422 }
3423
Douglas Gregor889ceb72009-02-03 19:21:40 +00003424 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003425 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00003426 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003427}
3428
3429void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3430 // If scope has associated entity, then using directive is at namespace
3431 // or translation unit scope. We add UsingDirectiveDecls, into
3432 // it's lookup structure.
3433 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003434 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003435 else
3436 // Otherwise it is block-sope. using-directives will affect lookup
3437 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003438 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00003439}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003440
Douglas Gregorfec52632009-06-20 00:51:54 +00003441
3442Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003443 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003444 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003445 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003446 CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003447 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003448 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003449 bool IsTypeName,
3450 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003451 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003452
Douglas Gregor220f4272009-11-04 16:30:06 +00003453 switch (Name.getKind()) {
3454 case UnqualifiedId::IK_Identifier:
3455 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003456 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003457 case UnqualifiedId::IK_ConversionFunctionId:
3458 break;
3459
3460 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003461 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003462 // C++0x inherited constructors.
3463 if (getLangOptions().CPlusPlus0x) break;
3464
Douglas Gregor220f4272009-11-04 16:30:06 +00003465 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3466 << SS.getRange();
3467 return DeclPtrTy();
3468
3469 case UnqualifiedId::IK_DestructorName:
3470 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3471 << SS.getRange();
3472 return DeclPtrTy();
3473
3474 case UnqualifiedId::IK_TemplateId:
3475 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3476 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3477 return DeclPtrTy();
3478 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003479
3480 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3481 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003482 if (!TargetName)
3483 return DeclPtrTy();
3484
John McCalla0097262009-12-11 02:10:03 +00003485 // Warn about using declarations.
3486 // TODO: store that the declaration was written without 'using' and
3487 // talk about access decls instead of using decls in the
3488 // diagnostics.
3489 if (!HasUsingKeyword) {
3490 UsingLoc = Name.getSourceRange().getBegin();
3491
3492 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003493 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003494 }
3495
John McCall3f746822009-11-17 05:59:44 +00003496 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003497 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003498 /* IsInstantiation */ false,
3499 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003500 if (UD)
3501 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003502
Anders Carlsson696a3f12009-08-28 05:40:36 +00003503 return DeclPtrTy::make(UD);
3504}
3505
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003506/// \brief Determine whether a using declaration considers the given
3507/// declarations as "equivalent", e.g., if they are redeclarations of
3508/// the same entity or are both typedefs of the same type.
3509static bool
3510IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3511 bool &SuppressRedeclaration) {
3512 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3513 SuppressRedeclaration = false;
3514 return true;
3515 }
3516
3517 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3518 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3519 SuppressRedeclaration = true;
3520 return Context.hasSameType(TD1->getUnderlyingType(),
3521 TD2->getUnderlyingType());
3522 }
3523
3524 return false;
3525}
3526
3527
John McCall84d87672009-12-10 09:41:52 +00003528/// Determines whether to create a using shadow decl for a particular
3529/// decl, given the set of decls existing prior to this using lookup.
3530bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3531 const LookupResult &Previous) {
3532 // Diagnose finding a decl which is not from a base class of the
3533 // current class. We do this now because there are cases where this
3534 // function will silently decide not to build a shadow decl, which
3535 // will pre-empt further diagnostics.
3536 //
3537 // We don't need to do this in C++0x because we do the check once on
3538 // the qualifier.
3539 //
3540 // FIXME: diagnose the following if we care enough:
3541 // struct A { int foo; };
3542 // struct B : A { using A::foo; };
3543 // template <class T> struct C : A {};
3544 // template <class T> struct D : C<T> { using B::foo; } // <---
3545 // This is invalid (during instantiation) in C++03 because B::foo
3546 // resolves to the using decl in B, which is not a base class of D<T>.
3547 // We can't diagnose it immediately because C<T> is an unknown
3548 // specialization. The UsingShadowDecl in D<T> then points directly
3549 // to A::foo, which will look well-formed when we instantiate.
3550 // The right solution is to not collapse the shadow-decl chain.
3551 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3552 DeclContext *OrigDC = Orig->getDeclContext();
3553
3554 // Handle enums and anonymous structs.
3555 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3556 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3557 while (OrigRec->isAnonymousStructOrUnion())
3558 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3559
3560 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3561 if (OrigDC == CurContext) {
3562 Diag(Using->getLocation(),
3563 diag::err_using_decl_nested_name_specifier_is_current_class)
3564 << Using->getNestedNameRange();
3565 Diag(Orig->getLocation(), diag::note_using_decl_target);
3566 return true;
3567 }
3568
3569 Diag(Using->getNestedNameRange().getBegin(),
3570 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3571 << Using->getTargetNestedNameDecl()
3572 << cast<CXXRecordDecl>(CurContext)
3573 << Using->getNestedNameRange();
3574 Diag(Orig->getLocation(), diag::note_using_decl_target);
3575 return true;
3576 }
3577 }
3578
3579 if (Previous.empty()) return false;
3580
3581 NamedDecl *Target = Orig;
3582 if (isa<UsingShadowDecl>(Target))
3583 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3584
John McCalla17e83e2009-12-11 02:33:26 +00003585 // If the target happens to be one of the previous declarations, we
3586 // don't have a conflict.
3587 //
3588 // FIXME: but we might be increasing its access, in which case we
3589 // should redeclare it.
3590 NamedDecl *NonTag = 0, *Tag = 0;
3591 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3592 I != E; ++I) {
3593 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003594 bool Result;
3595 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3596 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003597
3598 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3599 }
3600
John McCall84d87672009-12-10 09:41:52 +00003601 if (Target->isFunctionOrFunctionTemplate()) {
3602 FunctionDecl *FD;
3603 if (isa<FunctionTemplateDecl>(Target))
3604 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3605 else
3606 FD = cast<FunctionDecl>(Target);
3607
3608 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003609 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003610 case Ovl_Overload:
3611 return false;
3612
3613 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003614 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003615 break;
3616
3617 // We found a decl with the exact signature.
3618 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003619 // If we're in a record, we want to hide the target, so we
3620 // return true (without a diagnostic) to tell the caller not to
3621 // build a shadow decl.
3622 if (CurContext->isRecord())
3623 return true;
3624
3625 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003626 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003627 break;
3628 }
3629
3630 Diag(Target->getLocation(), diag::note_using_decl_target);
3631 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3632 return true;
3633 }
3634
3635 // Target is not a function.
3636
John McCall84d87672009-12-10 09:41:52 +00003637 if (isa<TagDecl>(Target)) {
3638 // No conflict between a tag and a non-tag.
3639 if (!Tag) return false;
3640
John McCalle29c5cd2009-12-10 19:51:03 +00003641 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003642 Diag(Target->getLocation(), diag::note_using_decl_target);
3643 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3644 return true;
3645 }
3646
3647 // No conflict between a tag and a non-tag.
3648 if (!NonTag) return false;
3649
John McCalle29c5cd2009-12-10 19:51:03 +00003650 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003651 Diag(Target->getLocation(), diag::note_using_decl_target);
3652 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3653 return true;
3654}
3655
John McCall3f746822009-11-17 05:59:44 +00003656/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003657UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003658 UsingDecl *UD,
3659 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003660
3661 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003662 NamedDecl *Target = Orig;
3663 if (isa<UsingShadowDecl>(Target)) {
3664 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3665 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003666 }
3667
3668 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003669 = UsingShadowDecl::Create(Context, CurContext,
3670 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003671 UD->addShadowDecl(Shadow);
3672
3673 if (S)
John McCall3969e302009-12-08 07:46:18 +00003674 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003675 else
John McCall3969e302009-12-08 07:46:18 +00003676 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003677 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003678
John McCallda4458e2010-03-31 01:36:47 +00003679 // Register it as a conversion if appropriate.
3680 if (Shadow->getDeclName().getNameKind()
3681 == DeclarationName::CXXConversionFunctionName)
3682 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3683
John McCall3969e302009-12-08 07:46:18 +00003684 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3685 Shadow->setInvalidDecl();
3686
John McCall84d87672009-12-10 09:41:52 +00003687 return Shadow;
3688}
John McCall3969e302009-12-08 07:46:18 +00003689
John McCall84d87672009-12-10 09:41:52 +00003690/// Hides a using shadow declaration. This is required by the current
3691/// using-decl implementation when a resolvable using declaration in a
3692/// class is followed by a declaration which would hide or override
3693/// one or more of the using decl's targets; for example:
3694///
3695/// struct Base { void foo(int); };
3696/// struct Derived : Base {
3697/// using Base::foo;
3698/// void foo(int);
3699/// };
3700///
3701/// The governing language is C++03 [namespace.udecl]p12:
3702///
3703/// When a using-declaration brings names from a base class into a
3704/// derived class scope, member functions in the derived class
3705/// override and/or hide member functions with the same name and
3706/// parameter types in a base class (rather than conflicting).
3707///
3708/// There are two ways to implement this:
3709/// (1) optimistically create shadow decls when they're not hidden
3710/// by existing declarations, or
3711/// (2) don't create any shadow decls (or at least don't make them
3712/// visible) until we've fully parsed/instantiated the class.
3713/// The problem with (1) is that we might have to retroactively remove
3714/// a shadow decl, which requires several O(n) operations because the
3715/// decl structures are (very reasonably) not designed for removal.
3716/// (2) avoids this but is very fiddly and phase-dependent.
3717void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003718 if (Shadow->getDeclName().getNameKind() ==
3719 DeclarationName::CXXConversionFunctionName)
3720 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3721
John McCall84d87672009-12-10 09:41:52 +00003722 // Remove it from the DeclContext...
3723 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003724
John McCall84d87672009-12-10 09:41:52 +00003725 // ...and the scope, if applicable...
3726 if (S) {
3727 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3728 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003729 }
3730
John McCall84d87672009-12-10 09:41:52 +00003731 // ...and the using decl.
3732 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3733
3734 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003735 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003736}
3737
John McCalle61f2ba2009-11-18 02:36:19 +00003738/// Builds a using declaration.
3739///
3740/// \param IsInstantiation - Whether this call arises from an
3741/// instantiation of an unresolved using declaration. We treat
3742/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003743NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3744 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003745 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003746 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003747 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003748 bool IsInstantiation,
3749 bool IsTypeName,
3750 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003751 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003752 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003753 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003754
Anders Carlssonf038fc22009-08-28 05:49:21 +00003755 // FIXME: We ignore attributes for now.
3756 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003757
Anders Carlsson59140b32009-08-28 03:16:11 +00003758 if (SS.isEmpty()) {
3759 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003760 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003761 }
Mike Stump11289f42009-09-09 15:08:12 +00003762
John McCall84d87672009-12-10 09:41:52 +00003763 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003764 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003765 ForRedeclaration);
3766 Previous.setHideTags(false);
3767 if (S) {
3768 LookupName(Previous, S);
3769
3770 // It is really dumb that we have to do this.
3771 LookupResult::Filter F = Previous.makeFilter();
3772 while (F.hasNext()) {
3773 NamedDecl *D = F.next();
3774 if (!isDeclInScope(D, CurContext, S))
3775 F.erase();
3776 }
3777 F.done();
3778 } else {
3779 assert(IsInstantiation && "no scope in non-instantiation");
3780 assert(CurContext->isRecord() && "scope not record in instantiation");
3781 LookupQualifiedName(Previous, CurContext);
3782 }
3783
Mike Stump11289f42009-09-09 15:08:12 +00003784 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003785 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3786
John McCall84d87672009-12-10 09:41:52 +00003787 // Check for invalid redeclarations.
3788 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3789 return 0;
3790
3791 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003792 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3793 return 0;
3794
John McCall84c16cf2009-11-12 03:15:40 +00003795 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003796 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003797 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003798 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003799 // FIXME: not all declaration name kinds are legal here
3800 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3801 UsingLoc, TypenameLoc,
3802 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003803 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003804 } else {
3805 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003806 UsingLoc, SS.getRange(),
3807 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003808 }
John McCallb96ec562009-12-04 22:46:56 +00003809 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003810 D = UsingDecl::Create(Context, CurContext,
3811 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003812 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003813 }
John McCallb96ec562009-12-04 22:46:56 +00003814 D->setAccess(AS);
3815 CurContext->addDecl(D);
3816
3817 if (!LookupContext) return D;
3818 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003819
John McCall0b66eb32010-05-01 00:40:08 +00003820 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003821 UD->setInvalidDecl();
3822 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003823 }
3824
John McCall3969e302009-12-08 07:46:18 +00003825 // Look up the target name.
3826
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003827 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003828
John McCall3969e302009-12-08 07:46:18 +00003829 // Unlike most lookups, we don't always want to hide tag
3830 // declarations: tag names are visible through the using declaration
3831 // even if hidden by ordinary names, *except* in a dependent context
3832 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003833 if (!IsInstantiation)
3834 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003835
John McCall27b18f82009-11-17 02:14:36 +00003836 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003837
John McCall9f3059a2009-10-09 21:13:30 +00003838 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003839 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003840 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003841 UD->setInvalidDecl();
3842 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003843 }
3844
John McCallb96ec562009-12-04 22:46:56 +00003845 if (R.isAmbiguous()) {
3846 UD->setInvalidDecl();
3847 return UD;
3848 }
Mike Stump11289f42009-09-09 15:08:12 +00003849
John McCalle61f2ba2009-11-18 02:36:19 +00003850 if (IsTypeName) {
3851 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003852 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003853 Diag(IdentLoc, diag::err_using_typename_non_type);
3854 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3855 Diag((*I)->getUnderlyingDecl()->getLocation(),
3856 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003857 UD->setInvalidDecl();
3858 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003859 }
3860 } else {
3861 // If we asked for a non-typename and we got a type, error out,
3862 // but only if this is an instantiation of an unresolved using
3863 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003864 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003865 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3866 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003867 UD->setInvalidDecl();
3868 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003869 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003870 }
3871
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003872 // C++0x N2914 [namespace.udecl]p6:
3873 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003874 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003875 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3876 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003877 UD->setInvalidDecl();
3878 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003879 }
Mike Stump11289f42009-09-09 15:08:12 +00003880
John McCall84d87672009-12-10 09:41:52 +00003881 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3882 if (!CheckUsingShadowDecl(UD, *I, Previous))
3883 BuildUsingShadowDecl(S, UD, *I);
3884 }
John McCall3f746822009-11-17 05:59:44 +00003885
3886 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003887}
3888
John McCall84d87672009-12-10 09:41:52 +00003889/// Checks that the given using declaration is not an invalid
3890/// redeclaration. Note that this is checking only for the using decl
3891/// itself, not for any ill-formedness among the UsingShadowDecls.
3892bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3893 bool isTypeName,
3894 const CXXScopeSpec &SS,
3895 SourceLocation NameLoc,
3896 const LookupResult &Prev) {
3897 // C++03 [namespace.udecl]p8:
3898 // C++0x [namespace.udecl]p10:
3899 // A using-declaration is a declaration and can therefore be used
3900 // repeatedly where (and only where) multiple declarations are
3901 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00003902 //
3903 // That's in non-member contexts.
3904 if (!CurContext->getLookupContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00003905 return false;
3906
3907 NestedNameSpecifier *Qual
3908 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3909
3910 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3911 NamedDecl *D = *I;
3912
3913 bool DTypename;
3914 NestedNameSpecifier *DQual;
3915 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3916 DTypename = UD->isTypeName();
3917 DQual = UD->getTargetNestedNameDecl();
3918 } else if (UnresolvedUsingValueDecl *UD
3919 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3920 DTypename = false;
3921 DQual = UD->getTargetNestedNameSpecifier();
3922 } else if (UnresolvedUsingTypenameDecl *UD
3923 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3924 DTypename = true;
3925 DQual = UD->getTargetNestedNameSpecifier();
3926 } else continue;
3927
3928 // using decls differ if one says 'typename' and the other doesn't.
3929 // FIXME: non-dependent using decls?
3930 if (isTypeName != DTypename) continue;
3931
3932 // using decls differ if they name different scopes (but note that
3933 // template instantiation can cause this check to trigger when it
3934 // didn't before instantiation).
3935 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3936 Context.getCanonicalNestedNameSpecifier(DQual))
3937 continue;
3938
3939 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003940 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003941 return true;
3942 }
3943
3944 return false;
3945}
3946
John McCall3969e302009-12-08 07:46:18 +00003947
John McCallb96ec562009-12-04 22:46:56 +00003948/// Checks that the given nested-name qualifier used in a using decl
3949/// in the current context is appropriately related to the current
3950/// scope. If an error is found, diagnoses it and returns true.
3951bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3952 const CXXScopeSpec &SS,
3953 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003954 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003955
John McCall3969e302009-12-08 07:46:18 +00003956 if (!CurContext->isRecord()) {
3957 // C++03 [namespace.udecl]p3:
3958 // C++0x [namespace.udecl]p8:
3959 // A using-declaration for a class member shall be a member-declaration.
3960
3961 // If we weren't able to compute a valid scope, it must be a
3962 // dependent class scope.
3963 if (!NamedContext || NamedContext->isRecord()) {
3964 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3965 << SS.getRange();
3966 return true;
3967 }
3968
3969 // Otherwise, everything is known to be fine.
3970 return false;
3971 }
3972
3973 // The current scope is a record.
3974
3975 // If the named context is dependent, we can't decide much.
3976 if (!NamedContext) {
3977 // FIXME: in C++0x, we can diagnose if we can prove that the
3978 // nested-name-specifier does not refer to a base class, which is
3979 // still possible in some cases.
3980
3981 // Otherwise we have to conservatively report that things might be
3982 // okay.
3983 return false;
3984 }
3985
3986 if (!NamedContext->isRecord()) {
3987 // Ideally this would point at the last name in the specifier,
3988 // but we don't have that level of source info.
3989 Diag(SS.getRange().getBegin(),
3990 diag::err_using_decl_nested_name_specifier_is_not_class)
3991 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3992 return true;
3993 }
3994
3995 if (getLangOptions().CPlusPlus0x) {
3996 // C++0x [namespace.udecl]p3:
3997 // In a using-declaration used as a member-declaration, the
3998 // nested-name-specifier shall name a base class of the class
3999 // being defined.
4000
4001 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4002 cast<CXXRecordDecl>(NamedContext))) {
4003 if (CurContext == NamedContext) {
4004 Diag(NameLoc,
4005 diag::err_using_decl_nested_name_specifier_is_current_class)
4006 << SS.getRange();
4007 return true;
4008 }
4009
4010 Diag(SS.getRange().getBegin(),
4011 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4012 << (NestedNameSpecifier*) SS.getScopeRep()
4013 << cast<CXXRecordDecl>(CurContext)
4014 << SS.getRange();
4015 return true;
4016 }
4017
4018 return false;
4019 }
4020
4021 // C++03 [namespace.udecl]p4:
4022 // A using-declaration used as a member-declaration shall refer
4023 // to a member of a base class of the class being defined [etc.].
4024
4025 // Salient point: SS doesn't have to name a base class as long as
4026 // lookup only finds members from base classes. Therefore we can
4027 // diagnose here only if we can prove that that can't happen,
4028 // i.e. if the class hierarchies provably don't intersect.
4029
4030 // TODO: it would be nice if "definitely valid" results were cached
4031 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4032 // need to be repeated.
4033
4034 struct UserData {
4035 llvm::DenseSet<const CXXRecordDecl*> Bases;
4036
4037 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4038 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4039 Data->Bases.insert(Base);
4040 return true;
4041 }
4042
4043 bool hasDependentBases(const CXXRecordDecl *Class) {
4044 return !Class->forallBases(collect, this);
4045 }
4046
4047 /// Returns true if the base is dependent or is one of the
4048 /// accumulated base classes.
4049 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4050 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4051 return !Data->Bases.count(Base);
4052 }
4053
4054 bool mightShareBases(const CXXRecordDecl *Class) {
4055 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4056 }
4057 };
4058
4059 UserData Data;
4060
4061 // Returns false if we find a dependent base.
4062 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4063 return false;
4064
4065 // Returns false if the class has a dependent base or if it or one
4066 // of its bases is present in the base set of the current context.
4067 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4068 return false;
4069
4070 Diag(SS.getRange().getBegin(),
4071 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4072 << (NestedNameSpecifier*) SS.getScopeRep()
4073 << cast<CXXRecordDecl>(CurContext)
4074 << SS.getRange();
4075
4076 return true;
John McCallb96ec562009-12-04 22:46:56 +00004077}
4078
Mike Stump11289f42009-09-09 15:08:12 +00004079Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004080 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004081 SourceLocation AliasLoc,
4082 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004083 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004084 SourceLocation IdentLoc,
4085 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004086
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004087 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004088 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4089 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004090
Anders Carlssondca83c42009-03-28 06:23:46 +00004091 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004092 NamedDecl *PrevDecl
4093 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4094 ForRedeclaration);
4095 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4096 PrevDecl = 0;
4097
4098 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004099 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004100 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004101 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004102 // FIXME: At some point, we'll want to create the (redundant)
4103 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004104 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004105 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004106 return DeclPtrTy();
4107 }
Mike Stump11289f42009-09-09 15:08:12 +00004108
Anders Carlssondca83c42009-03-28 06:23:46 +00004109 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4110 diag::err_redefinition_different_kind;
4111 Diag(AliasLoc, DiagID) << Alias;
4112 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00004113 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00004114 }
4115
John McCall27b18f82009-11-17 02:14:36 +00004116 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00004117 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00004118
John McCall9f3059a2009-10-09 21:13:30 +00004119 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004120 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4121 CTC_NoKeywords, 0)) {
4122 if (R.getAsSingle<NamespaceDecl>() ||
4123 R.getAsSingle<NamespaceAliasDecl>()) {
4124 if (DeclContext *DC = computeDeclContext(SS, false))
4125 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4126 << Ident << DC << Corrected << SS.getRange()
4127 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4128 else
4129 Diag(IdentLoc, diag::err_using_directive_suggest)
4130 << Ident << Corrected
4131 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4132
4133 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4134 << Corrected;
4135
4136 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004137 } else {
4138 R.clear();
4139 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004140 }
4141 }
4142
4143 if (R.empty()) {
4144 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
4145 return DeclPtrTy();
4146 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004147 }
Mike Stump11289f42009-09-09 15:08:12 +00004148
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004149 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004150 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4151 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004152 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004153 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004154
John McCalld8d0d432010-02-16 06:53:13 +00004155 PushOnScopeChains(AliasDecl, S);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00004156 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00004157}
4158
Douglas Gregora57478e2010-05-01 15:04:51 +00004159namespace {
4160 /// \brief Scoped object used to handle the state changes required in Sema
4161 /// to implicitly define the body of a C++ member function;
4162 class ImplicitlyDefinedFunctionScope {
4163 Sema &S;
4164 DeclContext *PreviousContext;
4165
4166 public:
4167 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4168 : S(S), PreviousContext(S.CurContext)
4169 {
4170 S.CurContext = Method;
4171 S.PushFunctionScope();
4172 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4173 }
4174
4175 ~ImplicitlyDefinedFunctionScope() {
4176 S.PopExpressionEvaluationContext();
4177 S.PopFunctionOrBlockScope();
4178 S.CurContext = PreviousContext;
4179 }
4180 };
4181}
4182
Douglas Gregor0be31a22010-07-02 17:43:08 +00004183CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4184 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004185 // C++ [class.ctor]p5:
4186 // A default constructor for a class X is a constructor of class X
4187 // that can be called without an argument. If there is no
4188 // user-declared constructor for class X, a default constructor is
4189 // implicitly declared. An implicitly-declared default constructor
4190 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004191 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4192 "Should not build implicit default constructor!");
4193
Douglas Gregor6d880b12010-07-01 22:31:05 +00004194 // C++ [except.spec]p14:
4195 // An implicitly declared special member function (Clause 12) shall have an
4196 // exception-specification. [...]
4197 ImplicitExceptionSpecification ExceptSpec(Context);
4198
4199 // Direct base-class destructors.
4200 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4201 BEnd = ClassDecl->bases_end();
4202 B != BEnd; ++B) {
4203 if (B->isVirtual()) // Handled below.
4204 continue;
4205
Douglas Gregor9672f922010-07-03 00:47:00 +00004206 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4207 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4208 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4209 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4210 else if (CXXConstructorDecl *Constructor
4211 = BaseClassDecl->getDefaultConstructor())
Douglas Gregor6d880b12010-07-01 22:31:05 +00004212 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004213 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004214 }
4215
4216 // Virtual base-class destructors.
4217 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4218 BEnd = ClassDecl->vbases_end();
4219 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004220 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4221 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4222 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4223 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4224 else if (CXXConstructorDecl *Constructor
4225 = BaseClassDecl->getDefaultConstructor())
Douglas Gregor6d880b12010-07-01 22:31:05 +00004226 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004227 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004228 }
4229
4230 // Field destructors.
4231 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4232 FEnd = ClassDecl->field_end();
4233 F != FEnd; ++F) {
4234 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004235 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4236 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4237 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4238 ExceptSpec.CalledDecl(
4239 DeclareImplicitDefaultConstructor(FieldClassDecl));
4240 else if (CXXConstructorDecl *Constructor
4241 = FieldClassDecl->getDefaultConstructor())
Douglas Gregor6d880b12010-07-01 22:31:05 +00004242 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004243 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004244 }
4245
4246
4247 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004248 CanQualType ClassType
4249 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4250 DeclarationName Name
4251 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004252 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004253 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004254 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004255 Context.getFunctionType(Context.VoidTy,
4256 0, 0, false, 0,
Douglas Gregor6d880b12010-07-01 22:31:05 +00004257 ExceptSpec.hasExceptionSpecification(),
4258 ExceptSpec.hasAnyExceptionSpecification(),
4259 ExceptSpec.size(),
4260 ExceptSpec.data(),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004261 FunctionType::ExtInfo()),
4262 /*TInfo=*/0,
4263 /*isExplicit=*/false,
4264 /*isInline=*/true,
4265 /*isImplicitlyDeclared=*/true);
4266 DefaultCon->setAccess(AS_public);
4267 DefaultCon->setImplicit();
4268 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004269
4270 // Note that we have declared this constructor.
4271 ClassDecl->setDeclaredDefaultConstructor(true);
4272 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4273
Douglas Gregor0be31a22010-07-02 17:43:08 +00004274 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004275 PushOnScopeChains(DefaultCon, S, false);
4276 ClassDecl->addDecl(DefaultCon);
4277
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004278 return DefaultCon;
4279}
4280
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004281void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4282 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004283 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004284 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004285 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004286
Anders Carlsson423f5d82010-04-23 16:04:08 +00004287 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004288 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004289
Douglas Gregora57478e2010-05-01 15:04:51 +00004290 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00004291 ErrorTrap Trap(*this);
4292 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4293 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004294 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004295 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004296 Constructor->setInvalidDecl();
4297 } else {
4298 Constructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004299 MarkVTableUsed(CurrentLocation, ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004300 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004301}
4302
Douglas Gregor0be31a22010-07-02 17:43:08 +00004303CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004304 // C++ [class.dtor]p2:
4305 // If a class has no user-declared destructor, a destructor is
4306 // declared implicitly. An implicitly-declared destructor is an
4307 // inline public member of its class.
4308
4309 // C++ [except.spec]p14:
4310 // An implicitly declared special member function (Clause 12) shall have
4311 // an exception-specification.
4312 ImplicitExceptionSpecification ExceptSpec(Context);
4313
4314 // Direct base-class destructors.
4315 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4316 BEnd = ClassDecl->bases_end();
4317 B != BEnd; ++B) {
4318 if (B->isVirtual()) // Handled below.
4319 continue;
4320
4321 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4322 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004323 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004324 }
4325
4326 // Virtual base-class destructors.
4327 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4328 BEnd = ClassDecl->vbases_end();
4329 B != BEnd; ++B) {
4330 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4331 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004332 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004333 }
4334
4335 // Field destructors.
4336 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4337 FEnd = ClassDecl->field_end();
4338 F != FEnd; ++F) {
4339 if (const RecordType *RecordTy
4340 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4341 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004342 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004343 }
4344
Douglas Gregor7454c562010-07-02 20:37:36 +00004345 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00004346 QualType Ty = Context.getFunctionType(Context.VoidTy,
4347 0, 0, false, 0,
4348 ExceptSpec.hasExceptionSpecification(),
4349 ExceptSpec.hasAnyExceptionSpecification(),
4350 ExceptSpec.size(),
4351 ExceptSpec.data(),
4352 FunctionType::ExtInfo());
4353
4354 CanQualType ClassType
4355 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4356 DeclarationName Name
4357 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004358 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004359 CXXDestructorDecl *Destructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004360 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty,
Douglas Gregorf1203042010-07-01 19:09:28 +00004361 /*isInline=*/true,
4362 /*isImplicitlyDeclared=*/true);
4363 Destructor->setAccess(AS_public);
4364 Destructor->setImplicit();
4365 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004366
4367 // Note that we have declared this destructor.
4368 ClassDecl->setDeclaredDestructor(true);
4369 ++ASTContext::NumImplicitDestructorsDeclared;
4370
4371 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004372 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004373 PushOnScopeChains(Destructor, S, false);
4374 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004375
4376 // This could be uniqued if it ever proves significant.
4377 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4378
4379 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004380
Douglas Gregorf1203042010-07-01 19:09:28 +00004381 return Destructor;
4382}
4383
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004384void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004385 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004386 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004387 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004388 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004389 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004390
Douglas Gregor54818f02010-05-12 16:39:35 +00004391 if (Destructor->isInvalidDecl())
4392 return;
4393
Douglas Gregora57478e2010-05-01 15:04:51 +00004394 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004395
Douglas Gregor54818f02010-05-12 16:39:35 +00004396 ErrorTrap Trap(*this);
John McCalla6309952010-03-16 21:39:52 +00004397 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4398 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004399
Douglas Gregor54818f02010-05-12 16:39:35 +00004400 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004401 Diag(CurrentLocation, diag::note_member_synthesized_at)
4402 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4403
4404 Destructor->setInvalidDecl();
4405 return;
4406 }
4407
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004408 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004409 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004410}
4411
Douglas Gregorb139cd52010-05-01 20:49:11 +00004412/// \brief Builds a statement that copies the given entity from \p From to
4413/// \c To.
4414///
4415/// This routine is used to copy the members of a class with an
4416/// implicitly-declared copy assignment operator. When the entities being
4417/// copied are arrays, this routine builds for loops to copy them.
4418///
4419/// \param S The Sema object used for type-checking.
4420///
4421/// \param Loc The location where the implicit copy is being generated.
4422///
4423/// \param T The type of the expressions being copied. Both expressions must
4424/// have this type.
4425///
4426/// \param To The expression we are copying to.
4427///
4428/// \param From The expression we are copying from.
4429///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004430/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4431/// Otherwise, it's a non-static member subobject.
4432///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004433/// \param Depth Internal parameter recording the depth of the recursion.
4434///
4435/// \returns A statement or a loop that copies the expressions.
4436static Sema::OwningStmtResult
4437BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4438 Sema::OwningExprResult To, Sema::OwningExprResult From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004439 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004440 typedef Sema::OwningStmtResult OwningStmtResult;
4441 typedef Sema::OwningExprResult OwningExprResult;
4442
4443 // C++0x [class.copy]p30:
4444 // Each subobject is assigned in the manner appropriate to its type:
4445 //
4446 // - if the subobject is of class type, the copy assignment operator
4447 // for the class is used (as if by explicit qualification; that is,
4448 // ignoring any possible virtual overriding functions in more derived
4449 // classes);
4450 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4451 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4452
4453 // Look for operator=.
4454 DeclarationName Name
4455 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4456 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4457 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4458
4459 // Filter out any result that isn't a copy-assignment operator.
4460 LookupResult::Filter F = OpLookup.makeFilter();
4461 while (F.hasNext()) {
4462 NamedDecl *D = F.next();
4463 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4464 if (Method->isCopyAssignmentOperator())
4465 continue;
4466
4467 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004468 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004469 F.done();
4470
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004471 // Suppress the protected check (C++ [class.protected]) for each of the
4472 // assignment operators we found. This strange dance is required when
4473 // we're assigning via a base classes's copy-assignment operator. To
4474 // ensure that we're getting the right base class subobject (without
4475 // ambiguities), we need to cast "this" to that subobject type; to
4476 // ensure that we don't go through the virtual call mechanism, we need
4477 // to qualify the operator= name with the base class (see below). However,
4478 // this means that if the base class has a protected copy assignment
4479 // operator, the protected member access check will fail. So, we
4480 // rewrite "protected" access to "public" access in this case, since we
4481 // know by construction that we're calling from a derived class.
4482 if (CopyingBaseSubobject) {
4483 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4484 L != LEnd; ++L) {
4485 if (L.getAccess() == AS_protected)
4486 L.setAccess(AS_public);
4487 }
4488 }
4489
Douglas Gregorb139cd52010-05-01 20:49:11 +00004490 // Create the nested-name-specifier that will be used to qualify the
4491 // reference to operator=; this is required to suppress the virtual
4492 // call mechanism.
4493 CXXScopeSpec SS;
4494 SS.setRange(Loc);
4495 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4496 T.getTypePtr()));
4497
4498 // Create the reference to operator=.
4499 OwningExprResult OpEqualRef
4500 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4501 /*FirstQualifierInScope=*/0, OpLookup,
4502 /*TemplateArgs=*/0,
4503 /*SuppressQualifierCheck=*/true);
4504 if (OpEqualRef.isInvalid())
4505 return S.StmtError();
4506
4507 // Build the call to the assignment operator.
4508 Expr *FromE = From.takeAs<Expr>();
4509 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4510 OpEqualRef.takeAs<Expr>(),
4511 Loc, &FromE, 1, 0, Loc);
4512 if (Call.isInvalid())
4513 return S.StmtError();
4514
4515 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004516 }
John McCallab8c2732010-03-16 06:11:48 +00004517
Douglas Gregorb139cd52010-05-01 20:49:11 +00004518 // - if the subobject is of scalar type, the built-in assignment
4519 // operator is used.
4520 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4521 if (!ArrayTy) {
4522 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4523 BinaryOperator::Assign,
4524 To.takeAs<Expr>(),
4525 From.takeAs<Expr>());
4526 if (Assignment.isInvalid())
4527 return S.StmtError();
4528
4529 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004530 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004531
4532 // - if the subobject is an array, each element is assigned, in the
4533 // manner appropriate to the element type;
4534
4535 // Construct a loop over the array bounds, e.g.,
4536 //
4537 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4538 //
4539 // that will copy each of the array elements.
4540 QualType SizeType = S.Context.getSizeType();
4541
4542 // Create the iteration variable.
4543 IdentifierInfo *IterationVarName = 0;
4544 {
4545 llvm::SmallString<8> Str;
4546 llvm::raw_svector_ostream OS(Str);
4547 OS << "__i" << Depth;
4548 IterationVarName = &S.Context.Idents.get(OS.str());
4549 }
4550 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4551 IterationVarName, SizeType,
4552 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4553 VarDecl::None, VarDecl::None);
4554
4555 // Initialize the iteration variable to zero.
4556 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4557 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4558
4559 // Create a reference to the iteration variable; we'll use this several
4560 // times throughout.
4561 Expr *IterationVarRef
4562 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4563 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4564
4565 // Create the DeclStmt that holds the iteration variable.
4566 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4567
4568 // Create the comparison against the array bound.
4569 llvm::APInt Upper = ArrayTy->getSize();
4570 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4571 OwningExprResult Comparison
4572 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4573 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4574 BinaryOperator::NE, S.Context.BoolTy, Loc));
4575
4576 // Create the pre-increment of the iteration variable.
4577 OwningExprResult Increment
4578 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4579 UnaryOperator::PreInc,
4580 SizeType, Loc));
4581
4582 // Subscript the "from" and "to" expressions with the iteration variable.
4583 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4584 S.Owned(IterationVarRef->Retain()),
4585 Loc);
4586 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4587 S.Owned(IterationVarRef->Retain()),
4588 Loc);
4589 assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4590 assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4591
4592 // Build the copy for an individual element of the array.
4593 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4594 ArrayTy->getElementType(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004595 move(To), move(From),
4596 CopyingBaseSubobject, Depth+1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004597 if (Copy.isInvalid())
Douglas Gregorb139cd52010-05-01 20:49:11 +00004598 return S.StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004599
4600 // Construct the loop that copies all elements of this array.
4601 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4602 S.MakeFullExpr(Comparison),
4603 Sema::DeclPtrTy(),
4604 S.MakeFullExpr(Increment),
4605 Loc, move(Copy));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004606}
4607
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004608/// \brief Determine whether the given class has a copy assignment operator
4609/// that accepts a const-qualified argument.
4610static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4611 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4612
4613 if (!Class->hasDeclaredCopyAssignment())
4614 S.DeclareImplicitCopyAssignment(Class);
4615
4616 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4617 DeclarationName OpName
4618 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4619
4620 DeclContext::lookup_const_iterator Op, OpEnd;
4621 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4622 // C++ [class.copy]p9:
4623 // A user-declared copy assignment operator is a non-static non-template
4624 // member function of class X with exactly one parameter of type X, X&,
4625 // const X&, volatile X& or const volatile X&.
4626 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4627 if (!Method)
4628 continue;
4629
4630 if (Method->isStatic())
4631 continue;
4632 if (Method->getPrimaryTemplate())
4633 continue;
4634 const FunctionProtoType *FnType =
4635 Method->getType()->getAs<FunctionProtoType>();
4636 assert(FnType && "Overloaded operator has no prototype.");
4637 // Don't assert on this; an invalid decl might have been left in the AST.
4638 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4639 continue;
4640 bool AcceptsConst = true;
4641 QualType ArgType = FnType->getArgType(0);
4642 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4643 ArgType = Ref->getPointeeType();
4644 // Is it a non-const lvalue reference?
4645 if (!ArgType.isConstQualified())
4646 AcceptsConst = false;
4647 }
4648 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4649 continue;
4650
4651 // We have a single argument of type cv X or cv X&, i.e. we've found the
4652 // copy assignment operator. Return whether it accepts const arguments.
4653 return AcceptsConst;
4654 }
4655 assert(Class->isInvalidDecl() &&
4656 "No copy assignment operator declared in valid code.");
4657 return false;
4658}
4659
Douglas Gregor0be31a22010-07-02 17:43:08 +00004660CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004661 // Note: The following rules are largely analoguous to the copy
4662 // constructor rules. Note that virtual bases are not taken into account
4663 // for determining the argument type of the operator. Note also that
4664 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004665
4666
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004667 // C++ [class.copy]p10:
4668 // If the class definition does not explicitly declare a copy
4669 // assignment operator, one is declared implicitly.
4670 // The implicitly-defined copy assignment operator for a class X
4671 // will have the form
4672 //
4673 // X& X::operator=(const X&)
4674 //
4675 // if
4676 bool HasConstCopyAssignment = true;
4677
4678 // -- each direct base class B of X has a copy assignment operator
4679 // whose parameter is of type const B&, const volatile B& or B,
4680 // and
4681 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4682 BaseEnd = ClassDecl->bases_end();
4683 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4684 assert(!Base->getType()->isDependentType() &&
4685 "Cannot generate implicit members for class with dependent bases.");
4686 const CXXRecordDecl *BaseClassDecl
4687 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004688 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004689 }
4690
4691 // -- for all the nonstatic data members of X that are of a class
4692 // type M (or array thereof), each such class type has a copy
4693 // assignment operator whose parameter is of type const M&,
4694 // const volatile M& or M.
4695 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4696 FieldEnd = ClassDecl->field_end();
4697 HasConstCopyAssignment && Field != FieldEnd;
4698 ++Field) {
4699 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4700 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4701 const CXXRecordDecl *FieldClassDecl
4702 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004703 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004704 }
4705 }
4706
4707 // Otherwise, the implicitly declared copy assignment operator will
4708 // have the form
4709 //
4710 // X& X::operator=(X&)
4711 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4712 QualType RetType = Context.getLValueReferenceType(ArgType);
4713 if (HasConstCopyAssignment)
4714 ArgType = ArgType.withConst();
4715 ArgType = Context.getLValueReferenceType(ArgType);
4716
Douglas Gregor68e11362010-07-01 17:48:08 +00004717 // C++ [except.spec]p14:
4718 // An implicitly declared special member function (Clause 12) shall have an
4719 // exception-specification. [...]
4720 ImplicitExceptionSpecification ExceptSpec(Context);
4721 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4722 BaseEnd = ClassDecl->bases_end();
4723 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004724 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004725 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004726
4727 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4728 DeclareImplicitCopyAssignment(BaseClassDecl);
4729
Douglas Gregor68e11362010-07-01 17:48:08 +00004730 if (CXXMethodDecl *CopyAssign
4731 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4732 ExceptSpec.CalledDecl(CopyAssign);
4733 }
4734 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4735 FieldEnd = ClassDecl->field_end();
4736 Field != FieldEnd;
4737 ++Field) {
4738 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4739 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004740 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004741 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004742
4743 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4744 DeclareImplicitCopyAssignment(FieldClassDecl);
4745
Douglas Gregor68e11362010-07-01 17:48:08 +00004746 if (CXXMethodDecl *CopyAssign
4747 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4748 ExceptSpec.CalledDecl(CopyAssign);
4749 }
4750 }
4751
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004752 // An implicitly-declared copy assignment operator is an inline public
4753 // member of its class.
4754 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004755 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004756 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004757 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004758 Context.getFunctionType(RetType, &ArgType, 1,
4759 false, 0,
Douglas Gregor68e11362010-07-01 17:48:08 +00004760 ExceptSpec.hasExceptionSpecification(),
4761 ExceptSpec.hasAnyExceptionSpecification(),
4762 ExceptSpec.size(),
4763 ExceptSpec.data(),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004764 FunctionType::ExtInfo()),
4765 /*TInfo=*/0, /*isStatic=*/false,
4766 /*StorageClassAsWritten=*/FunctionDecl::None,
4767 /*isInline=*/true);
4768 CopyAssignment->setAccess(AS_public);
4769 CopyAssignment->setImplicit();
4770 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
4771 CopyAssignment->setCopyAssignment(true);
4772
4773 // Add the parameter to the operator.
4774 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4775 ClassDecl->getLocation(),
4776 /*Id=*/0,
4777 ArgType, /*TInfo=*/0,
4778 VarDecl::None,
4779 VarDecl::None, 0);
4780 CopyAssignment->setParams(&FromParam, 1);
4781
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004782 // Note that we have added this copy-assignment operator.
4783 ClassDecl->setDeclaredCopyAssignment(true);
4784 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4785
Douglas Gregor0be31a22010-07-02 17:43:08 +00004786 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004787 PushOnScopeChains(CopyAssignment, S, false);
4788 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004789
4790 AddOverriddenMethods(ClassDecl, CopyAssignment);
4791 return CopyAssignment;
4792}
4793
Douglas Gregorb139cd52010-05-01 20:49:11 +00004794void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4795 CXXMethodDecl *CopyAssignOperator) {
4796 assert((CopyAssignOperator->isImplicit() &&
4797 CopyAssignOperator->isOverloadedOperator() &&
4798 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004799 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004800 "DefineImplicitCopyAssignment called for wrong function");
4801
4802 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4803
4804 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4805 CopyAssignOperator->setInvalidDecl();
4806 return;
4807 }
4808
4809 CopyAssignOperator->setUsed();
4810
4811 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregor54818f02010-05-12 16:39:35 +00004812 ErrorTrap Trap(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004813
4814 // C++0x [class.copy]p30:
4815 // The implicitly-defined or explicitly-defaulted copy assignment operator
4816 // for a non-union class X performs memberwise copy assignment of its
4817 // subobjects. The direct base classes of X are assigned first, in the
4818 // order of their declaration in the base-specifier-list, and then the
4819 // immediate non-static data members of X are assigned, in the order in
4820 // which they were declared in the class definition.
4821
4822 // The statements that form the synthesized function body.
4823 ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this);
4824
4825 // The parameter for the "other" object, which we are copying from.
4826 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4827 Qualifiers OtherQuals = Other->getType().getQualifiers();
4828 QualType OtherRefType = Other->getType();
4829 if (const LValueReferenceType *OtherRef
4830 = OtherRefType->getAs<LValueReferenceType>()) {
4831 OtherRefType = OtherRef->getPointeeType();
4832 OtherQuals = OtherRefType.getQualifiers();
4833 }
4834
4835 // Our location for everything implicitly-generated.
4836 SourceLocation Loc = CopyAssignOperator->getLocation();
4837
4838 // Construct a reference to the "other" object. We'll be using this
4839 // throughout the generated ASTs.
4840 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4841 assert(OtherRef && "Reference to parameter cannot fail!");
4842
4843 // Construct the "this" pointer. We'll be using this throughout the generated
4844 // ASTs.
4845 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4846 assert(This && "Reference to this cannot fail!");
4847
4848 // Assign base classes.
4849 bool Invalid = false;
4850 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4851 E = ClassDecl->bases_end(); Base != E; ++Base) {
4852 // Form the assignment:
4853 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4854 QualType BaseType = Base->getType().getUnqualifiedType();
4855 CXXRecordDecl *BaseClassDecl = 0;
4856 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4857 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4858 else {
4859 Invalid = true;
4860 continue;
4861 }
4862
John McCallcf142162010-08-07 06:22:56 +00004863 CXXCastPath BasePath;
4864 BasePath.push_back(Base);
4865
Douglas Gregorb139cd52010-05-01 20:49:11 +00004866 // Construct the "from" expression, which is an implicit cast to the
4867 // appropriately-qualified base type.
4868 Expr *From = OtherRef->Retain();
4869 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004870 CastExpr::CK_UncheckedDerivedToBase,
John McCallcf142162010-08-07 06:22:56 +00004871 ImplicitCastExpr::LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004872
4873 // Dereference "this".
4874 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4875 Owned(This->Retain()));
4876
4877 // Implicitly cast "this" to the appropriately-qualified base type.
4878 Expr *ToE = To.takeAs<Expr>();
4879 ImpCastExprToType(ToE,
4880 Context.getCVRQualifiedType(BaseType,
4881 CopyAssignOperator->getTypeQualifiers()),
4882 CastExpr::CK_UncheckedDerivedToBase,
John McCallcf142162010-08-07 06:22:56 +00004883 ImplicitCastExpr::LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004884 To = Owned(ToE);
4885
4886 // Build the copy.
4887 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004888 move(To), Owned(From),
4889 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004890 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004891 Diag(CurrentLocation, diag::note_member_synthesized_at)
4892 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4893 CopyAssignOperator->setInvalidDecl();
4894 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004895 }
4896
4897 // Success! Record the copy.
4898 Statements.push_back(Copy.takeAs<Expr>());
4899 }
4900
4901 // \brief Reference to the __builtin_memcpy function.
4902 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004903 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004904 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004905
4906 // Assign non-static members.
4907 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4908 FieldEnd = ClassDecl->field_end();
4909 Field != FieldEnd; ++Field) {
4910 // Check for members of reference type; we can't copy those.
4911 if (Field->getType()->isReferenceType()) {
4912 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4913 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4914 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004915 Diag(CurrentLocation, diag::note_member_synthesized_at)
4916 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004917 Invalid = true;
4918 continue;
4919 }
4920
4921 // Check for members of const-qualified, non-class type.
4922 QualType BaseType = Context.getBaseElementType(Field->getType());
4923 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4924 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4925 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4926 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004927 Diag(CurrentLocation, diag::note_member_synthesized_at)
4928 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004929 Invalid = true;
4930 continue;
4931 }
4932
4933 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004934 if (FieldType->isIncompleteArrayType()) {
4935 assert(ClassDecl->hasFlexibleArrayMember() &&
4936 "Incomplete array type is not valid");
4937 continue;
4938 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004939
4940 // Build references to the field in the object we're copying from and to.
4941 CXXScopeSpec SS; // Intentionally empty
4942 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4943 LookupMemberName);
4944 MemberLookup.addDecl(*Field);
4945 MemberLookup.resolveKind();
4946 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
4947 OtherRefType,
4948 Loc, /*IsArrow=*/false,
4949 SS, 0, MemberLookup, 0);
4950 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
4951 This->getType(),
4952 Loc, /*IsArrow=*/true,
4953 SS, 0, MemberLookup, 0);
4954 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4955 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4956
4957 // If the field should be copied with __builtin_memcpy rather than via
4958 // explicit assignments, do so. This optimization only applies for arrays
4959 // of scalars and arrays of class type with trivial copy-assignment
4960 // operators.
4961 if (FieldType->isArrayType() &&
4962 (!BaseType->isRecordType() ||
4963 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4964 ->hasTrivialCopyAssignment())) {
4965 // Compute the size of the memory buffer to be copied.
4966 QualType SizeType = Context.getSizeType();
4967 llvm::APInt Size(Context.getTypeSize(SizeType),
4968 Context.getTypeSizeInChars(BaseType).getQuantity());
4969 for (const ConstantArrayType *Array
4970 = Context.getAsConstantArrayType(FieldType);
4971 Array;
4972 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4973 llvm::APInt ArraySize = Array->getSize();
4974 ArraySize.zextOrTrunc(Size.getBitWidth());
4975 Size *= ArraySize;
4976 }
4977
4978 // Take the address of the field references for "from" and "to".
4979 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
4980 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004981
4982 bool NeedsCollectableMemCpy =
4983 (BaseType->isRecordType() &&
4984 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
4985
4986 if (NeedsCollectableMemCpy) {
4987 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004988 // Create a reference to the __builtin_objc_memmove_collectable function.
4989 LookupResult R(*this,
4990 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004991 Loc, LookupOrdinaryName);
4992 LookupName(R, TUScope, true);
4993
4994 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
4995 if (!CollectableMemCpy) {
4996 // Something went horribly wrong earlier, and we will have
4997 // complained about it.
4998 Invalid = true;
4999 continue;
5000 }
5001
5002 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
5003 CollectableMemCpy->getType(),
5004 Loc, 0).takeAs<Expr>();
5005 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
5006 }
5007 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005008 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005009 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005010 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5011 LookupOrdinaryName);
5012 LookupName(R, TUScope, true);
5013
5014 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5015 if (!BuiltinMemCpy) {
5016 // Something went horribly wrong earlier, and we will have complained
5017 // about it.
5018 Invalid = true;
5019 continue;
5020 }
5021
5022 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5023 BuiltinMemCpy->getType(),
5024 Loc, 0).takeAs<Expr>();
5025 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5026 }
5027
5028 ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this);
5029 CallArgs.push_back(To.takeAs<Expr>());
5030 CallArgs.push_back(From.takeAs<Expr>());
5031 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
5032 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
5033 Commas.push_back(Loc);
5034 Commas.push_back(Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005035 OwningExprResult Call = ExprError();
5036 if (NeedsCollectableMemCpy)
5037 Call = ActOnCallExpr(/*Scope=*/0,
5038 Owned(CollectableMemCpyRef->Retain()),
5039 Loc, move_arg(CallArgs),
5040 Commas.data(), Loc);
5041 else
5042 Call = ActOnCallExpr(/*Scope=*/0,
5043 Owned(BuiltinMemCpyRef->Retain()),
5044 Loc, move_arg(CallArgs),
5045 Commas.data(), Loc);
5046
Douglas Gregorb139cd52010-05-01 20:49:11 +00005047 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5048 Statements.push_back(Call.takeAs<Expr>());
5049 continue;
5050 }
5051
5052 // Build the copy of this field.
5053 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005054 move(To), move(From),
5055 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005056 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005057 Diag(CurrentLocation, diag::note_member_synthesized_at)
5058 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5059 CopyAssignOperator->setInvalidDecl();
5060 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005061 }
5062
5063 // Success! Record the copy.
5064 Statements.push_back(Copy.takeAs<Stmt>());
5065 }
5066
5067 if (!Invalid) {
5068 // Add a "return *this;"
5069 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
5070 Owned(This->Retain()));
5071
5072 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
5073 if (Return.isInvalid())
5074 Invalid = true;
5075 else {
5076 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005077
5078 if (Trap.hasErrorOccurred()) {
5079 Diag(CurrentLocation, diag::note_member_synthesized_at)
5080 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5081 Invalid = true;
5082 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005083 }
5084 }
5085
5086 if (Invalid) {
5087 CopyAssignOperator->setInvalidDecl();
5088 return;
5089 }
5090
5091 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
5092 /*isStmtExpr=*/false);
5093 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5094 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005095}
5096
Douglas Gregor0be31a22010-07-02 17:43:08 +00005097CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5098 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005099 // C++ [class.copy]p4:
5100 // If the class definition does not explicitly declare a copy
5101 // constructor, one is declared implicitly.
5102
Douglas Gregor54be3392010-07-01 17:57:27 +00005103 // C++ [class.copy]p5:
5104 // The implicitly-declared copy constructor for a class X will
5105 // have the form
5106 //
5107 // X::X(const X&)
5108 //
5109 // if
5110 bool HasConstCopyConstructor = true;
5111
5112 // -- each direct or virtual base class B of X has a copy
5113 // constructor whose first parameter is of type const B& or
5114 // const volatile B&, and
5115 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5116 BaseEnd = ClassDecl->bases_end();
5117 HasConstCopyConstructor && Base != BaseEnd;
5118 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005119 // Virtual bases are handled below.
5120 if (Base->isVirtual())
5121 continue;
5122
Douglas Gregora6d69502010-07-02 23:41:54 +00005123 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005124 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005125 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5126 DeclareImplicitCopyConstructor(BaseClassDecl);
5127
Douglas Gregorcfe68222010-07-01 18:27:03 +00005128 HasConstCopyConstructor
5129 = BaseClassDecl->hasConstCopyConstructor(Context);
5130 }
5131
5132 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5133 BaseEnd = ClassDecl->vbases_end();
5134 HasConstCopyConstructor && Base != BaseEnd;
5135 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005136 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005137 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005138 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5139 DeclareImplicitCopyConstructor(BaseClassDecl);
5140
Douglas Gregor54be3392010-07-01 17:57:27 +00005141 HasConstCopyConstructor
5142 = BaseClassDecl->hasConstCopyConstructor(Context);
5143 }
5144
5145 // -- for all the nonstatic data members of X that are of a
5146 // class type M (or array thereof), each such class type
5147 // has a copy constructor whose first parameter is of type
5148 // const M& or const volatile M&.
5149 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5150 FieldEnd = ClassDecl->field_end();
5151 HasConstCopyConstructor && Field != FieldEnd;
5152 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005153 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005154 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005155 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005156 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005157 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5158 DeclareImplicitCopyConstructor(FieldClassDecl);
5159
Douglas Gregor54be3392010-07-01 17:57:27 +00005160 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005161 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005162 }
5163 }
5164
5165 // Otherwise, the implicitly declared copy constructor will have
5166 // the form
5167 //
5168 // X::X(X&)
5169 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5170 QualType ArgType = ClassType;
5171 if (HasConstCopyConstructor)
5172 ArgType = ArgType.withConst();
5173 ArgType = Context.getLValueReferenceType(ArgType);
5174
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005175 // C++ [except.spec]p14:
5176 // An implicitly declared special member function (Clause 12) shall have an
5177 // exception-specification. [...]
5178 ImplicitExceptionSpecification ExceptSpec(Context);
5179 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5180 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5181 BaseEnd = ClassDecl->bases_end();
5182 Base != BaseEnd;
5183 ++Base) {
5184 // Virtual bases are handled below.
5185 if (Base->isVirtual())
5186 continue;
5187
Douglas Gregora6d69502010-07-02 23:41:54 +00005188 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005189 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005190 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5191 DeclareImplicitCopyConstructor(BaseClassDecl);
5192
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005193 if (CXXConstructorDecl *CopyConstructor
5194 = BaseClassDecl->getCopyConstructor(Context, Quals))
5195 ExceptSpec.CalledDecl(CopyConstructor);
5196 }
5197 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5198 BaseEnd = ClassDecl->vbases_end();
5199 Base != BaseEnd;
5200 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005201 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005202 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005203 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5204 DeclareImplicitCopyConstructor(BaseClassDecl);
5205
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005206 if (CXXConstructorDecl *CopyConstructor
5207 = BaseClassDecl->getCopyConstructor(Context, Quals))
5208 ExceptSpec.CalledDecl(CopyConstructor);
5209 }
5210 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5211 FieldEnd = ClassDecl->field_end();
5212 Field != FieldEnd;
5213 ++Field) {
5214 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5215 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005216 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005217 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005218 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5219 DeclareImplicitCopyConstructor(FieldClassDecl);
5220
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005221 if (CXXConstructorDecl *CopyConstructor
5222 = FieldClassDecl->getCopyConstructor(Context, Quals))
5223 ExceptSpec.CalledDecl(CopyConstructor);
5224 }
5225 }
5226
Douglas Gregor54be3392010-07-01 17:57:27 +00005227 // An implicitly-declared copy constructor is an inline public
5228 // member of its class.
5229 DeclarationName Name
5230 = Context.DeclarationNames.getCXXConstructorName(
5231 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005232 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005233 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005234 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005235 Context.getFunctionType(Context.VoidTy,
5236 &ArgType, 1,
5237 false, 0,
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005238 ExceptSpec.hasExceptionSpecification(),
5239 ExceptSpec.hasAnyExceptionSpecification(),
5240 ExceptSpec.size(),
5241 ExceptSpec.data(),
Douglas Gregor54be3392010-07-01 17:57:27 +00005242 FunctionType::ExtInfo()),
5243 /*TInfo=*/0,
5244 /*isExplicit=*/false,
5245 /*isInline=*/true,
5246 /*isImplicitlyDeclared=*/true);
5247 CopyConstructor->setAccess(AS_public);
5248 CopyConstructor->setImplicit();
5249 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5250
Douglas Gregora6d69502010-07-02 23:41:54 +00005251 // Note that we have declared this constructor.
5252 ClassDecl->setDeclaredCopyConstructor(true);
5253 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5254
Douglas Gregor54be3392010-07-01 17:57:27 +00005255 // Add the parameter to the constructor.
5256 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5257 ClassDecl->getLocation(),
5258 /*IdentifierInfo=*/0,
5259 ArgType, /*TInfo=*/0,
5260 VarDecl::None,
5261 VarDecl::None, 0);
5262 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005263 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005264 PushOnScopeChains(CopyConstructor, S, false);
5265 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005266
5267 return CopyConstructor;
5268}
5269
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005270void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5271 CXXConstructorDecl *CopyConstructor,
5272 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005273 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005274 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005275 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005276 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005277
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005278 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005279 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005280
Douglas Gregora57478e2010-05-01 15:04:51 +00005281 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00005282 ErrorTrap Trap(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005283
Douglas Gregor54818f02010-05-12 16:39:35 +00005284 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5285 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005286 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005287 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005288 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005289 } else {
5290 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5291 CopyConstructor->getLocation(),
5292 MultiStmtArg(*this, 0, 0),
5293 /*isStmtExpr=*/false)
5294 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005295 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005296
5297 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005298}
5299
Anders Carlsson6eb55572009-08-25 05:12:04 +00005300Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005301Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005302 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005303 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005304 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00005305 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005306 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005307
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005308 // C++0x [class.copy]p34:
5309 // When certain criteria are met, an implementation is allowed to
5310 // omit the copy/move construction of a class object, even if the
5311 // copy/move constructor and/or destructor for the object have
5312 // side effects. [...]
5313 // - when a temporary class object that has not been bound to a
5314 // reference (12.2) would be copied/moved to a class object
5315 // with the same cv-unqualified type, the copy/move operation
5316 // can be omitted by constructing the temporary object
5317 // directly into the target of the omitted copy/move
5318 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
5319 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
5320 Elidable = SubExpr->isTemporaryObject() &&
5321 Context.hasSameUnqualifiedType(SubExpr->getType(),
5322 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson250aada2009-08-16 05:13:48 +00005323 }
Mike Stump11289f42009-09-09 15:08:12 +00005324
5325 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005326 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00005327 ConstructKind);
Anders Carlsson250aada2009-08-16 05:13:48 +00005328}
5329
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005330/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5331/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00005332Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005333Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5334 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005335 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005336 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00005337 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005338 unsigned NumExprs = ExprArgs.size();
5339 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005340
Douglas Gregor27381f32009-11-23 12:27:39 +00005341 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005342 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005343 Constructor, Elidable, Exprs, NumExprs,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00005344 RequiresZeroInit, ConstructKind));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005345}
5346
Mike Stump11289f42009-09-09 15:08:12 +00005347bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005348 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005349 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00005350 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005351 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005352 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005353 if (TempResult.isInvalid())
5354 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005355
Anders Carlsson6eb55572009-08-25 05:12:04 +00005356 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00005357 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00005358 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005359 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005360
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005361 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005362}
5363
John McCall03c48482010-02-02 09:10:11 +00005364void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5365 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005366 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005367 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005368 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005369 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005370 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005371 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005372 << VD->getDeclName()
5373 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005374
5375 if (!VD->isInvalidDecl() && VD->hasGlobalStorage())
5376 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005377 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005378}
5379
Mike Stump11289f42009-09-09 15:08:12 +00005380/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005381/// ActOnDeclarator, when a C++ direct initializer is present.
5382/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00005383void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
5384 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005385 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005386 SourceLocation *CommaLocs,
5387 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005388 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00005389 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005390
5391 // If there is no declaration, there was an error parsing it. Just ignore
5392 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005393 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005394 return;
Mike Stump11289f42009-09-09 15:08:12 +00005395
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005396 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5397 if (!VDecl) {
5398 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5399 RealDecl->setInvalidDecl();
5400 return;
5401 }
5402
Douglas Gregor402250f2009-08-26 21:14:46 +00005403 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005404 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005405 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5406 //
5407 // Clients that want to distinguish between the two forms, can check for
5408 // direct initializer using VarDecl::hasCXXDirectInitializer().
5409 // A major benefit is that clients that don't particularly care about which
5410 // exactly form was it (like the CodeGen) can handle both cases without
5411 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005412
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005413 // C++ 8.5p11:
5414 // The form of initialization (using parentheses or '=') is generally
5415 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005416 // class type.
5417
Douglas Gregor50dc2192010-02-11 22:55:30 +00005418 if (!VDecl->getType()->isDependentType() &&
5419 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005420 diag::err_typecheck_decl_incomplete_type)) {
5421 VDecl->setInvalidDecl();
5422 return;
5423 }
5424
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005425 // The variable can not have an abstract class type.
5426 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5427 diag::err_abstract_type_in_decl,
5428 AbstractVariableType))
5429 VDecl->setInvalidDecl();
5430
Sebastian Redl5ca79842010-02-01 20:16:42 +00005431 const VarDecl *Def;
5432 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005433 Diag(VDecl->getLocation(), diag::err_redefinition)
5434 << VDecl->getDeclName();
5435 Diag(Def->getLocation(), diag::note_previous_definition);
5436 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005437 return;
5438 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005439
5440 // If either the declaration has a dependent type or if any of the
5441 // expressions is type-dependent, we represent the initialization
5442 // via a ParenListExpr for later use during template instantiation.
5443 if (VDecl->getType()->isDependentType() ||
5444 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5445 // Let clients know that initialization was done with a direct initializer.
5446 VDecl->setCXXDirectInitializer(true);
5447
5448 // Store the initialization expressions as a ParenListExpr.
5449 unsigned NumExprs = Exprs.size();
5450 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5451 (Expr **)Exprs.release(),
5452 NumExprs, RParenLoc));
5453 return;
5454 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005455
5456 // Capture the variable that is being initialized and the style of
5457 // initialization.
5458 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5459
5460 // FIXME: Poor source location information.
5461 InitializationKind Kind
5462 = InitializationKind::CreateDirect(VDecl->getLocation(),
5463 LParenLoc, RParenLoc);
5464
5465 InitializationSequence InitSeq(*this, Entity, Kind,
5466 (Expr**)Exprs.get(), Exprs.size());
5467 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
5468 if (Result.isInvalid()) {
5469 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005470 return;
5471 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005472
5473 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregord5058122010-02-11 01:19:42 +00005474 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005475 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005476
John McCall8b0f4ff2010-08-02 21:13:48 +00005477 if (!VDecl->isInvalidDecl() &&
5478 !VDecl->getDeclContext()->isDependentContext() &&
5479 VDecl->hasGlobalStorage() &&
5480 !VDecl->getInit()->isConstantInitializer(Context,
5481 VDecl->getType()->isReferenceType()))
5482 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5483 << VDecl->getInit()->getSourceRange();
5484
John McCall03c48482010-02-02 09:10:11 +00005485 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5486 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005487}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005488
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005489/// \brief Given a constructor and the set of arguments provided for the
5490/// constructor, convert the arguments and add any required default arguments
5491/// to form a proper call to this constructor.
5492///
5493/// \returns true if an error occurred, false otherwise.
5494bool
5495Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5496 MultiExprArg ArgsPtr,
5497 SourceLocation Loc,
5498 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
5499 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5500 unsigned NumArgs = ArgsPtr.size();
5501 Expr **Args = (Expr **)ArgsPtr.get();
5502
5503 const FunctionProtoType *Proto
5504 = Constructor->getType()->getAs<FunctionProtoType>();
5505 assert(Proto && "Constructor without a prototype?");
5506 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005507
5508 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005509 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005510 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005511 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005512 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005513
5514 VariadicCallType CallType =
5515 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5516 llvm::SmallVector<Expr *, 8> AllArgs;
5517 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5518 Proto, 0, Args, NumArgs, AllArgs,
5519 CallType);
5520 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5521 ConvertedArgs.push_back(AllArgs[i]);
5522 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005523}
5524
Anders Carlssone363c8e2009-12-12 00:32:00 +00005525static inline bool
5526CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5527 const FunctionDecl *FnDecl) {
5528 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
5529 if (isa<NamespaceDecl>(DC)) {
5530 return SemaRef.Diag(FnDecl->getLocation(),
5531 diag::err_operator_new_delete_declared_in_namespace)
5532 << FnDecl->getDeclName();
5533 }
5534
5535 if (isa<TranslationUnitDecl>(DC) &&
5536 FnDecl->getStorageClass() == FunctionDecl::Static) {
5537 return SemaRef.Diag(FnDecl->getLocation(),
5538 diag::err_operator_new_delete_declared_static)
5539 << FnDecl->getDeclName();
5540 }
5541
Anders Carlsson60659a82009-12-12 02:43:16 +00005542 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005543}
5544
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005545static inline bool
5546CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5547 CanQualType ExpectedResultType,
5548 CanQualType ExpectedFirstParamType,
5549 unsigned DependentParamTypeDiag,
5550 unsigned InvalidParamTypeDiag) {
5551 QualType ResultType =
5552 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5553
5554 // Check that the result type is not dependent.
5555 if (ResultType->isDependentType())
5556 return SemaRef.Diag(FnDecl->getLocation(),
5557 diag::err_operator_new_delete_dependent_result_type)
5558 << FnDecl->getDeclName() << ExpectedResultType;
5559
5560 // Check that the result type is what we expect.
5561 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5562 return SemaRef.Diag(FnDecl->getLocation(),
5563 diag::err_operator_new_delete_invalid_result_type)
5564 << FnDecl->getDeclName() << ExpectedResultType;
5565
5566 // A function template must have at least 2 parameters.
5567 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5568 return SemaRef.Diag(FnDecl->getLocation(),
5569 diag::err_operator_new_delete_template_too_few_parameters)
5570 << FnDecl->getDeclName();
5571
5572 // The function decl must have at least 1 parameter.
5573 if (FnDecl->getNumParams() == 0)
5574 return SemaRef.Diag(FnDecl->getLocation(),
5575 diag::err_operator_new_delete_too_few_parameters)
5576 << FnDecl->getDeclName();
5577
5578 // Check the the first parameter type is not dependent.
5579 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5580 if (FirstParamType->isDependentType())
5581 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5582 << FnDecl->getDeclName() << ExpectedFirstParamType;
5583
5584 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005585 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005586 ExpectedFirstParamType)
5587 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5588 << FnDecl->getDeclName() << ExpectedFirstParamType;
5589
5590 return false;
5591}
5592
Anders Carlsson12308f42009-12-11 23:23:22 +00005593static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005594CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005595 // C++ [basic.stc.dynamic.allocation]p1:
5596 // A program is ill-formed if an allocation function is declared in a
5597 // namespace scope other than global scope or declared static in global
5598 // scope.
5599 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5600 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005601
5602 CanQualType SizeTy =
5603 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5604
5605 // C++ [basic.stc.dynamic.allocation]p1:
5606 // The return type shall be void*. The first parameter shall have type
5607 // std::size_t.
5608 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5609 SizeTy,
5610 diag::err_operator_new_dependent_param_type,
5611 diag::err_operator_new_param_type))
5612 return true;
5613
5614 // C++ [basic.stc.dynamic.allocation]p1:
5615 // The first parameter shall not have an associated default argument.
5616 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005617 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005618 diag::err_operator_new_default_arg)
5619 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5620
5621 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005622}
5623
5624static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005625CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5626 // C++ [basic.stc.dynamic.deallocation]p1:
5627 // A program is ill-formed if deallocation functions are declared in a
5628 // namespace scope other than global scope or declared static in global
5629 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005630 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5631 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005632
5633 // C++ [basic.stc.dynamic.deallocation]p2:
5634 // Each deallocation function shall return void and its first parameter
5635 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005636 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5637 SemaRef.Context.VoidPtrTy,
5638 diag::err_operator_delete_dependent_param_type,
5639 diag::err_operator_delete_param_type))
5640 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005641
Anders Carlsson12308f42009-12-11 23:23:22 +00005642 return false;
5643}
5644
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005645/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5646/// of this overloaded operator is well-formed. If so, returns false;
5647/// otherwise, emits appropriate diagnostics and returns true.
5648bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005649 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005650 "Expected an overloaded operator declaration");
5651
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005652 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5653
Mike Stump11289f42009-09-09 15:08:12 +00005654 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005655 // The allocation and deallocation functions, operator new,
5656 // operator new[], operator delete and operator delete[], are
5657 // described completely in 3.7.3. The attributes and restrictions
5658 // found in the rest of this subclause do not apply to them unless
5659 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005660 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005661 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005662
Anders Carlsson22f443f2009-12-12 00:26:23 +00005663 if (Op == OO_New || Op == OO_Array_New)
5664 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005665
5666 // C++ [over.oper]p6:
5667 // An operator function shall either be a non-static member
5668 // function or be a non-member function and have at least one
5669 // parameter whose type is a class, a reference to a class, an
5670 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005671 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5672 if (MethodDecl->isStatic())
5673 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005674 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005675 } else {
5676 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005677 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5678 ParamEnd = FnDecl->param_end();
5679 Param != ParamEnd; ++Param) {
5680 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005681 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5682 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005683 ClassOrEnumParam = true;
5684 break;
5685 }
5686 }
5687
Douglas Gregord69246b2008-11-17 16:14:12 +00005688 if (!ClassOrEnumParam)
5689 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005690 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005691 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005692 }
5693
5694 // C++ [over.oper]p8:
5695 // An operator function cannot have default arguments (8.3.6),
5696 // except where explicitly stated below.
5697 //
Mike Stump11289f42009-09-09 15:08:12 +00005698 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005699 // (C++ [over.call]p1).
5700 if (Op != OO_Call) {
5701 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5702 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005703 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005704 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005705 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005706 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005707 }
5708 }
5709
Douglas Gregor6cf08062008-11-10 13:38:07 +00005710 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5711 { false, false, false }
5712#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5713 , { Unary, Binary, MemberOnly }
5714#include "clang/Basic/OperatorKinds.def"
5715 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005716
Douglas Gregor6cf08062008-11-10 13:38:07 +00005717 bool CanBeUnaryOperator = OperatorUses[Op][0];
5718 bool CanBeBinaryOperator = OperatorUses[Op][1];
5719 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005720
5721 // C++ [over.oper]p8:
5722 // [...] Operator functions cannot have more or fewer parameters
5723 // than the number required for the corresponding operator, as
5724 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005725 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005726 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005727 if (Op != OO_Call &&
5728 ((NumParams == 1 && !CanBeUnaryOperator) ||
5729 (NumParams == 2 && !CanBeBinaryOperator) ||
5730 (NumParams < 1) || (NumParams > 2))) {
5731 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005732 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005733 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005734 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005735 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005736 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005737 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005738 assert(CanBeBinaryOperator &&
5739 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005740 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005741 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005742
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005743 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005744 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005745 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005746
Douglas Gregord69246b2008-11-17 16:14:12 +00005747 // Overloaded operators other than operator() cannot be variadic.
5748 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005749 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005750 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005751 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005752 }
5753
5754 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005755 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5756 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005757 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005758 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005759 }
5760
5761 // C++ [over.inc]p1:
5762 // The user-defined function called operator++ implements the
5763 // prefix and postfix ++ operator. If this function is a member
5764 // function with no parameters, or a non-member function with one
5765 // parameter of class or enumeration type, it defines the prefix
5766 // increment operator ++ for objects of that type. If the function
5767 // is a member function with one parameter (which shall be of type
5768 // int) or a non-member function with two parameters (the second
5769 // of which shall be of type int), it defines the postfix
5770 // increment operator ++ for objects of that type.
5771 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5772 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5773 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005774 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005775 ParamIsInt = BT->getKind() == BuiltinType::Int;
5776
Chris Lattner2b786902008-11-21 07:50:02 +00005777 if (!ParamIsInt)
5778 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005779 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005780 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005781 }
5782
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005783 // Notify the class if it got an assignment operator.
5784 if (Op == OO_Equal) {
5785 // Would have returned earlier otherwise.
5786 assert(isa<CXXMethodDecl>(FnDecl) &&
5787 "Overloaded = not member, but not filtered.");
5788 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5789 Method->getParent()->addedAssignmentOperator(Context, Method);
5790 }
5791
Douglas Gregord69246b2008-11-17 16:14:12 +00005792 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005793}
Chris Lattner3b024a32008-12-17 07:09:26 +00005794
Alexis Huntc88db062010-01-13 09:01:02 +00005795/// CheckLiteralOperatorDeclaration - Check whether the declaration
5796/// of this literal operator function is well-formed. If so, returns
5797/// false; otherwise, emits appropriate diagnostics and returns true.
5798bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5799 DeclContext *DC = FnDecl->getDeclContext();
5800 Decl::Kind Kind = DC->getDeclKind();
5801 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5802 Kind != Decl::LinkageSpec) {
5803 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5804 << FnDecl->getDeclName();
5805 return true;
5806 }
5807
5808 bool Valid = false;
5809
Alexis Hunt7dd26172010-04-07 23:11:06 +00005810 // template <char...> type operator "" name() is the only valid template
5811 // signature, and the only valid signature with no parameters.
5812 if (FnDecl->param_size() == 0) {
5813 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5814 // Must have only one template parameter
5815 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5816 if (Params->size() == 1) {
5817 NonTypeTemplateParmDecl *PmDecl =
5818 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005819
Alexis Hunt7dd26172010-04-07 23:11:06 +00005820 // The template parameter must be a char parameter pack.
5821 // FIXME: This test will always fail because non-type parameter packs
5822 // have not been implemented.
5823 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5824 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5825 Valid = true;
5826 }
5827 }
5828 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005829 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005830 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5831
Alexis Huntc88db062010-01-13 09:01:02 +00005832 QualType T = (*Param)->getType();
5833
Alexis Hunt079a6f72010-04-07 22:57:35 +00005834 // unsigned long long int, long double, and any character type are allowed
5835 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005836 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5837 Context.hasSameType(T, Context.LongDoubleTy) ||
5838 Context.hasSameType(T, Context.CharTy) ||
5839 Context.hasSameType(T, Context.WCharTy) ||
5840 Context.hasSameType(T, Context.Char16Ty) ||
5841 Context.hasSameType(T, Context.Char32Ty)) {
5842 if (++Param == FnDecl->param_end())
5843 Valid = true;
5844 goto FinishedParams;
5845 }
5846
Alexis Hunt079a6f72010-04-07 22:57:35 +00005847 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005848 const PointerType *PT = T->getAs<PointerType>();
5849 if (!PT)
5850 goto FinishedParams;
5851 T = PT->getPointeeType();
5852 if (!T.isConstQualified())
5853 goto FinishedParams;
5854 T = T.getUnqualifiedType();
5855
5856 // Move on to the second parameter;
5857 ++Param;
5858
5859 // If there is no second parameter, the first must be a const char *
5860 if (Param == FnDecl->param_end()) {
5861 if (Context.hasSameType(T, Context.CharTy))
5862 Valid = true;
5863 goto FinishedParams;
5864 }
5865
5866 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5867 // are allowed as the first parameter to a two-parameter function
5868 if (!(Context.hasSameType(T, Context.CharTy) ||
5869 Context.hasSameType(T, Context.WCharTy) ||
5870 Context.hasSameType(T, Context.Char16Ty) ||
5871 Context.hasSameType(T, Context.Char32Ty)))
5872 goto FinishedParams;
5873
5874 // The second and final parameter must be an std::size_t
5875 T = (*Param)->getType().getUnqualifiedType();
5876 if (Context.hasSameType(T, Context.getSizeType()) &&
5877 ++Param == FnDecl->param_end())
5878 Valid = true;
5879 }
5880
5881 // FIXME: This diagnostic is absolutely terrible.
5882FinishedParams:
5883 if (!Valid) {
5884 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5885 << FnDecl->getDeclName();
5886 return true;
5887 }
5888
5889 return false;
5890}
5891
Douglas Gregor07665a62009-01-05 19:45:36 +00005892/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5893/// linkage specification, including the language and (if present)
5894/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5895/// the location of the language string literal, which is provided
5896/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5897/// the '{' brace. Otherwise, this linkage specification does not
5898/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005899Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5900 SourceLocation ExternLoc,
5901 SourceLocation LangLoc,
Benjamin Kramerbebee842010-05-03 13:08:54 +00005902 llvm::StringRef Lang,
Chris Lattner83f095c2009-03-28 19:18:32 +00005903 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005904 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005905 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005906 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005907 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005908 Language = LinkageSpecDecl::lang_cxx;
5909 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005910 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00005911 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00005912 }
Mike Stump11289f42009-09-09 15:08:12 +00005913
Chris Lattner438e5012008-12-17 07:13:27 +00005914 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005915
Douglas Gregor07665a62009-01-05 19:45:36 +00005916 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005917 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005918 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005919 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005920 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005921 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00005922}
5923
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00005924/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00005925/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5926/// valid, it's the position of the closing '}' brace in a linkage
5927/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005928Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5929 DeclPtrTy LinkageSpec,
5930 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005931 if (LinkageSpec)
5932 PopDeclContext();
5933 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005934}
5935
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005936/// \brief Perform semantic analysis for the variable declaration that
5937/// occurs within a C++ catch clause, returning the newly-created
5938/// variable.
5939VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00005940 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005941 IdentifierInfo *Name,
5942 SourceLocation Loc,
5943 SourceRange Range) {
5944 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005945
5946 // Arrays and functions decay.
5947 if (ExDeclType->isArrayType())
5948 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5949 else if (ExDeclType->isFunctionType())
5950 ExDeclType = Context.getPointerType(ExDeclType);
5951
5952 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5953 // The exception-declaration shall not denote a pointer or reference to an
5954 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005955 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005956 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005957 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00005958 Invalid = true;
5959 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005960
Douglas Gregor104ee002010-03-08 01:47:36 +00005961 // GCC allows catching pointers and references to incomplete types
5962 // as an extension; so do we, but we warn by default.
5963
Sebastian Redl54c04d42008-12-22 19:15:10 +00005964 QualType BaseType = ExDeclType;
5965 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005966 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00005967 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005968 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005969 BaseType = Ptr->getPointeeType();
5970 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00005971 DK = diag::ext_catch_incomplete_ptr;
5972 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00005973 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005974 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005975 BaseType = Ref->getPointeeType();
5976 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00005977 DK = diag::ext_catch_incomplete_ref;
5978 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005979 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005980 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00005981 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5982 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00005983 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005984
Mike Stump11289f42009-09-09 15:08:12 +00005985 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005986 RequireNonAbstractType(Loc, ExDeclType,
5987 diag::err_abstract_type_in_decl,
5988 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005989 Invalid = true;
5990
John McCall2ca705e2010-07-24 00:37:23 +00005991 // Only the non-fragile NeXT runtime currently supports C++ catches
5992 // of ObjC types, and no runtime supports catching ObjC types by value.
5993 if (!Invalid && getLangOptions().ObjC1) {
5994 QualType T = ExDeclType;
5995 if (const ReferenceType *RT = T->getAs<ReferenceType>())
5996 T = RT->getPointeeType();
5997
5998 if (T->isObjCObjectType()) {
5999 Diag(Loc, diag::err_objc_object_catch);
6000 Invalid = true;
6001 } else if (T->isObjCObjectPointerType()) {
6002 if (!getLangOptions().NeXTRuntime) {
6003 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6004 Invalid = true;
6005 } else if (!getLangOptions().ObjCNonFragileABI) {
6006 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6007 Invalid = true;
6008 }
6009 }
6010 }
6011
Mike Stump11289f42009-09-09 15:08:12 +00006012 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregorc4df4072010-04-19 22:54:31 +00006013 Name, ExDeclType, TInfo, VarDecl::None,
6014 VarDecl::None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006015 ExDecl->setExceptionVariable(true);
6016
Douglas Gregor6de584c2010-03-05 23:38:39 +00006017 if (!Invalid) {
6018 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6019 // C++ [except.handle]p16:
6020 // The object declared in an exception-declaration or, if the
6021 // exception-declaration does not specify a name, a temporary (12.2) is
6022 // copy-initialized (8.5) from the exception object. [...]
6023 // The object is destroyed when the handler exits, after the destruction
6024 // of any automatic objects initialized within the handler.
6025 //
6026 // We just pretend to initialize the object with itself, then make sure
6027 // it can be destroyed later.
6028 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6029 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6030 Loc, ExDeclType, 0);
6031 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6032 SourceLocation());
6033 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
6034 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
6035 MultiExprArg(*this, (void**)&ExDeclRef, 1));
6036 if (Result.isInvalid())
6037 Invalid = true;
6038 else
6039 FinalizeVarWithDestructor(ExDecl, RecordTy);
6040 }
6041 }
6042
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006043 if (Invalid)
6044 ExDecl->setInvalidDecl();
6045
6046 return ExDecl;
6047}
6048
6049/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6050/// handler.
6051Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006052 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6053 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006054
6055 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00006056 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006057 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006058 LookupOrdinaryName,
6059 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006060 // The scope should be freshly made just for us. There is just no way
6061 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00006062 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006063 if (PrevDecl->isTemplateParameter()) {
6064 // Maybe we will complain about the shadowed template parameter.
6065 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006066 }
6067 }
6068
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006069 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006070 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6071 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006072 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006073 }
6074
John McCallbcd03502009-12-07 02:54:59 +00006075 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006076 D.getIdentifier(),
6077 D.getIdentifierLoc(),
6078 D.getDeclSpec().getSourceRange());
6079
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006080 if (Invalid)
6081 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006082
Sebastian Redl54c04d42008-12-22 19:15:10 +00006083 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006084 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006085 PushOnScopeChains(ExDecl, S);
6086 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006087 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006088
Douglas Gregor758a8692009-06-17 21:51:59 +00006089 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00006090 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006091}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006092
Mike Stump11289f42009-09-09 15:08:12 +00006093Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00006094 ExprArg assertexpr,
6095 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006096 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00006097 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006098 cast<StringLiteral>((Expr *)assertmessageexpr.get());
6099
Anders Carlsson54b26982009-03-14 00:33:21 +00006100 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6101 llvm::APSInt Value(32);
6102 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6103 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6104 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00006105 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00006106 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006107
Anders Carlsson54b26982009-03-14 00:33:21 +00006108 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006109 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006110 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006111 }
6112 }
Mike Stump11289f42009-09-09 15:08:12 +00006113
Anders Carlsson78e2bc02009-03-15 17:35:16 +00006114 assertexpr.release();
6115 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00006116 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006117 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006118
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006119 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00006120 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006121}
Sebastian Redlf769df52009-03-24 22:27:57 +00006122
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006123/// \brief Perform semantic analysis of the given friend type declaration.
6124///
6125/// \returns A friend declaration that.
6126FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6127 TypeSourceInfo *TSInfo) {
6128 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6129
6130 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006131 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006132
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006133 if (!getLangOptions().CPlusPlus0x) {
6134 // C++03 [class.friend]p2:
6135 // An elaborated-type-specifier shall be used in a friend declaration
6136 // for a class.*
6137 //
6138 // * The class-key of the elaborated-type-specifier is required.
6139 if (!ActiveTemplateInstantiations.empty()) {
6140 // Do not complain about the form of friend template types during
6141 // template instantiation; we will already have complained when the
6142 // template was declared.
6143 } else if (!T->isElaboratedTypeSpecifier()) {
6144 // If we evaluated the type to a record type, suggest putting
6145 // a tag in front.
6146 if (const RecordType *RT = T->getAs<RecordType>()) {
6147 RecordDecl *RD = RT->getDecl();
6148
6149 std::string InsertionText = std::string(" ") + RD->getKindName();
6150
6151 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6152 << (unsigned) RD->getTagKind()
6153 << T
6154 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6155 InsertionText);
6156 } else {
6157 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6158 << T
6159 << SourceRange(FriendLoc, TypeRange.getEnd());
6160 }
6161 } else if (T->getAs<EnumType>()) {
6162 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006163 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006164 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006165 }
6166 }
6167
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006168 // C++0x [class.friend]p3:
6169 // If the type specifier in a friend declaration designates a (possibly
6170 // cv-qualified) class type, that class is declared as a friend; otherwise,
6171 // the friend declaration is ignored.
6172
6173 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6174 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006175
6176 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6177}
6178
John McCall11083da2009-09-16 22:47:08 +00006179/// Handle a friend type declaration. This works in tandem with
6180/// ActOnTag.
6181///
6182/// Notes on friend class templates:
6183///
6184/// We generally treat friend class declarations as if they were
6185/// declaring a class. So, for example, the elaborated type specifier
6186/// in a friend declaration is required to obey the restrictions of a
6187/// class-head (i.e. no typedefs in the scope chain), template
6188/// parameters are required to match up with simple template-ids, &c.
6189/// However, unlike when declaring a template specialization, it's
6190/// okay to refer to a template specialization without an empty
6191/// template parameter declaration, e.g.
6192/// friend class A<T>::B<unsigned>;
6193/// We permit this as a special case; if there are any template
6194/// parameters present at all, require proper matching, i.e.
6195/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00006196Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00006197 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006198 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006199
6200 assert(DS.isFriendSpecified());
6201 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6202
John McCall11083da2009-09-16 22:47:08 +00006203 // Try to convert the decl specifier to a type. This works for
6204 // friend templates because ActOnTag never produces a ClassTemplateDecl
6205 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006206 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006207 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6208 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006209 if (TheDeclarator.isInvalidType())
6210 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00006211
John McCall11083da2009-09-16 22:47:08 +00006212 // This is definitely an error in C++98. It's probably meant to
6213 // be forbidden in C++0x, too, but the specification is just
6214 // poorly written.
6215 //
6216 // The problem is with declarations like the following:
6217 // template <T> friend A<T>::foo;
6218 // where deciding whether a class C is a friend or not now hinges
6219 // on whether there exists an instantiation of A that causes
6220 // 'foo' to equal C. There are restrictions on class-heads
6221 // (which we declare (by fiat) elaborated friend declarations to
6222 // be) that makes this tractable.
6223 //
6224 // FIXME: handle "template <> friend class A<T>;", which
6225 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006226 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006227 Diag(Loc, diag::err_tagless_friend_type_template)
6228 << DS.getSourceRange();
6229 return DeclPtrTy();
6230 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006231
John McCallaa74a0c2009-08-28 07:59:38 +00006232 // C++98 [class.friend]p1: A friend of a class is a function
6233 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006234 // This is fixed in DR77, which just barely didn't make the C++03
6235 // deadline. It's also a very silly restriction that seriously
6236 // affects inner classes and which nobody else seems to implement;
6237 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006238 //
6239 // But note that we could warn about it: it's always useless to
6240 // friend one of your own members (it's not, however, worthless to
6241 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006242
John McCall11083da2009-09-16 22:47:08 +00006243 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006244 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006245 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006246 NumTempParamLists,
John McCall11083da2009-09-16 22:47:08 +00006247 (TemplateParameterList**) TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006248 TSI,
John McCall11083da2009-09-16 22:47:08 +00006249 DS.getFriendSpecLoc());
6250 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006251 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6252
6253 if (!D)
6254 return DeclPtrTy();
6255
John McCall11083da2009-09-16 22:47:08 +00006256 D->setAccess(AS_public);
6257 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006258
John McCall11083da2009-09-16 22:47:08 +00006259 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006260}
6261
John McCall2f212b32009-09-11 21:02:39 +00006262Sema::DeclPtrTy
6263Sema::ActOnFriendFunctionDecl(Scope *S,
6264 Declarator &D,
6265 bool IsDefinition,
6266 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006267 const DeclSpec &DS = D.getDeclSpec();
6268
6269 assert(DS.isFriendSpecified());
6270 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6271
6272 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006273 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6274 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006275
6276 // C++ [class.friend]p1
6277 // A friend of a class is a function or class....
6278 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006279 // It *doesn't* see through dependent types, which is correct
6280 // according to [temp.arg.type]p3:
6281 // If a declaration acquires a function type through a
6282 // type dependent on a template-parameter and this causes
6283 // a declaration that does not use the syntactic form of a
6284 // function declarator to have a function type, the program
6285 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006286 if (!T->isFunctionType()) {
6287 Diag(Loc, diag::err_unexpected_friend);
6288
6289 // It might be worthwhile to try to recover by creating an
6290 // appropriate declaration.
6291 return DeclPtrTy();
6292 }
6293
6294 // C++ [namespace.memdef]p3
6295 // - If a friend declaration in a non-local class first declares a
6296 // class or function, the friend class or function is a member
6297 // of the innermost enclosing namespace.
6298 // - The name of the friend is not found by simple name lookup
6299 // until a matching declaration is provided in that namespace
6300 // scope (either before or after the class declaration granting
6301 // friendship).
6302 // - If a friend function is called, its name may be found by the
6303 // name lookup that considers functions from namespaces and
6304 // classes associated with the types of the function arguments.
6305 // - When looking for a prior declaration of a class or a function
6306 // declared as a friend, scopes outside the innermost enclosing
6307 // namespace scope are not considered.
6308
John McCallaa74a0c2009-08-28 07:59:38 +00006309 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006310 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6311 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006312 assert(Name);
6313
John McCall07e91c02009-08-06 02:15:43 +00006314 // The context we found the declaration in, or in which we should
6315 // create the declaration.
6316 DeclContext *DC;
6317
6318 // FIXME: handle local classes
6319
6320 // Recover from invalid scope qualifiers as if they just weren't there.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006321 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006322 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006323 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
6324 DC = computeDeclContext(ScopeQual);
6325
6326 // FIXME: handle dependent contexts
6327 if (!DC) return DeclPtrTy();
John McCall0b66eb32010-05-01 00:40:08 +00006328 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00006329
John McCall1f82f242009-11-18 22:49:29 +00006330 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006331
John McCall45831862010-05-28 01:41:47 +00006332 // Ignore things found implicitly in the wrong scope.
John McCall07e91c02009-08-06 02:15:43 +00006333 // TODO: better diagnostics for this case. Suggesting the right
6334 // qualified scope would be nice...
John McCall45831862010-05-28 01:41:47 +00006335 LookupResult::Filter F = Previous.makeFilter();
6336 while (F.hasNext()) {
6337 NamedDecl *D = F.next();
6338 if (!D->getDeclContext()->getLookupContext()->Equals(DC))
6339 F.erase();
6340 }
6341 F.done();
6342
6343 if (Previous.empty()) {
John McCallaa74a0c2009-08-28 07:59:38 +00006344 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00006345 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
6346 return DeclPtrTy();
6347 }
6348
6349 // C++ [class.friend]p1: A friend of a class is a function or
6350 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006351 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00006352 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6353
John McCall07e91c02009-08-06 02:15:43 +00006354 // Otherwise walk out to the nearest namespace scope looking for matches.
6355 } else {
6356 // TODO: handle local class contexts.
6357
6358 DC = CurContext;
6359 while (true) {
6360 // Skip class contexts. If someone can cite chapter and verse
6361 // for this behavior, that would be nice --- it's what GCC and
6362 // EDG do, and it seems like a reasonable intent, but the spec
6363 // really only says that checks for unqualified existing
6364 // declarations should stop at the nearest enclosing namespace,
6365 // not that they should only consider the nearest enclosing
6366 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006367 while (DC->isRecord())
6368 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006369
John McCall1f82f242009-11-18 22:49:29 +00006370 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006371
6372 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00006373 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006374 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006375
John McCall07e91c02009-08-06 02:15:43 +00006376 if (DC->isFileContext()) break;
6377 DC = DC->getParent();
6378 }
6379
6380 // C++ [class.friend]p1: A friend of a class is a function or
6381 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006382 // C++0x changes this for both friend types and functions.
6383 // Most C++ 98 compilers do seem to give an error here, so
6384 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006385 if (!Previous.empty() && DC->Equals(CurContext)
6386 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006387 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6388 }
6389
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006390 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00006391 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006392 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6393 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6394 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006395 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006396 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6397 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00006398 return DeclPtrTy();
6399 }
John McCall07e91c02009-08-06 02:15:43 +00006400 }
6401
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006402 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00006403 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006404 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006405 IsDefinition,
6406 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00006407 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00006408
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006409 assert(ND->getDeclContext() == DC);
6410 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006411
John McCall759e32b2009-08-31 22:39:49 +00006412 // Add the function declaration to the appropriate lookup tables,
6413 // adjusting the redeclarations list as necessary. We don't
6414 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006415 //
John McCall759e32b2009-08-31 22:39:49 +00006416 // Also update the scope-based lookup if the target context's
6417 // lookup context is in lexical scope.
6418 if (!CurContext->isDependentContext()) {
6419 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006420 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006421 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006422 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006423 }
John McCallaa74a0c2009-08-28 07:59:38 +00006424
6425 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006426 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006427 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006428 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006429 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006430
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006431 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00006432}
6433
Chris Lattner83f095c2009-03-28 19:18:32 +00006434void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00006435 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006436
Chris Lattner83f095c2009-03-28 19:18:32 +00006437 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00006438 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6439 if (!Fn) {
6440 Diag(DelLoc, diag::err_deleted_non_function);
6441 return;
6442 }
6443 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6444 Diag(DelLoc, diag::err_deleted_decl_not_first);
6445 Diag(Prev->getLocation(), diag::note_previous_declaration);
6446 // If the declaration wasn't the first, we delete the function anyway for
6447 // recovery.
6448 }
6449 Fn->setDeleted();
6450}
Sebastian Redl4c018662009-04-27 21:33:24 +00006451
6452static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6453 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6454 ++CI) {
6455 Stmt *SubStmt = *CI;
6456 if (!SubStmt)
6457 continue;
6458 if (isa<ReturnStmt>(SubStmt))
6459 Self.Diag(SubStmt->getSourceRange().getBegin(),
6460 diag::err_return_in_constructor_handler);
6461 if (!isa<Expr>(SubStmt))
6462 SearchForReturnInStmt(Self, SubStmt);
6463 }
6464}
6465
6466void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6467 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6468 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6469 SearchForReturnInStmt(*this, Handler);
6470 }
6471}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006472
Mike Stump11289f42009-09-09 15:08:12 +00006473bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006474 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006475 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6476 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006477
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006478 if (Context.hasSameType(NewTy, OldTy) ||
6479 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006480 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006481
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006482 // Check if the return types are covariant
6483 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006484
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006485 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006486 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6487 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006488 NewClassTy = NewPT->getPointeeType();
6489 OldClassTy = OldPT->getPointeeType();
6490 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006491 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6492 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6493 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6494 NewClassTy = NewRT->getPointeeType();
6495 OldClassTy = OldRT->getPointeeType();
6496 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006497 }
6498 }
Mike Stump11289f42009-09-09 15:08:12 +00006499
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006500 // The return types aren't either both pointers or references to a class type.
6501 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006502 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006503 diag::err_different_return_type_for_overriding_virtual_function)
6504 << New->getDeclName() << NewTy << OldTy;
6505 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006506
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006507 return true;
6508 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006509
Anders Carlssone60365b2009-12-31 18:34:24 +00006510 // C++ [class.virtual]p6:
6511 // If the return type of D::f differs from the return type of B::f, the
6512 // class type in the return type of D::f shall be complete at the point of
6513 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006514 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6515 if (!RT->isBeingDefined() &&
6516 RequireCompleteType(New->getLocation(), NewClassTy,
6517 PDiag(diag::err_covariant_return_incomplete)
6518 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006519 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006520 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006521
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006522 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006523 // Check if the new class derives from the old class.
6524 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6525 Diag(New->getLocation(),
6526 diag::err_covariant_return_not_derived)
6527 << New->getDeclName() << NewTy << OldTy;
6528 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6529 return true;
6530 }
Mike Stump11289f42009-09-09 15:08:12 +00006531
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006532 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006533 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006534 diag::err_covariant_return_inaccessible_base,
6535 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6536 // FIXME: Should this point to the return type?
6537 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006538 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6539 return true;
6540 }
6541 }
Mike Stump11289f42009-09-09 15:08:12 +00006542
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006543 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006544 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006545 Diag(New->getLocation(),
6546 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006547 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006548 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6549 return true;
6550 };
Mike Stump11289f42009-09-09 15:08:12 +00006551
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006552
6553 // The new class type must have the same or less qualifiers as the old type.
6554 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6555 Diag(New->getLocation(),
6556 diag::err_covariant_return_type_class_type_more_qualified)
6557 << New->getDeclName() << NewTy << OldTy;
6558 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6559 return true;
6560 };
Mike Stump11289f42009-09-09 15:08:12 +00006561
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006562 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006563}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006564
Alexis Hunt96d5c762009-11-21 08:43:09 +00006565bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6566 const CXXMethodDecl *Old)
6567{
6568 if (Old->hasAttr<FinalAttr>()) {
6569 Diag(New->getLocation(), diag::err_final_function_overridden)
6570 << New->getDeclName();
6571 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6572 return true;
6573 }
6574
6575 return false;
6576}
6577
Douglas Gregor21920e372009-12-01 17:24:26 +00006578/// \brief Mark the given method pure.
6579///
6580/// \param Method the method to be marked pure.
6581///
6582/// \param InitRange the source range that covers the "0" initializer.
6583bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6584 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6585 Method->setPure();
6586
6587 // A class is abstract if at least one function is pure virtual.
6588 Method->getParent()->setAbstract(true);
6589 return false;
6590 }
6591
6592 if (!Method->isInvalidDecl())
6593 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6594 << Method->getDeclName() << InitRange;
6595 return true;
6596}
6597
John McCall1f4ee7b2009-12-19 09:28:58 +00006598/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6599/// an initializer for the out-of-line declaration 'Dcl'. The scope
6600/// is a fresh scope pushed for just this purpose.
6601///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006602/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6603/// static data member of class X, names should be looked up in the scope of
6604/// class X.
6605void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006606 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006607 Decl *D = Dcl.getAs<Decl>();
6608 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006609
John McCall1f4ee7b2009-12-19 09:28:58 +00006610 // We should only get called for declarations with scope specifiers, like:
6611 // int foo::bar;
6612 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006613 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006614}
6615
6616/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall1f4ee7b2009-12-19 09:28:58 +00006617/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006618void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006619 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006620 Decl *D = Dcl.getAs<Decl>();
6621 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006622
John McCall1f4ee7b2009-12-19 09:28:58 +00006623 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006624 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006625}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006626
6627/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6628/// C++ if/switch/while/for statement.
6629/// e.g: "if (int x = f()) {...}"
6630Action::DeclResult
6631Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
6632 // C++ 6.4p2:
6633 // The declarator shall not specify a function or an array.
6634 // The type-specifier-seq shall not contain typedef and shall not declare a
6635 // new class or enumeration.
6636 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6637 "Parser allowed 'typedef' as storage class of condition decl.");
6638
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006639 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006640 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6641 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006642
6643 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6644 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6645 // would be created and CXXConditionDeclExpr wants a VarDecl.
6646 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6647 << D.getSourceRange();
6648 return DeclResult();
6649 } else if (OwnedTag && OwnedTag->isDefinition()) {
6650 // The type-specifier-seq shall not declare a new class or enumeration.
6651 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6652 }
6653
6654 DeclPtrTy Dcl = ActOnDeclarator(S, D);
6655 if (!Dcl)
6656 return DeclResult();
6657
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006658 return Dcl;
6659}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006660
Douglas Gregor88d292c2010-05-13 16:44:06 +00006661void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6662 bool DefinitionRequired) {
6663 // Ignore any vtable uses in unevaluated operands or for classes that do
6664 // not have a vtable.
6665 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6666 CurContext->isDependentContext() ||
6667 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006668 return;
6669
Douglas Gregor88d292c2010-05-13 16:44:06 +00006670 // Try to insert this class into the map.
6671 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6672 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6673 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6674 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006675 // If we already had an entry, check to see if we are promoting this vtable
6676 // to required a definition. If so, we need to reappend to the VTableUses
6677 // list, since we may have already processed the first entry.
6678 if (DefinitionRequired && !Pos.first->second) {
6679 Pos.first->second = true;
6680 } else {
6681 // Otherwise, we can early exit.
6682 return;
6683 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006684 }
6685
6686 // Local classes need to have their virtual members marked
6687 // immediately. For all other classes, we mark their virtual members
6688 // at the end of the translation unit.
6689 if (Class->isLocalClass())
6690 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006691 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006692 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006693}
6694
Douglas Gregor88d292c2010-05-13 16:44:06 +00006695bool Sema::DefineUsedVTables() {
6696 // If any dynamic classes have their key function defined within
6697 // this translation unit, then those vtables are considered "used" and must
6698 // be emitted.
6699 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6700 if (const CXXMethodDecl *KeyFunction
6701 = Context.getKeyFunction(DynamicClasses[I])) {
6702 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006703 if (KeyFunction->hasBody(Definition))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006704 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6705 }
6706 }
6707
6708 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006709 return false;
6710
Douglas Gregor88d292c2010-05-13 16:44:06 +00006711 // Note: The VTableUses vector could grow as a result of marking
6712 // the members of a class as "used", so we check the size each
6713 // time through the loop and prefer indices (with are stable) to
6714 // iterators (which are not).
6715 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00006716 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006717 if (!Class)
6718 continue;
6719
6720 SourceLocation Loc = VTableUses[I].second;
6721
6722 // If this class has a key function, but that key function is
6723 // defined in another translation unit, we don't need to emit the
6724 // vtable even though we're using it.
6725 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006726 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006727 switch (KeyFunction->getTemplateSpecializationKind()) {
6728 case TSK_Undeclared:
6729 case TSK_ExplicitSpecialization:
6730 case TSK_ExplicitInstantiationDeclaration:
6731 // The key function is in another translation unit.
6732 continue;
6733
6734 case TSK_ExplicitInstantiationDefinition:
6735 case TSK_ImplicitInstantiation:
6736 // We will be instantiating the key function.
6737 break;
6738 }
6739 } else if (!KeyFunction) {
6740 // If we have a class with no key function that is the subject
6741 // of an explicit instantiation declaration, suppress the
6742 // vtable; it will live with the explicit instantiation
6743 // definition.
6744 bool IsExplicitInstantiationDeclaration
6745 = Class->getTemplateSpecializationKind()
6746 == TSK_ExplicitInstantiationDeclaration;
6747 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6748 REnd = Class->redecls_end();
6749 R != REnd; ++R) {
6750 TemplateSpecializationKind TSK
6751 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6752 if (TSK == TSK_ExplicitInstantiationDeclaration)
6753 IsExplicitInstantiationDeclaration = true;
6754 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6755 IsExplicitInstantiationDeclaration = false;
6756 break;
6757 }
6758 }
6759
6760 if (IsExplicitInstantiationDeclaration)
6761 continue;
6762 }
6763
6764 // Mark all of the virtual members of this class as referenced, so
6765 // that we can build a vtable. Then, tell the AST consumer that a
6766 // vtable for this class is required.
6767 MarkVirtualMembersReferenced(Loc, Class);
6768 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6769 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6770
6771 // Optionally warn if we're emitting a weak vtable.
6772 if (Class->getLinkage() == ExternalLinkage &&
6773 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006774 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006775 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6776 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00006777 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006778 VTableUses.clear();
6779
Anders Carlsson82fccd02009-12-07 08:24:59 +00006780 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006781}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006782
Rafael Espindola5b334082010-03-26 00:36:59 +00006783void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6784 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006785 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6786 e = RD->method_end(); i != e; ++i) {
6787 CXXMethodDecl *MD = *i;
6788
6789 // C++ [basic.def.odr]p2:
6790 // [...] A virtual member function is used if it is not pure. [...]
6791 if (MD->isVirtual() && !MD->isPure())
6792 MarkDeclarationReferenced(Loc, MD);
6793 }
Rafael Espindola5b334082010-03-26 00:36:59 +00006794
6795 // Only classes that have virtual bases need a VTT.
6796 if (RD->getNumVBases() == 0)
6797 return;
6798
6799 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6800 e = RD->bases_end(); i != e; ++i) {
6801 const CXXRecordDecl *Base =
6802 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00006803 if (Base->getNumVBases() == 0)
6804 continue;
6805 MarkVirtualMembersReferenced(Loc, Base);
6806 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006807}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006808
6809/// SetIvarInitializers - This routine builds initialization ASTs for the
6810/// Objective-C implementation whose ivars need be initialized.
6811void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6812 if (!getLangOptions().CPlusPlus)
6813 return;
6814 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
6815 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6816 CollectIvarsToConstructOrDestruct(OID, ivars);
6817 if (ivars.empty())
6818 return;
6819 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6820 for (unsigned i = 0; i < ivars.size(); i++) {
6821 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00006822 if (Field->isInvalidDecl())
6823 continue;
6824
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006825 CXXBaseOrMemberInitializer *Member;
6826 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6827 InitializationKind InitKind =
6828 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6829
6830 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6831 Sema::OwningExprResult MemberInit =
6832 InitSeq.Perform(*this, InitEntity, InitKind,
6833 Sema::MultiExprArg(*this, 0, 0));
6834 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6835 // Note, MemberInit could actually come back empty if no initialization
6836 // is required (e.g., because it would call a trivial default constructor)
6837 if (!MemberInit.get() || MemberInit.isInvalid())
6838 continue;
6839
6840 Member =
6841 new (Context) CXXBaseOrMemberInitializer(Context,
6842 Field, SourceLocation(),
6843 SourceLocation(),
6844 MemberInit.takeAs<Expr>(),
6845 SourceLocation());
6846 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00006847
6848 // Be sure that the destructor is accessible and is marked as referenced.
6849 if (const RecordType *RecordTy
6850 = Context.getBaseElementType(Field->getType())
6851 ->getAs<RecordType>()) {
6852 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00006853 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00006854 MarkDeclarationReferenced(Field->getLocation(), Destructor);
6855 CheckDestructorAccess(Field->getLocation(), Destructor,
6856 PDiag(diag::err_access_dtor_ivar)
6857 << Context.getBaseElementType(Field->getType()));
6858 }
6859 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006860 }
6861 ObjCImplementation->setIvarInitializers(Context,
6862 AllToInit.data(), AllToInit.size());
6863 }
6864}