blob: 7dcda884076a04fc0738b68fa5fed68aaf2d39f1 [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
14#include "Sema.h"
Douglas Gregor3e1e5272009-12-09 23:02:17 +000015#include "SemaInit.h"
John McCall5cebab12009-11-18 07:57:50 +000016#include "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()) {
Douglas Gregor58354032008-12-24 00:01:03 +0000415 if (!Param->hasUnparsedDefaultArg())
416 Param->getDefaultArg()->Destroy(Context);
Chris Lattner199abbc2008-04-08 05:04:30 +0000417 Param->setDefaultArg(0);
418 }
419 }
420 }
421}
Douglas Gregor556877c2008-04-13 21:30:24 +0000422
Douglas Gregor61956c42008-10-31 09:07:45 +0000423/// isCurrentClassName - Determine whether the identifier II is the
424/// name of the class type currently being defined. In the case of
425/// nested classes, this will only return true if II is the name of
426/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000427bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
428 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000429 assert(getLangOptions().CPlusPlus && "No class names in C!");
430
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000431 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000432 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000433 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000434 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
435 } else
436 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
437
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000438 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000439 return &II == CurDecl->getIdentifier();
440 else
441 return false;
442}
443
Mike Stump11289f42009-09-09 15:08:12 +0000444/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000445///
446/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
447/// and returns NULL otherwise.
448CXXBaseSpecifier *
449Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
450 SourceRange SpecifierRange,
451 bool Virtual, AccessSpecifier Access,
Mike Stump11289f42009-09-09 15:08:12 +0000452 QualType BaseType,
Douglas Gregor463421d2009-03-03 04:44:36 +0000453 SourceLocation BaseLoc) {
454 // C++ [class.union]p1:
455 // A union shall not have base classes.
456 if (Class->isUnion()) {
457 Diag(Class->getLocation(), diag::err_base_clause_on_union)
458 << SpecifierRange;
459 return 0;
460 }
461
462 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000463 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000464 Class->getTagKind() == TTK_Class,
Douglas Gregor463421d2009-03-03 04:44:36 +0000465 Access, BaseType);
466
467 // Base specifiers must be record types.
468 if (!BaseType->isRecordType()) {
469 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
470 return 0;
471 }
472
473 // C++ [class.union]p1:
474 // A union shall not be used as a base class.
475 if (BaseType->isUnionType()) {
476 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
477 return 0;
478 }
479
480 // C++ [class.derived]p2:
481 // The class-name in a base-specifier shall not be an incompletely
482 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000483 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000484 PDiag(diag::err_incomplete_base_class)
485 << SpecifierRange))
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 return 0;
487
Eli Friedmanc96d4962009-08-15 21:55:26 +0000488 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000489 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000490 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000491 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000492 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000493 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
494 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000495
Alexis Hunt96d5c762009-11-21 08:43:09 +0000496 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
497 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
498 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000499 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
500 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000501 return 0;
502 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000503
Eli Friedman89c038e2009-12-05 23:03:49 +0000504 SetClassDeclAttributesFromBase(Class, CXXBaseDecl, Virtual);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000505
506 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000507 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000508 Class->getTagKind() == TTK_Class,
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000509 Access, BaseType);
510}
511
512void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
513 const CXXRecordDecl *BaseClass,
514 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000515 // A class with a non-empty base class is not empty.
516 // FIXME: Standard ref?
517 if (!BaseClass->isEmpty())
518 Class->setEmpty(false);
519
520 // C++ [class.virtual]p1:
521 // A class that [...] inherits a virtual function is called a polymorphic
522 // class.
523 if (BaseClass->isPolymorphic())
524 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000525
Douglas Gregor463421d2009-03-03 04:44:36 +0000526 // C++ [dcl.init.aggr]p1:
527 // An aggregate is [...] a class with [...] no base classes [...].
528 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000529
530 // C++ [class]p4:
531 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000532 Class->setPOD(false);
533
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000534 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000535 // C++ [class.ctor]p5:
536 // A constructor is trivial if its class has no virtual base classes.
537 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000538
539 // C++ [class.copy]p6:
540 // A copy constructor is trivial if its class has no virtual base classes.
541 Class->setHasTrivialCopyConstructor(false);
542
543 // C++ [class.copy]p11:
544 // A copy assignment operator is trivial if its class has no virtual
545 // base classes.
546 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000547
548 // C++0x [meta.unary.prop] is_empty:
549 // T is a class type, but not a union type, with ... no virtual base
550 // classes
551 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000552 } else {
553 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000554 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000555 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000556 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000557 Class->setHasTrivialConstructor(false);
558
559 // C++ [class.copy]p6:
560 // A copy constructor is trivial if all the direct base classes of its
561 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000562 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000563 Class->setHasTrivialCopyConstructor(false);
564
565 // C++ [class.copy]p11:
566 // A copy assignment operator is trivial if all the direct base classes
567 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000568 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000569 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000570 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000571
572 // C++ [class.ctor]p3:
573 // A destructor is trivial if all the direct base classes of its class
574 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000575 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000576 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000577}
578
Douglas Gregor556877c2008-04-13 21:30:24 +0000579/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
580/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000581/// example:
582/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000583/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000584Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000585Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000586 bool Virtual, AccessSpecifier Access,
587 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000588 if (!classdecl)
589 return true;
590
Douglas Gregorc40290e2009-03-09 23:48:35 +0000591 AdjustDeclIfTemplate(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000592 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
593 if (!Class)
594 return true;
595
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000596 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000597 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
598 Virtual, Access,
599 BaseType, BaseLoc))
600 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000601
Douglas Gregor463421d2009-03-03 04:44:36 +0000602 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000603}
Douglas Gregor556877c2008-04-13 21:30:24 +0000604
Douglas Gregor463421d2009-03-03 04:44:36 +0000605/// \brief Performs the actual work of attaching the given base class
606/// specifiers to a C++ class.
607bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
608 unsigned NumBases) {
609 if (NumBases == 0)
610 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000611
612 // Used to keep track of which base types we have already seen, so
613 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000614 // that the key is always the unqualified canonical type of the base
615 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000616 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
617
618 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000619 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000620 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000621 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000622 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000623 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000624 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000625 if (!Class->hasObjectMember()) {
626 if (const RecordType *FDTTy =
627 NewBaseType.getTypePtr()->getAs<RecordType>())
628 if (FDTTy->getDecl()->hasObjectMember())
629 Class->setHasObjectMember(true);
630 }
631
Douglas Gregor29a92472008-10-22 17:49:05 +0000632 if (KnownBaseTypes[NewBaseType]) {
633 // C++ [class.mi]p3:
634 // A class shall not be specified as a direct base class of a
635 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000636 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000637 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000638 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000639 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000640
641 // Delete the duplicate base class specifier; we're going to
642 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000643 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000644
645 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000646 } else {
647 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000648 KnownBaseTypes[NewBaseType] = Bases[idx];
649 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000650 }
651 }
652
653 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000654 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000655
656 // Delete the remaining (good) base class specifiers, since their
657 // data has been copied into the CXXRecordDecl.
658 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000659 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000660
661 return Invalid;
662}
663
664/// ActOnBaseSpecifiers - Attach the given base specifiers to the
665/// class, after checking whether there are any duplicate base
666/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000667void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000668 unsigned NumBases) {
669 if (!ClassDecl || !Bases || !NumBases)
670 return;
671
672 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000673 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000674 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000675}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000676
John McCalle78aac42010-03-10 03:28:59 +0000677static CXXRecordDecl *GetClassForType(QualType T) {
678 if (const RecordType *RT = T->getAs<RecordType>())
679 return cast<CXXRecordDecl>(RT->getDecl());
680 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
681 return ICT->getDecl();
682 else
683 return 0;
684}
685
Douglas Gregor36d1b142009-10-06 17:59:45 +0000686/// \brief Determine whether the type \p Derived is a C++ class that is
687/// derived from the type \p Base.
688bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
689 if (!getLangOptions().CPlusPlus)
690 return false;
John McCalle78aac42010-03-10 03:28:59 +0000691
692 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
693 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000694 return false;
695
John McCalle78aac42010-03-10 03:28:59 +0000696 CXXRecordDecl *BaseRD = GetClassForType(Base);
697 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000698 return false;
699
John McCall67da35c2010-02-04 22:26:26 +0000700 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
701 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000702}
703
704/// \brief Determine whether the type \p Derived is a C++ class that is
705/// derived from the type \p Base.
706bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
707 if (!getLangOptions().CPlusPlus)
708 return false;
709
John McCalle78aac42010-03-10 03:28:59 +0000710 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
711 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000712 return false;
713
John McCalle78aac42010-03-10 03:28:59 +0000714 CXXRecordDecl *BaseRD = GetClassForType(Base);
715 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000716 return false;
717
Douglas Gregor36d1b142009-10-06 17:59:45 +0000718 return DerivedRD->isDerivedFrom(BaseRD, Paths);
719}
720
Anders Carlssona70cff62010-04-24 19:06:50 +0000721void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
722 CXXBaseSpecifierArray &BasePathArray) {
723 assert(BasePathArray.empty() && "Base path array must be empty!");
724 assert(Paths.isRecordingPaths() && "Must record paths!");
725
726 const CXXBasePath &Path = Paths.front();
727
728 // We first go backward and check if we have a virtual base.
729 // FIXME: It would be better if CXXBasePath had the base specifier for
730 // the nearest virtual base.
731 unsigned Start = 0;
732 for (unsigned I = Path.size(); I != 0; --I) {
733 if (Path[I - 1].Base->isVirtual()) {
734 Start = I - 1;
735 break;
736 }
737 }
738
739 // Now add all bases.
740 for (unsigned I = Start, E = Path.size(); I != E; ++I)
741 BasePathArray.push_back(Path[I].Base);
742}
743
Douglas Gregor88d292c2010-05-13 16:44:06 +0000744/// \brief Determine whether the given base path includes a virtual
745/// base class.
746bool Sema::BasePathInvolvesVirtualBase(const CXXBaseSpecifierArray &BasePath) {
747 for (CXXBaseSpecifierArray::iterator B = BasePath.begin(),
748 BEnd = BasePath.end();
749 B != BEnd; ++B)
750 if ((*B)->isVirtual())
751 return true;
752
753 return false;
754}
755
Douglas Gregor36d1b142009-10-06 17:59:45 +0000756/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
757/// conversion (where Derived and Base are class types) is
758/// well-formed, meaning that the conversion is unambiguous (and
759/// that all of the base classes are accessible). Returns true
760/// and emits a diagnostic if the code is ill-formed, returns false
761/// otherwise. Loc is the location where this routine should point to
762/// if there is an error, and Range is the source range to highlight
763/// if there is an error.
764bool
765Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000766 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000767 unsigned AmbigiousBaseConvID,
768 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000769 DeclarationName Name,
770 CXXBaseSpecifierArray *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000771 // First, determine whether the path from Derived to Base is
772 // ambiguous. This is slightly more expensive than checking whether
773 // the Derived to Base conversion exists, because here we need to
774 // explore multiple paths to determine if there is an ambiguity.
775 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
776 /*DetectVirtual=*/false);
777 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
778 assert(DerivationOkay &&
779 "Can only be used with a derived-to-base conversion");
780 (void)DerivationOkay;
781
782 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000783 if (InaccessibleBaseID) {
784 // Check that the base class can be accessed.
785 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
786 InaccessibleBaseID)) {
787 case AR_inaccessible:
788 return true;
789 case AR_accessible:
790 case AR_dependent:
791 case AR_delayed:
792 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000793 }
John McCall5b0829a2010-02-10 09:31:12 +0000794 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000795
796 // Build a base path if necessary.
797 if (BasePath)
798 BuildBasePathArray(Paths, *BasePath);
799 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000800 }
801
802 // We know that the derived-to-base conversion is ambiguous, and
803 // we're going to produce a diagnostic. Perform the derived-to-base
804 // search just one more time to compute all of the possible paths so
805 // that we can print them out. This is more expensive than any of
806 // the previous derived-to-base checks we've done, but at this point
807 // performance isn't as much of an issue.
808 Paths.clear();
809 Paths.setRecordingPaths(true);
810 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
811 assert(StillOkay && "Can only be used with a derived-to-base conversion");
812 (void)StillOkay;
813
814 // Build up a textual representation of the ambiguous paths, e.g.,
815 // D -> B -> A, that will be used to illustrate the ambiguous
816 // conversions in the diagnostic. We only print one of the paths
817 // to each base class subobject.
818 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
819
820 Diag(Loc, AmbigiousBaseConvID)
821 << Derived << Base << PathDisplayStr << Range << Name;
822 return true;
823}
824
825bool
826Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000827 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000828 CXXBaseSpecifierArray *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000829 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000830 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000831 IgnoreAccess ? 0
832 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000833 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000834 Loc, Range, DeclarationName(),
835 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000836}
837
838
839/// @brief Builds a string representing ambiguous paths from a
840/// specific derived class to different subobjects of the same base
841/// class.
842///
843/// This function builds a string that can be used in error messages
844/// to show the different paths that one can take through the
845/// inheritance hierarchy to go from the derived class to different
846/// subobjects of a base class. The result looks something like this:
847/// @code
848/// struct D -> struct B -> struct A
849/// struct D -> struct C -> struct A
850/// @endcode
851std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
852 std::string PathDisplayStr;
853 std::set<unsigned> DisplayedPaths;
854 for (CXXBasePaths::paths_iterator Path = Paths.begin();
855 Path != Paths.end(); ++Path) {
856 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
857 // We haven't displayed a path to this particular base
858 // class subobject yet.
859 PathDisplayStr += "\n ";
860 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
861 for (CXXBasePath::const_iterator Element = Path->begin();
862 Element != Path->end(); ++Element)
863 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
864 }
865 }
866
867 return PathDisplayStr;
868}
869
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000870//===----------------------------------------------------------------------===//
871// C++ class member Handling
872//===----------------------------------------------------------------------===//
873
Abramo Bagnarad7340582010-06-05 05:09:32 +0000874/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
875Sema::DeclPtrTy
876Sema::ActOnAccessSpecifier(AccessSpecifier Access,
877 SourceLocation ASLoc, SourceLocation ColonLoc) {
878 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
879 AccessSpecDecl* ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
880 ASLoc, ColonLoc);
881 CurContext->addHiddenDecl(ASDecl);
882 return DeclPtrTy::make(ASDecl);
883}
884
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000885/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
886/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
887/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000888/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000889Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000890Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000891 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000892 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
893 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000894 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000895 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000896 Expr *BitWidth = static_cast<Expr*>(BW);
897 Expr *Init = static_cast<Expr*>(InitExpr);
898 SourceLocation Loc = D.getIdentifierLoc();
899
John McCallb1cd7da2010-06-04 08:34:12 +0000900 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000901 assert(!DS.isFriendSpecified());
902
John McCallb1cd7da2010-06-04 08:34:12 +0000903 bool isFunc = false;
904 if (D.isFunctionDeclarator())
905 isFunc = true;
906 else if (D.getNumTypeObjects() == 0 &&
907 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
908 QualType TDType = GetTypeFromParser(DS.getTypeRep());
909 isFunc = TDType->isFunctionType();
910 }
911
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000912 // C++ 9.2p6: A member shall not be declared to have automatic storage
913 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000914 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
915 // data members and cannot be applied to names declared const or static,
916 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000917 switch (DS.getStorageClassSpec()) {
918 case DeclSpec::SCS_unspecified:
919 case DeclSpec::SCS_typedef:
920 case DeclSpec::SCS_static:
921 // FALL THROUGH.
922 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000923 case DeclSpec::SCS_mutable:
924 if (isFunc) {
925 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000926 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000927 else
Chris Lattner3b054132008-11-19 05:08:23 +0000928 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000929
Sebastian Redl8071edb2008-11-17 23:24:37 +0000930 // FIXME: It would be nicer if the keyword was ignored only for this
931 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000932 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000933 }
934 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000935 default:
936 if (DS.getStorageClassSpecLoc().isValid())
937 Diag(DS.getStorageClassSpecLoc(),
938 diag::err_storageclass_invalid_for_member);
939 else
940 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
941 D.getMutableDeclSpec().ClearStorageClassSpecs();
942 }
943
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000944 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
945 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000946 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000947
948 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000949 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000950 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000951 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
952 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000953 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000954 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000955 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000956 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000957 if (!Member) {
958 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000959 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000960 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000961
962 // Non-instance-fields can't have a bitfield.
963 if (BitWidth) {
964 if (Member->isInvalidDecl()) {
965 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000966 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000967 // C++ 9.6p3: A bit-field shall not be a static member.
968 // "static member 'A' cannot be a bit-field"
969 Diag(Loc, diag::err_static_not_bitfield)
970 << Name << BitWidth->getSourceRange();
971 } else if (isa<TypedefDecl>(Member)) {
972 // "typedef member 'x' cannot be a bit-field"
973 Diag(Loc, diag::err_typedef_not_bitfield)
974 << Name << BitWidth->getSourceRange();
975 } else {
976 // A function typedef ("typedef int f(); f a;").
977 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
978 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000979 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000980 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000981 }
Mike Stump11289f42009-09-09 15:08:12 +0000982
Chris Lattnerd26760a2009-03-05 23:01:03 +0000983 DeleteExpr(BitWidth);
984 BitWidth = 0;
985 Member->setInvalidDecl();
986 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000987
988 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000989
Douglas Gregor3447e762009-08-20 22:52:58 +0000990 // If we have declared a member function template, set the access of the
991 // templated declaration as well.
992 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
993 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000994 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000995
Douglas Gregor92751d42008-11-17 22:58:34 +0000996 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000997
Douglas Gregor0c880302009-03-11 23:00:04 +0000998 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000999 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +00001000 if (Deleted) // FIXME: Source location is not very good.
1001 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001002
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001003 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +00001004 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +00001005 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001006 }
Chris Lattner83f095c2009-03-28 19:18:32 +00001007 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001008}
1009
Douglas Gregor15e77a22009-12-31 09:10:24 +00001010/// \brief Find the direct and/or virtual base specifiers that
1011/// correspond to the given base type, for use in base initialization
1012/// within a constructor.
1013static bool FindBaseInitializer(Sema &SemaRef,
1014 CXXRecordDecl *ClassDecl,
1015 QualType BaseType,
1016 const CXXBaseSpecifier *&DirectBaseSpec,
1017 const CXXBaseSpecifier *&VirtualBaseSpec) {
1018 // First, check for a direct base class.
1019 DirectBaseSpec = 0;
1020 for (CXXRecordDecl::base_class_const_iterator Base
1021 = ClassDecl->bases_begin();
1022 Base != ClassDecl->bases_end(); ++Base) {
1023 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1024 // We found a direct base of this type. That's what we're
1025 // initializing.
1026 DirectBaseSpec = &*Base;
1027 break;
1028 }
1029 }
1030
1031 // Check for a virtual base class.
1032 // FIXME: We might be able to short-circuit this if we know in advance that
1033 // there are no virtual bases.
1034 VirtualBaseSpec = 0;
1035 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1036 // We haven't found a base yet; search the class hierarchy for a
1037 // virtual base class.
1038 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1039 /*DetectVirtual=*/false);
1040 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1041 BaseType, Paths)) {
1042 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1043 Path != Paths.end(); ++Path) {
1044 if (Path->back().Base->isVirtual()) {
1045 VirtualBaseSpec = Path->back().Base;
1046 break;
1047 }
1048 }
1049 }
1050 }
1051
1052 return DirectBaseSpec || VirtualBaseSpec;
1053}
1054
Douglas Gregore8381c02008-11-05 04:29:56 +00001055/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001056Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +00001057Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001058 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001059 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001060 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001061 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001062 SourceLocation IdLoc,
1063 SourceLocation LParenLoc,
1064 ExprTy **Args, unsigned NumArgs,
1065 SourceLocation *CommaLocs,
1066 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001067 if (!ConstructorD)
1068 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001069
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001070 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001071
1072 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +00001073 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +00001074 if (!Constructor) {
1075 // The user wrote a constructor initializer on a function that is
1076 // not a C++ constructor. Ignore the error for now, because we may
1077 // have more member initializers coming; we'll diagnose it just
1078 // once in ActOnMemInitializers.
1079 return true;
1080 }
1081
1082 CXXRecordDecl *ClassDecl = Constructor->getParent();
1083
1084 // C++ [class.base.init]p2:
1085 // Names in a mem-initializer-id are looked up in the scope of the
1086 // constructor’s class and, if not found in that scope, are looked
1087 // up in the scope containing the constructor’s
1088 // definition. [Note: if the constructor’s class contains a member
1089 // with the same name as a direct or virtual base class of the
1090 // class, a mem-initializer-id naming the member or base class and
1091 // composed of a single identifier refers to the class member. A
1092 // mem-initializer-id for the hidden base class may be specified
1093 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001094 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001095 // Look for a member, first.
1096 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001097 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001098 = ClassDecl->lookup(MemberOrBase);
1099 if (Result.first != Result.second)
1100 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001101
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001102 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001103
Eli Friedman8e1433b2009-07-29 19:44:27 +00001104 if (Member)
1105 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001106 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001107 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001108 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001109 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001110 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001111
1112 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001113 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001114 } else {
1115 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1116 LookupParsedName(R, S, &SS);
1117
1118 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1119 if (!TyD) {
1120 if (R.isAmbiguous()) return true;
1121
John McCallda6841b2010-04-09 19:01:14 +00001122 // We don't want access-control diagnostics here.
1123 R.suppressDiagnostics();
1124
Douglas Gregora3b624a2010-01-19 06:46:48 +00001125 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1126 bool NotUnknownSpecialization = false;
1127 DeclContext *DC = computeDeclContext(SS, false);
1128 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1129 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1130
1131 if (!NotUnknownSpecialization) {
1132 // When the scope specifier can refer to a member of an unknown
1133 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001134 BaseType = CheckTypenameType(ETK_None,
1135 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001136 *MemberOrBase, SourceLocation(),
1137 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001138 if (BaseType.isNull())
1139 return true;
1140
Douglas Gregora3b624a2010-01-19 06:46:48 +00001141 R.clear();
1142 }
1143 }
1144
Douglas Gregor15e77a22009-12-31 09:10:24 +00001145 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001146 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001147 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1148 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001149 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1150 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1151 // We have found a non-static data member with a similar
1152 // name to what was typed; complain and initialize that
1153 // member.
1154 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1155 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001156 << FixItHint::CreateReplacement(R.getNameLoc(),
1157 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001158 Diag(Member->getLocation(), diag::note_previous_decl)
1159 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001160
1161 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1162 LParenLoc, RParenLoc);
1163 }
1164 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1165 const CXXBaseSpecifier *DirectBaseSpec;
1166 const CXXBaseSpecifier *VirtualBaseSpec;
1167 if (FindBaseInitializer(*this, ClassDecl,
1168 Context.getTypeDeclType(Type),
1169 DirectBaseSpec, VirtualBaseSpec)) {
1170 // We have found a direct or virtual base class with a
1171 // similar name to what was typed; complain and initialize
1172 // that base class.
1173 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1174 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001175 << FixItHint::CreateReplacement(R.getNameLoc(),
1176 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001177
1178 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1179 : VirtualBaseSpec;
1180 Diag(BaseSpec->getSourceRange().getBegin(),
1181 diag::note_base_class_specified_here)
1182 << BaseSpec->getType()
1183 << BaseSpec->getSourceRange();
1184
Douglas Gregor15e77a22009-12-31 09:10:24 +00001185 TyD = Type;
1186 }
1187 }
1188 }
1189
Douglas Gregora3b624a2010-01-19 06:46:48 +00001190 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001191 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1192 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1193 return true;
1194 }
John McCallb5a0d312009-12-21 10:41:20 +00001195 }
1196
Douglas Gregora3b624a2010-01-19 06:46:48 +00001197 if (BaseType.isNull()) {
1198 BaseType = Context.getTypeDeclType(TyD);
1199 if (SS.isSet()) {
1200 NestedNameSpecifier *Qualifier =
1201 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001202
Douglas Gregora3b624a2010-01-19 06:46:48 +00001203 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001204 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001205 }
John McCallb5a0d312009-12-21 10:41:20 +00001206 }
1207 }
Mike Stump11289f42009-09-09 15:08:12 +00001208
John McCallbcd03502009-12-07 02:54:59 +00001209 if (!TInfo)
1210 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001211
John McCallbcd03502009-12-07 02:54:59 +00001212 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001213 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001214}
1215
John McCalle22a04a2009-11-04 23:02:40 +00001216/// Checks an initializer expression for use of uninitialized fields, such as
1217/// containing the field that is being initialized. Returns true if there is an
1218/// uninitialized field was used an updates the SourceLocation parameter; false
1219/// otherwise.
1220static bool InitExprContainsUninitializedFields(const Stmt* S,
1221 const FieldDecl* LhsField,
1222 SourceLocation* L) {
1223 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1224 if (ME) {
1225 const NamedDecl* RhsField = ME->getMemberDecl();
1226 if (RhsField == LhsField) {
1227 // Initializing a field with itself. Throw a warning.
1228 // But wait; there are exceptions!
1229 // Exception #1: The field may not belong to this record.
1230 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1231 const Expr* base = ME->getBase();
1232 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1233 // Even though the field matches, it does not belong to this record.
1234 return false;
1235 }
1236 // None of the exceptions triggered; return true to indicate an
1237 // uninitialized field was used.
1238 *L = ME->getMemberLoc();
1239 return true;
1240 }
1241 }
1242 bool found = false;
1243 for (Stmt::const_child_iterator it = S->child_begin();
1244 it != S->child_end() && found == false;
1245 ++it) {
1246 if (isa<CallExpr>(S)) {
1247 // Do not descend into function calls or constructors, as the use
1248 // of an uninitialized field may be valid. One would have to inspect
1249 // the contents of the function/ctor to determine if it is safe or not.
1250 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1251 // may be safe, depending on what the function/ctor does.
1252 continue;
1253 }
1254 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1255 }
1256 return found;
1257}
1258
Eli Friedman8e1433b2009-07-29 19:44:27 +00001259Sema::MemInitResult
1260Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1261 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001262 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001263 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001264 // Diagnose value-uses of fields to initialize themselves, e.g.
1265 // foo(foo)
1266 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001267 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001268 for (unsigned i = 0; i < NumArgs; ++i) {
1269 SourceLocation L;
1270 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1271 // FIXME: Return true in the case when other fields are used before being
1272 // uninitialized. For example, let this field be the i'th field. When
1273 // initializing the i'th field, throw a warning if any of the >= i'th
1274 // fields are used, as they are not yet initialized.
1275 // Right now we are only handling the case where the i'th field uses
1276 // itself in its initializer.
1277 Diag(L, diag::warn_field_is_uninit);
1278 }
1279 }
1280
Eli Friedman8e1433b2009-07-29 19:44:27 +00001281 bool HasDependentArg = false;
1282 for (unsigned i = 0; i < NumArgs; i++)
1283 HasDependentArg |= Args[i]->isTypeDependent();
1284
Eli Friedman8e1433b2009-07-29 19:44:27 +00001285 QualType FieldType = Member->getType();
1286 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1287 FieldType = Array->getElementType();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001288 if (FieldType->isDependentType() || HasDependentArg) {
1289 // Can't check initialization for a member of dependent type or when
1290 // any of the arguments are type-dependent expressions.
1291 OwningExprResult Init
1292 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1293 RParenLoc));
1294
1295 // Erase any temporaries within this evaluation context; we're not
1296 // going to track them in the AST, since we'll be rebuilding the
1297 // ASTs during template instantiation.
1298 ExprTemporaries.erase(
1299 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1300 ExprTemporaries.end());
1301
1302 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1303 LParenLoc,
1304 Init.takeAs<Expr>(),
1305 RParenLoc);
1306
Douglas Gregore8381c02008-11-05 04:29:56 +00001307 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001308
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001309 if (Member->isInvalidDecl())
1310 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001311
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001312 // Initialize the member.
1313 InitializedEntity MemberEntity =
1314 InitializedEntity::InitializeMember(Member, 0);
1315 InitializationKind Kind =
1316 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1317
1318 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1319
1320 OwningExprResult MemberInit =
1321 InitSeq.Perform(*this, MemberEntity, Kind,
1322 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1323 if (MemberInit.isInvalid())
1324 return true;
1325
1326 // C++0x [class.base.init]p7:
1327 // The initialization of each base and member constitutes a
1328 // full-expression.
1329 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1330 if (MemberInit.isInvalid())
1331 return true;
1332
1333 // If we are in a dependent context, template instantiation will
1334 // perform this type-checking again. Just save the arguments that we
1335 // received in a ParenListExpr.
1336 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1337 // of the information that we have about the member
1338 // initializer. However, deconstructing the ASTs is a dicey process,
1339 // and this approach is far more likely to get the corner cases right.
1340 if (CurContext->isDependentContext()) {
1341 // Bump the reference count of all of the arguments.
1342 for (unsigned I = 0; I != NumArgs; ++I)
1343 Args[I]->Retain();
1344
1345 OwningExprResult Init
1346 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1347 RParenLoc));
1348 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1349 LParenLoc,
1350 Init.takeAs<Expr>(),
1351 RParenLoc);
1352 }
1353
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001354 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001355 LParenLoc,
1356 MemberInit.takeAs<Expr>(),
1357 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001358}
1359
1360Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001361Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001362 Expr **Args, unsigned NumArgs,
1363 SourceLocation LParenLoc, SourceLocation RParenLoc,
1364 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001365 bool HasDependentArg = false;
1366 for (unsigned i = 0; i < NumArgs; i++)
1367 HasDependentArg |= Args[i]->isTypeDependent();
1368
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001369 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001370 if (BaseType->isDependentType() || HasDependentArg) {
1371 // Can't check initialization for a base of dependent type or when
1372 // any of the arguments are type-dependent expressions.
1373 OwningExprResult BaseInit
1374 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1375 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001376
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001377 // Erase any temporaries within this evaluation context; we're not
1378 // going to track them in the AST, since we'll be rebuilding the
1379 // ASTs during template instantiation.
1380 ExprTemporaries.erase(
1381 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1382 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001383
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001384 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001385 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001386 LParenLoc,
1387 BaseInit.takeAs<Expr>(),
1388 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001389 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001390
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001391 if (!BaseType->isRecordType())
1392 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001393 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001394
1395 // C++ [class.base.init]p2:
1396 // [...] Unless the mem-initializer-id names a nonstatic data
1397 // member of the constructor’s class or a direct or virtual base
1398 // of that class, the mem-initializer is ill-formed. A
1399 // mem-initializer-list can initialize a base class using any
1400 // name that denotes that base class type.
1401
1402 // Check for direct and virtual base classes.
1403 const CXXBaseSpecifier *DirectBaseSpec = 0;
1404 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1405 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1406 VirtualBaseSpec);
1407
1408 // C++ [base.class.init]p2:
1409 // If a mem-initializer-id is ambiguous because it designates both
1410 // a direct non-virtual base class and an inherited virtual base
1411 // class, the mem-initializer is ill-formed.
1412 if (DirectBaseSpec && VirtualBaseSpec)
1413 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001414 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001415 // C++ [base.class.init]p2:
1416 // Unless the mem-initializer-id names a nonstatic data membeer of the
1417 // constructor's class ot a direst or virtual base of that class, the
1418 // mem-initializer is ill-formed.
1419 if (!DirectBaseSpec && !VirtualBaseSpec)
1420 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
John McCall1e67dd62010-04-27 01:43:38 +00001421 << BaseType << Context.getTypeDeclType(ClassDecl)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001422 << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001423
1424 CXXBaseSpecifier *BaseSpec
1425 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1426 if (!BaseSpec)
1427 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1428
1429 // Initialize the base.
1430 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001431 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001432 InitializationKind Kind =
1433 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1434
1435 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1436
1437 OwningExprResult BaseInit =
1438 InitSeq.Perform(*this, BaseEntity, Kind,
1439 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1440 if (BaseInit.isInvalid())
1441 return true;
1442
1443 // C++0x [class.base.init]p7:
1444 // The initialization of each base and member constitutes a
1445 // full-expression.
1446 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1447 if (BaseInit.isInvalid())
1448 return true;
1449
1450 // If we are in a dependent context, template instantiation will
1451 // perform this type-checking again. Just save the arguments that we
1452 // received in a ParenListExpr.
1453 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1454 // of the information that we have about the base
1455 // initializer. However, deconstructing the ASTs is a dicey process,
1456 // and this approach is far more likely to get the corner cases right.
1457 if (CurContext->isDependentContext()) {
1458 // Bump the reference count of all of the arguments.
1459 for (unsigned I = 0; I != NumArgs; ++I)
1460 Args[I]->Retain();
1461
1462 OwningExprResult Init
1463 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1464 RParenLoc));
1465 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001466 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001467 LParenLoc,
1468 Init.takeAs<Expr>(),
1469 RParenLoc);
1470 }
1471
1472 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001473 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001474 LParenLoc,
1475 BaseInit.takeAs<Expr>(),
1476 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001477}
1478
Anders Carlsson1b00e242010-04-23 03:10:23 +00001479/// ImplicitInitializerKind - How an implicit base or member initializer should
1480/// initialize its base or member.
1481enum ImplicitInitializerKind {
1482 IIK_Default,
1483 IIK_Copy,
1484 IIK_Move
1485};
1486
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001487static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001488BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001489 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001490 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001491 bool IsInheritedVirtualBase,
1492 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001493 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001494 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1495 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001496
Anders Carlsson1b00e242010-04-23 03:10:23 +00001497 Sema::OwningExprResult BaseInit(SemaRef);
1498
1499 switch (ImplicitInitKind) {
1500 case IIK_Default: {
1501 InitializationKind InitKind
1502 = InitializationKind::CreateDefault(Constructor->getLocation());
1503 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1504 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1505 Sema::MultiExprArg(SemaRef, 0, 0));
1506 break;
1507 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001508
Anders Carlsson1b00e242010-04-23 03:10:23 +00001509 case IIK_Copy: {
1510 ParmVarDecl *Param = Constructor->getParamDecl(0);
1511 QualType ParamType = Param->getType().getNonReferenceType();
1512
1513 Expr *CopyCtorArg =
1514 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregored088b72010-05-03 15:43:53 +00001515 Constructor->getLocation(), ParamType, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001516
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001517 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001518 QualType ArgTy =
1519 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1520 ParamType.getQualifiers());
1521 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001522 CastExpr::CK_UncheckedDerivedToBase,
Anders Carlsson36db0d92010-04-24 22:54:32 +00001523 /*isLvalue=*/true,
1524 CXXBaseSpecifierArray(BaseSpec));
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001525
Anders Carlsson1b00e242010-04-23 03:10:23 +00001526 InitializationKind InitKind
1527 = InitializationKind::CreateDirect(Constructor->getLocation(),
1528 SourceLocation(), SourceLocation());
1529 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1530 &CopyCtorArg, 1);
1531 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1532 Sema::MultiExprArg(SemaRef,
1533 (void**)&CopyCtorArg, 1));
1534 break;
1535 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001536
Anders Carlsson1b00e242010-04-23 03:10:23 +00001537 case IIK_Move:
1538 assert(false && "Unhandled initializer kind!");
1539 }
1540
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001541 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1542 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001543 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001544
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001545 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001546 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1547 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1548 SourceLocation()),
1549 BaseSpec->isVirtual(),
1550 SourceLocation(),
1551 BaseInit.takeAs<Expr>(),
1552 SourceLocation());
1553
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001554 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001555}
1556
Anders Carlsson3c1db572010-04-23 02:15:47 +00001557static bool
1558BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001559 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001560 FieldDecl *Field,
1561 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001562 if (Field->isInvalidDecl())
1563 return true;
1564
Anders Carlsson423f5d82010-04-23 16:04:08 +00001565 if (ImplicitInitKind == IIK_Copy) {
Douglas Gregor94f9a482010-05-05 05:51:00 +00001566 SourceLocation Loc = Constructor->getLocation();
Anders Carlsson423f5d82010-04-23 16:04:08 +00001567 ParmVarDecl *Param = Constructor->getParamDecl(0);
1568 QualType ParamType = Param->getType().getNonReferenceType();
1569
1570 Expr *MemberExprBase =
1571 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001572 Loc, ParamType, 0);
1573
1574 // Build a reference to this field within the parameter.
1575 CXXScopeSpec SS;
1576 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1577 Sema::LookupMemberName);
1578 MemberLookup.addDecl(Field, AS_public);
1579 MemberLookup.resolveKind();
1580 Sema::OwningExprResult CopyCtorArg
1581 = SemaRef.BuildMemberReferenceExpr(SemaRef.Owned(MemberExprBase),
1582 ParamType, Loc,
1583 /*IsArrow=*/false,
1584 SS,
1585 /*FirstQualifierInScope=*/0,
1586 MemberLookup,
1587 /*TemplateArgs=*/0);
1588 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001589 return true;
1590
Douglas Gregor94f9a482010-05-05 05:51:00 +00001591 // When the field we are copying is an array, create index variables for
1592 // each dimension of the array. We use these index variables to subscript
1593 // the source array, and other clients (e.g., CodeGen) will perform the
1594 // necessary iteration with these index variables.
1595 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1596 QualType BaseType = Field->getType();
1597 QualType SizeType = SemaRef.Context.getSizeType();
1598 while (const ConstantArrayType *Array
1599 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1600 // Create the iteration variable for this array index.
1601 IdentifierInfo *IterationVarName = 0;
1602 {
1603 llvm::SmallString<8> Str;
1604 llvm::raw_svector_ostream OS(Str);
1605 OS << "__i" << IndexVariables.size();
1606 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1607 }
1608 VarDecl *IterationVar
1609 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1610 IterationVarName, SizeType,
1611 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
1612 VarDecl::None, VarDecl::None);
1613 IndexVariables.push_back(IterationVar);
1614
1615 // Create a reference to the iteration variable.
1616 Sema::OwningExprResult IterationVarRef
1617 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1618 assert(!IterationVarRef.isInvalid() &&
1619 "Reference to invented variable cannot fail!");
1620
1621 // Subscript the array with this iteration variable.
1622 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(move(CopyCtorArg),
1623 Loc,
1624 move(IterationVarRef),
1625 Loc);
1626 if (CopyCtorArg.isInvalid())
1627 return true;
1628
1629 BaseType = Array->getElementType();
1630 }
1631
1632 // Construct the entity that we will be initializing. For an array, this
1633 // will be first element in the array, which may require several levels
1634 // of array-subscript entities.
1635 llvm::SmallVector<InitializedEntity, 4> Entities;
1636 Entities.reserve(1 + IndexVariables.size());
1637 Entities.push_back(InitializedEntity::InitializeMember(Field));
1638 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1639 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1640 0,
1641 Entities.back()));
1642
1643 // Direct-initialize to use the copy constructor.
1644 InitializationKind InitKind =
1645 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1646
1647 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1648 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1649 &CopyCtorArgE, 1);
1650
1651 Sema::OwningExprResult MemberInit
1652 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
1653 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArgE, 1));
1654 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1655 if (MemberInit.isInvalid())
1656 return true;
1657
1658 CXXMemberInit
1659 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1660 MemberInit.takeAs<Expr>(), Loc,
1661 IndexVariables.data(),
1662 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001663 return false;
1664 }
1665
Anders Carlsson423f5d82010-04-23 16:04:08 +00001666 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1667
Anders Carlsson3c1db572010-04-23 02:15:47 +00001668 QualType FieldBaseElementType =
1669 SemaRef.Context.getBaseElementType(Field->getType());
1670
Anders Carlsson3c1db572010-04-23 02:15:47 +00001671 if (FieldBaseElementType->isRecordType()) {
1672 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001673 InitializationKind InitKind =
1674 InitializationKind::CreateDefault(Constructor->getLocation());
Anders Carlsson3c1db572010-04-23 02:15:47 +00001675
1676 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1677 Sema::OwningExprResult MemberInit =
1678 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1679 Sema::MultiExprArg(SemaRef, 0, 0));
1680 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1681 if (MemberInit.isInvalid())
1682 return true;
1683
1684 CXXMemberInit =
1685 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1686 Field, SourceLocation(),
1687 SourceLocation(),
1688 MemberInit.takeAs<Expr>(),
1689 SourceLocation());
1690 return false;
1691 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001692
1693 if (FieldBaseElementType->isReferenceType()) {
1694 SemaRef.Diag(Constructor->getLocation(),
1695 diag::err_uninitialized_member_in_ctor)
1696 << (int)Constructor->isImplicit()
1697 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1698 << 0 << Field->getDeclName();
1699 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1700 return true;
1701 }
1702
1703 if (FieldBaseElementType.isConstQualified()) {
1704 SemaRef.Diag(Constructor->getLocation(),
1705 diag::err_uninitialized_member_in_ctor)
1706 << (int)Constructor->isImplicit()
1707 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1708 << 1 << Field->getDeclName();
1709 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1710 return true;
1711 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001712
1713 // Nothing to initialize.
1714 CXXMemberInit = 0;
1715 return false;
1716}
John McCallbc83b3f2010-05-20 23:23:51 +00001717
1718namespace {
1719struct BaseAndFieldInfo {
1720 Sema &S;
1721 CXXConstructorDecl *Ctor;
1722 bool AnyErrorsInInits;
1723 ImplicitInitializerKind IIK;
1724 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1725 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1726
1727 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1728 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1729 // FIXME: Handle implicit move constructors.
1730 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1731 IIK = IIK_Copy;
1732 else
1733 IIK = IIK_Default;
1734 }
1735};
1736}
1737
1738static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1739 FieldDecl *Top, FieldDecl *Field) {
1740
1741 // Overwhelmingly common case: we have a direct initializer for this field.
1742 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
1743 Info.AllToInit.push_back(Init);
1744
1745 if (Field != Top) {
1746 Init->setMember(Top);
1747 Init->setAnonUnionMember(Field);
1748 }
1749 return false;
1750 }
1751
1752 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1753 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1754 assert(FieldClassType && "anonymous struct/union without record type");
1755
1756 // Walk through the members, tying in any initializers for fields
1757 // we find. The earlier semantic checks should prevent redundant
1758 // initialization of union members, given the requirement that
1759 // union members never have non-trivial default constructors.
1760
1761 // TODO: in C++0x, it might be legal to have union members with
1762 // non-trivial default constructors in unions. Revise this
1763 // implementation then with the appropriate semantics.
1764 CXXRecordDecl *FieldClassDecl
1765 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1766 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1767 EA = FieldClassDecl->field_end(); FA != EA; FA++)
1768 if (CollectFieldInitializer(Info, Top, *FA))
1769 return true;
1770 }
1771
1772 // Don't try to build an implicit initializer if there were semantic
1773 // errors in any of the initializers (and therefore we might be
1774 // missing some that the user actually wrote).
1775 if (Info.AnyErrorsInInits)
1776 return false;
1777
1778 CXXBaseOrMemberInitializer *Init = 0;
1779 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1780 return true;
1781
1782 // If the member doesn't need to be initialized, Init will still be null.
1783 if (!Init) return false;
1784
1785 Info.AllToInit.push_back(Init);
1786 if (Top != Field) {
1787 Init->setMember(Top);
1788 Init->setAnonUnionMember(Field);
1789 }
1790 return false;
1791}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001792
Eli Friedman9cf6b592009-11-09 19:20:36 +00001793bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001794Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001795 CXXBaseOrMemberInitializer **Initializers,
1796 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001797 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001798 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001799 // Just store the initializers as written, they will be checked during
1800 // instantiation.
1801 if (NumInitializers > 0) {
1802 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1803 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1804 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1805 memcpy(baseOrMemberInitializers, Initializers,
1806 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1807 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1808 }
1809
1810 return false;
1811 }
1812
John McCallbc83b3f2010-05-20 23:23:51 +00001813 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001814
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001815 // We need to build the initializer AST according to order of construction
1816 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001817 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001818 if (!ClassDecl)
1819 return true;
1820
Eli Friedman9cf6b592009-11-09 19:20:36 +00001821 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001822
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001823 for (unsigned i = 0; i < NumInitializers; i++) {
1824 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001825
1826 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001827 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001828 else
John McCallbc83b3f2010-05-20 23:23:51 +00001829 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001830 }
1831
Anders Carlsson43c64af2010-04-21 19:52:01 +00001832 // Keep track of the direct virtual bases.
1833 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1834 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1835 E = ClassDecl->bases_end(); I != E; ++I) {
1836 if (I->isVirtual())
1837 DirectVBases.insert(I);
1838 }
1839
Anders Carlssondb0a9652010-04-02 06:26:44 +00001840 // Push virtual bases before others.
1841 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1842 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1843
1844 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001845 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1846 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001847 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001848 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001849 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001850 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001851 VBase, IsInheritedVirtualBase,
1852 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001853 HadError = true;
1854 continue;
1855 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001856
John McCallbc83b3f2010-05-20 23:23:51 +00001857 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001858 }
1859 }
Mike Stump11289f42009-09-09 15:08:12 +00001860
John McCallbc83b3f2010-05-20 23:23:51 +00001861 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001862 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1863 E = ClassDecl->bases_end(); Base != E; ++Base) {
1864 // Virtuals are in the virtual base list and already constructed.
1865 if (Base->isVirtual())
1866 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001867
Anders Carlssondb0a9652010-04-02 06:26:44 +00001868 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001869 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1870 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001871 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001872 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001873 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001874 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001875 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001876 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001877 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001878 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001879
John McCallbc83b3f2010-05-20 23:23:51 +00001880 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001881 }
1882 }
Mike Stump11289f42009-09-09 15:08:12 +00001883
John McCallbc83b3f2010-05-20 23:23:51 +00001884 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001885 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001886 E = ClassDecl->field_end(); Field != E; ++Field) {
1887 if ((*Field)->getType()->isIncompleteArrayType()) {
1888 assert(ClassDecl->hasFlexibleArrayMember() &&
1889 "Incomplete array type is not valid");
1890 continue;
1891 }
John McCallbc83b3f2010-05-20 23:23:51 +00001892 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001893 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001894 }
Mike Stump11289f42009-09-09 15:08:12 +00001895
John McCallbc83b3f2010-05-20 23:23:51 +00001896 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001897 if (NumInitializers > 0) {
1898 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1899 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1900 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001901 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001902 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001903 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001904
John McCalla6309952010-03-16 21:39:52 +00001905 // Constructors implicitly reference the base and member
1906 // destructors.
1907 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1908 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001909 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001910
1911 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001912}
1913
Eli Friedman952c15d2009-07-21 19:28:10 +00001914static void *GetKeyForTopLevelField(FieldDecl *Field) {
1915 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001916 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001917 if (RT->getDecl()->isAnonymousStructOrUnion())
1918 return static_cast<void *>(RT->getDecl());
1919 }
1920 return static_cast<void *>(Field);
1921}
1922
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001923static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1924 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001925}
1926
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001927static void *GetKeyForMember(ASTContext &Context,
1928 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001929 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001930 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001931 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001932
Eli Friedman952c15d2009-07-21 19:28:10 +00001933 // For fields injected into the class via declaration of an anonymous union,
1934 // use its anonymous union class declaration as the unique key.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001935 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001936
Anders Carlssona942dcd2010-03-30 15:39:27 +00001937 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1938 // data member of the class. Data member used in the initializer list is
1939 // in AnonUnionMember field.
1940 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1941 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001942
John McCall23eebd92010-04-10 09:28:51 +00001943 // If the field is a member of an anonymous struct or union, our key
1944 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001945 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001946 if (RD->isAnonymousStructOrUnion()) {
1947 while (true) {
1948 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1949 if (Parent->isAnonymousStructOrUnion())
1950 RD = Parent;
1951 else
1952 break;
1953 }
1954
Anders Carlsson83ac3122010-03-30 16:19:37 +00001955 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001956 }
Mike Stump11289f42009-09-09 15:08:12 +00001957
Anders Carlssona942dcd2010-03-30 15:39:27 +00001958 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00001959}
1960
Anders Carlssone857b292010-04-02 03:37:03 +00001961static void
1962DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001963 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00001964 CXXBaseOrMemberInitializer **Inits,
1965 unsigned NumInits) {
1966 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001967 return;
Mike Stump11289f42009-09-09 15:08:12 +00001968
John McCallbb7b6582010-04-10 07:37:23 +00001969 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1970 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001971 return;
Anders Carlssone857b292010-04-02 03:37:03 +00001972
John McCallbb7b6582010-04-10 07:37:23 +00001973 // Build the list of bases and members in the order that they'll
1974 // actually be initialized. The explicit initializers should be in
1975 // this same order but may be missing things.
1976 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00001977
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001978 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1979
John McCallbb7b6582010-04-10 07:37:23 +00001980 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001981 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001982 ClassDecl->vbases_begin(),
1983 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00001984 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001985
John McCallbb7b6582010-04-10 07:37:23 +00001986 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001987 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001988 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00001989 if (Base->isVirtual())
1990 continue;
John McCallbb7b6582010-04-10 07:37:23 +00001991 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001992 }
Mike Stump11289f42009-09-09 15:08:12 +00001993
John McCallbb7b6582010-04-10 07:37:23 +00001994 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00001995 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1996 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00001997 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001998
John McCallbb7b6582010-04-10 07:37:23 +00001999 unsigned NumIdealInits = IdealInitKeys.size();
2000 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00002001
John McCallbb7b6582010-04-10 07:37:23 +00002002 CXXBaseOrMemberInitializer *PrevInit = 0;
2003 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2004 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
2005 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
2006
2007 // Scan forward to try to find this initializer in the idealized
2008 // initializers list.
2009 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2010 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002011 break;
John McCallbb7b6582010-04-10 07:37:23 +00002012
2013 // If we didn't find this initializer, it must be because we
2014 // scanned past it on a previous iteration. That can only
2015 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002016 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002017 Sema::SemaDiagnosticBuilder D =
2018 SemaRef.Diag(PrevInit->getSourceLocation(),
2019 diag::warn_initializer_out_of_order);
2020
2021 if (PrevInit->isMemberInitializer())
2022 D << 0 << PrevInit->getMember()->getDeclName();
2023 else
2024 D << 1 << PrevInit->getBaseClassInfo()->getType();
2025
2026 if (Init->isMemberInitializer())
2027 D << 0 << Init->getMember()->getDeclName();
2028 else
2029 D << 1 << Init->getBaseClassInfo()->getType();
2030
2031 // Move back to the initializer's location in the ideal list.
2032 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2033 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002034 break;
John McCallbb7b6582010-04-10 07:37:23 +00002035
2036 assert(IdealIndex != NumIdealInits &&
2037 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002038 }
John McCallbb7b6582010-04-10 07:37:23 +00002039
2040 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002041 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002042}
2043
John McCall23eebd92010-04-10 09:28:51 +00002044namespace {
2045bool CheckRedundantInit(Sema &S,
2046 CXXBaseOrMemberInitializer *Init,
2047 CXXBaseOrMemberInitializer *&PrevInit) {
2048 if (!PrevInit) {
2049 PrevInit = Init;
2050 return false;
2051 }
2052
2053 if (FieldDecl *Field = Init->getMember())
2054 S.Diag(Init->getSourceLocation(),
2055 diag::err_multiple_mem_initialization)
2056 << Field->getDeclName()
2057 << Init->getSourceRange();
2058 else {
2059 Type *BaseClass = Init->getBaseClass();
2060 assert(BaseClass && "neither field nor base");
2061 S.Diag(Init->getSourceLocation(),
2062 diag::err_multiple_base_initialization)
2063 << QualType(BaseClass, 0)
2064 << Init->getSourceRange();
2065 }
2066 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2067 << 0 << PrevInit->getSourceRange();
2068
2069 return true;
2070}
2071
2072typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2073typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2074
2075bool CheckRedundantUnionInit(Sema &S,
2076 CXXBaseOrMemberInitializer *Init,
2077 RedundantUnionMap &Unions) {
2078 FieldDecl *Field = Init->getMember();
2079 RecordDecl *Parent = Field->getParent();
2080 if (!Parent->isAnonymousStructOrUnion())
2081 return false;
2082
2083 NamedDecl *Child = Field;
2084 do {
2085 if (Parent->isUnion()) {
2086 UnionEntry &En = Unions[Parent];
2087 if (En.first && En.first != Child) {
2088 S.Diag(Init->getSourceLocation(),
2089 diag::err_multiple_mem_union_initialization)
2090 << Field->getDeclName()
2091 << Init->getSourceRange();
2092 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2093 << 0 << En.second->getSourceRange();
2094 return true;
2095 } else if (!En.first) {
2096 En.first = Child;
2097 En.second = Init;
2098 }
2099 }
2100
2101 Child = Parent;
2102 Parent = cast<RecordDecl>(Parent->getDeclContext());
2103 } while (Parent->isAnonymousStructOrUnion());
2104
2105 return false;
2106}
2107}
2108
Anders Carlssone857b292010-04-02 03:37:03 +00002109/// ActOnMemInitializers - Handle the member initializers for a constructor.
2110void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
2111 SourceLocation ColonLoc,
2112 MemInitTy **meminits, unsigned NumMemInits,
2113 bool AnyErrors) {
2114 if (!ConstructorDecl)
2115 return;
2116
2117 AdjustDeclIfTemplate(ConstructorDecl);
2118
2119 CXXConstructorDecl *Constructor
2120 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2121
2122 if (!Constructor) {
2123 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2124 return;
2125 }
2126
2127 CXXBaseOrMemberInitializer **MemInits =
2128 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002129
2130 // Mapping for the duplicate initializers check.
2131 // For member initializers, this is keyed with a FieldDecl*.
2132 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002133 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002134
2135 // Mapping for the inconsistent anonymous-union initializers check.
2136 RedundantUnionMap MemberUnions;
2137
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002138 bool HadError = false;
2139 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002140 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002141
Abramo Bagnara341d7832010-05-26 18:09:23 +00002142 // Set the source order index.
2143 Init->setSourceOrder(i);
2144
John McCall23eebd92010-04-10 09:28:51 +00002145 if (Init->isMemberInitializer()) {
2146 FieldDecl *Field = Init->getMember();
2147 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2148 CheckRedundantUnionInit(*this, Init, MemberUnions))
2149 HadError = true;
2150 } else {
2151 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2152 if (CheckRedundantInit(*this, Init, Members[Key]))
2153 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002154 }
Anders Carlssone857b292010-04-02 03:37:03 +00002155 }
2156
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002157 if (HadError)
2158 return;
2159
Anders Carlssone857b292010-04-02 03:37:03 +00002160 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002161
2162 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002163}
2164
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002165void
John McCalla6309952010-03-16 21:39:52 +00002166Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2167 CXXRecordDecl *ClassDecl) {
2168 // Ignore dependent contexts.
2169 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002170 return;
John McCall1064d7e2010-03-16 05:22:47 +00002171
2172 // FIXME: all the access-control diagnostics are positioned on the
2173 // field/base declaration. That's probably good; that said, the
2174 // user might reasonably want to know why the destructor is being
2175 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002176
Anders Carlssondee9a302009-11-17 04:44:12 +00002177 // Non-static data members.
2178 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2179 E = ClassDecl->field_end(); I != E; ++I) {
2180 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002181 if (Field->isInvalidDecl())
2182 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002183 QualType FieldType = Context.getBaseElementType(Field->getType());
2184
2185 const RecordType* RT = FieldType->getAs<RecordType>();
2186 if (!RT)
2187 continue;
2188
2189 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2190 if (FieldClassDecl->hasTrivialDestructor())
2191 continue;
2192
John McCall1064d7e2010-03-16 05:22:47 +00002193 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2194 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002195 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002196 << Field->getDeclName()
2197 << FieldType);
2198
John McCalla6309952010-03-16 21:39:52 +00002199 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002200 }
2201
John McCall1064d7e2010-03-16 05:22:47 +00002202 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2203
Anders Carlssondee9a302009-11-17 04:44:12 +00002204 // Bases.
2205 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2206 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002207 // Bases are always records in a well-formed non-dependent class.
2208 const RecordType *RT = Base->getType()->getAs<RecordType>();
2209
2210 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002211 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002212 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002213
2214 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002215 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002216 if (BaseClassDecl->hasTrivialDestructor())
2217 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002218
2219 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2220
2221 // FIXME: caret should be on the start of the class name
2222 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002223 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002224 << Base->getType()
2225 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002226
John McCalla6309952010-03-16 21:39:52 +00002227 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002228 }
2229
2230 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002231 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2232 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002233
2234 // Bases are always records in a well-formed non-dependent class.
2235 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2236
2237 // Ignore direct virtual bases.
2238 if (DirectVirtualBases.count(RT))
2239 continue;
2240
Anders Carlssondee9a302009-11-17 04:44:12 +00002241 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002242 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002243 if (BaseClassDecl->hasTrivialDestructor())
2244 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002245
2246 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2247 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002248 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002249 << VBase->getType());
2250
John McCalla6309952010-03-16 21:39:52 +00002251 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002252 }
2253}
2254
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00002255void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002256 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002257 return;
Mike Stump11289f42009-09-09 15:08:12 +00002258
Mike Stump11289f42009-09-09 15:08:12 +00002259 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002260 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002261 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002262}
2263
Mike Stump11289f42009-09-09 15:08:12 +00002264bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002265 unsigned DiagID, AbstractDiagSelID SelID,
2266 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002267 if (SelID == -1)
2268 return RequireNonAbstractType(Loc, T,
2269 PDiag(DiagID), CurrentRD);
2270 else
2271 return RequireNonAbstractType(Loc, T,
2272 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002273}
2274
Anders Carlssoneabf7702009-08-27 00:13:57 +00002275bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2276 const PartialDiagnostic &PD,
2277 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002278 if (!getLangOptions().CPlusPlus)
2279 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002280
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002281 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002282 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002283 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002284
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002285 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002286 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002287 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002288 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002289
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002290 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002291 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002292 }
Mike Stump11289f42009-09-09 15:08:12 +00002293
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002294 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002295 if (!RT)
2296 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002297
John McCall67da35c2010-02-04 22:26:26 +00002298 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002299
Anders Carlssonb57738b2009-03-24 17:23:42 +00002300 if (CurrentRD && CurrentRD != RD)
2301 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002302
John McCall67da35c2010-02-04 22:26:26 +00002303 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002304 if (!RD->getDefinition())
John McCall67da35c2010-02-04 22:26:26 +00002305 return false;
2306
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002307 if (!RD->isAbstract())
2308 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002309
Anders Carlssoneabf7702009-08-27 00:13:57 +00002310 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002311
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002312 // Check if we've already emitted the list of pure virtual functions for this
2313 // class.
2314 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2315 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002316
Douglas Gregor4165bd62010-03-23 23:47:56 +00002317 CXXFinalOverriderMap FinalOverriders;
2318 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002319
Anders Carlssona2f74f32010-06-03 01:00:02 +00002320 // Keep a set of seen pure methods so we won't diagnose the same method
2321 // more than once.
2322 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2323
Douglas Gregor4165bd62010-03-23 23:47:56 +00002324 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2325 MEnd = FinalOverriders.end();
2326 M != MEnd;
2327 ++M) {
2328 for (OverridingMethods::iterator SO = M->second.begin(),
2329 SOEnd = M->second.end();
2330 SO != SOEnd; ++SO) {
2331 // C++ [class.abstract]p4:
2332 // A class is abstract if it contains or inherits at least one
2333 // pure virtual function for which the final overrider is pure
2334 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002335
Douglas Gregor4165bd62010-03-23 23:47:56 +00002336 //
2337 if (SO->second.size() != 1)
2338 continue;
2339
2340 if (!SO->second.front().Method->isPure())
2341 continue;
2342
Anders Carlssona2f74f32010-06-03 01:00:02 +00002343 if (!SeenPureMethods.insert(SO->second.front().Method))
2344 continue;
2345
Douglas Gregor4165bd62010-03-23 23:47:56 +00002346 Diag(SO->second.front().Method->getLocation(),
2347 diag::note_pure_virtual_function)
2348 << SO->second.front().Method->getDeclName();
2349 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002350 }
2351
2352 if (!PureVirtualClassDiagSet)
2353 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2354 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002355
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002356 return true;
2357}
2358
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002359namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00002360 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002361 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2362 Sema &SemaRef;
2363 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00002364
Anders Carlssonb57738b2009-03-24 17:23:42 +00002365 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002366 bool Invalid = false;
2367
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002368 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2369 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002370 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002371
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002372 return Invalid;
2373 }
Mike Stump11289f42009-09-09 15:08:12 +00002374
Anders Carlssonb57738b2009-03-24 17:23:42 +00002375 public:
2376 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2377 : SemaRef(SemaRef), AbstractClass(ac) {
2378 Visit(SemaRef.Context.getTranslationUnitDecl());
2379 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002380
Anders Carlssonb57738b2009-03-24 17:23:42 +00002381 bool VisitFunctionDecl(const FunctionDecl *FD) {
2382 if (FD->isThisDeclarationADefinition()) {
2383 // No need to do the check if we're in a definition, because it requires
2384 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00002385 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00002386 return VisitDeclContext(FD);
2387 }
Mike Stump11289f42009-09-09 15:08:12 +00002388
Anders Carlssonb57738b2009-03-24 17:23:42 +00002389 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00002390 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00002391 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00002392 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2393 diag::err_abstract_type_in_decl,
2394 Sema::AbstractReturnType,
2395 AbstractClass);
2396
Mike Stump11289f42009-09-09 15:08:12 +00002397 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00002398 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002399 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002400 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002401 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002402 VD->getOriginalType(),
2403 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002404 Sema::AbstractParamType,
2405 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002406 }
2407
2408 return Invalid;
2409 }
Mike Stump11289f42009-09-09 15:08:12 +00002410
Anders Carlssonb57738b2009-03-24 17:23:42 +00002411 bool VisitDecl(const Decl* D) {
2412 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2413 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00002414
Anders Carlssonb57738b2009-03-24 17:23:42 +00002415 return false;
2416 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002417 };
2418}
2419
Douglas Gregorc99f1552009-12-03 18:33:45 +00002420/// \brief Perform semantic checks on a class definition that has been
2421/// completing, introducing implicitly-declared members, checking for
2422/// abstract types, etc.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002423void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
Douglas Gregorc99f1552009-12-03 18:33:45 +00002424 if (!Record || Record->isInvalidDecl())
2425 return;
2426
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002427 if (!Record->isDependentType())
Douglas Gregorb93b6062010-04-12 17:09:20 +00002428 AddImplicitlyDeclaredMembersToClass(S, Record);
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00002429
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002430 if (Record->isInvalidDecl())
2431 return;
2432
John McCall2cb94162010-01-28 07:38:46 +00002433 // Set access bits correctly on the directly-declared conversions.
2434 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2435 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2436 Convs->setAccess(I, (*I)->getAccess());
2437
Douglas Gregor4165bd62010-03-23 23:47:56 +00002438 // Determine whether we need to check for final overriders. We do
2439 // this either when there are virtual base classes (in which case we
2440 // may end up finding multiple final overriders for a given virtual
2441 // function) or any of the base classes is abstract (in which case
2442 // we might detect that this class is abstract).
2443 bool CheckFinalOverriders = false;
2444 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2445 !Record->isDependentType()) {
2446 if (Record->getNumVBases())
2447 CheckFinalOverriders = true;
2448 else if (!Record->isAbstract()) {
2449 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2450 BEnd = Record->bases_end();
2451 B != BEnd; ++B) {
2452 CXXRecordDecl *BaseDecl
2453 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2454 if (BaseDecl->isAbstract()) {
2455 CheckFinalOverriders = true;
2456 break;
2457 }
2458 }
2459 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002460 }
2461
Douglas Gregor4165bd62010-03-23 23:47:56 +00002462 if (CheckFinalOverriders) {
2463 CXXFinalOverriderMap FinalOverriders;
2464 Record->getFinalOverriders(FinalOverriders);
2465
2466 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2467 MEnd = FinalOverriders.end();
2468 M != MEnd; ++M) {
2469 for (OverridingMethods::iterator SO = M->second.begin(),
2470 SOEnd = M->second.end();
2471 SO != SOEnd; ++SO) {
2472 assert(SO->second.size() > 0 &&
2473 "All virtual functions have overridding virtual functions");
2474 if (SO->second.size() == 1) {
2475 // C++ [class.abstract]p4:
2476 // A class is abstract if it contains or inherits at least one
2477 // pure virtual function for which the final overrider is pure
2478 // virtual.
2479 if (SO->second.front().Method->isPure())
2480 Record->setAbstract(true);
2481 continue;
2482 }
2483
2484 // C++ [class.virtual]p2:
2485 // In a derived class, if a virtual member function of a base
2486 // class subobject has more than one final overrider the
2487 // program is ill-formed.
2488 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2489 << (NamedDecl *)M->first << Record;
2490 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2491 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2492 OMEnd = SO->second.end();
2493 OM != OMEnd; ++OM)
2494 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2495 << (NamedDecl *)M->first << OM->Method->getParent();
2496
2497 Record->setInvalidDecl();
2498 }
2499 }
2500 }
2501
2502 if (Record->isAbstract() && !Record->isInvalidDecl())
Douglas Gregorc99f1552009-12-03 18:33:45 +00002503 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor454a5b62010-04-15 00:00:53 +00002504
2505 // If this is not an aggregate type and has no user-declared constructor,
2506 // complain about any non-static data members of reference or const scalar
2507 // type, since they will never get initializers.
2508 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2509 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2510 bool Complained = false;
2511 for (RecordDecl::field_iterator F = Record->field_begin(),
2512 FEnd = Record->field_end();
2513 F != FEnd; ++F) {
2514 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002515 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002516 if (!Complained) {
2517 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2518 << Record->getTagKind() << Record;
2519 Complained = true;
2520 }
2521
2522 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2523 << F->getType()->isReferenceType()
2524 << F->getDeclName();
2525 }
2526 }
2527 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002528
2529 if (Record->isDynamicClass())
2530 DynamicClasses.push_back(Record);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002531}
2532
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002533void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002534 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002535 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002536 SourceLocation RBrac,
2537 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002538 if (!TagDecl)
2539 return;
Mike Stump11289f42009-09-09 15:08:12 +00002540
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002541 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002542
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002543 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002544 (DeclPtrTy*)FieldCollector->getCurFields(),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002545 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002546
Douglas Gregorb93b6062010-04-12 17:09:20 +00002547 CheckCompletedCXXClass(S,
Douglas Gregorc99f1552009-12-03 18:33:45 +00002548 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002549}
2550
Douglas Gregor05379422008-11-03 17:51:48 +00002551/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2552/// special functions, such as the default constructor, copy
2553/// constructor, or destructor, to the given C++ class (C++
2554/// [special]p1). This routine can only be executed just before the
2555/// definition of the class is complete.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002556///
2557/// The scope, if provided, is the class scope.
2558void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2559 CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002560 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002561 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002562
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002563 // FIXME: Implicit declarations have exception specifications, which are
2564 // the union of the specifications of the implicitly called functions.
2565
Douglas Gregor05379422008-11-03 17:51:48 +00002566 if (!ClassDecl->hasUserDeclaredConstructor()) {
2567 // C++ [class.ctor]p5:
2568 // A default constructor for a class X is a constructor of class X
2569 // that can be called without an argument. If there is no
2570 // user-declared constructor for class X, a default constructor is
2571 // implicitly declared. An implicitly-declared default constructor
2572 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002573 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002574 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002575 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002576 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002577 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002578 Context.getFunctionType(Context.VoidTy,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002579 0, 0, false, 0,
2580 /*FIXME*/false, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002581 0, 0,
2582 FunctionType::ExtInfo()),
John McCallbcd03502009-12-07 02:54:59 +00002583 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002584 /*isExplicit=*/false,
2585 /*isInline=*/true,
2586 /*isImplicitlyDeclared=*/true);
2587 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002588 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002589 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregorb93b6062010-04-12 17:09:20 +00002590 if (S)
2591 PushOnScopeChains(DefaultCon, S, true);
2592 else
2593 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002594 }
2595
2596 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2597 // C++ [class.copy]p4:
2598 // If the class definition does not explicitly declare a copy
2599 // constructor, one is declared implicitly.
2600
2601 // C++ [class.copy]p5:
2602 // The implicitly-declared copy constructor for a class X will
2603 // have the form
2604 //
2605 // X::X(const X&)
2606 //
2607 // if
2608 bool HasConstCopyConstructor = true;
2609
2610 // -- each direct or virtual base class B of X has a copy
2611 // constructor whose first parameter is of type const B& or
2612 // const volatile B&, and
2613 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2614 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2615 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002616 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002617 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002618 = BaseClassDecl->hasConstCopyConstructor(Context);
2619 }
2620
2621 // -- for all the nonstatic data members of X that are of a
2622 // class type M (or array thereof), each such class type
2623 // has a copy constructor whose first parameter is of type
2624 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002625 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2626 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002627 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002628 QualType FieldType = (*Field)->getType();
2629 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2630 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002631 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002632 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002633 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002634 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002635 = FieldClassDecl->hasConstCopyConstructor(Context);
2636 }
2637 }
2638
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002639 // Otherwise, the implicitly declared copy constructor will have
2640 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002641 //
2642 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002643 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002644 if (HasConstCopyConstructor)
2645 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002646 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002647
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002648 // An implicitly-declared copy constructor is an inline public
2649 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002650 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002651 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002652 CXXConstructorDecl *CopyConstructor
2653 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002654 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002655 Context.getFunctionType(Context.VoidTy,
2656 &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002657 false, 0,
Chris Lattner5c02c2a2010-05-12 23:26:21 +00002658 /*FIXME: hasExceptionSpec*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002659 false, 0, 0,
2660 FunctionType::ExtInfo()),
John McCallbcd03502009-12-07 02:54:59 +00002661 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002662 /*isExplicit=*/false,
2663 /*isInline=*/true,
2664 /*isImplicitlyDeclared=*/true);
2665 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002666 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002667 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002668
2669 // Add the parameter to the constructor.
2670 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2671 ClassDecl->getLocation(),
2672 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002673 ArgType, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002674 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002675 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002676 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregorb93b6062010-04-12 17:09:20 +00002677 if (S)
2678 PushOnScopeChains(CopyConstructor, S, true);
2679 else
2680 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002681 }
2682
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002683 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2684 // Note: The following rules are largely analoguous to the copy
2685 // constructor rules. Note that virtual bases are not taken into account
2686 // for determining the argument type of the operator. Note also that
2687 // operators taking an object instead of a reference are allowed.
2688 //
2689 // C++ [class.copy]p10:
2690 // If the class definition does not explicitly declare a copy
2691 // assignment operator, one is declared implicitly.
2692 // The implicitly-defined copy assignment operator for a class X
2693 // will have the form
2694 //
2695 // X& X::operator=(const X&)
2696 //
2697 // if
2698 bool HasConstCopyAssignment = true;
2699
2700 // -- each direct base class B of X has a copy assignment operator
2701 // whose parameter is of type const B&, const volatile B& or B,
2702 // and
2703 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2704 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002705 assert(!Base->getType()->isDependentType() &&
2706 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002707 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002708 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002709 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002710 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002711 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002712 }
2713
2714 // -- for all the nonstatic data members of X that are of a class
2715 // type M (or array thereof), each such class type has a copy
2716 // assignment operator whose parameter is of type const M&,
2717 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002718 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2719 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002720 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002721 QualType FieldType = (*Field)->getType();
2722 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2723 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002724 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002725 const CXXRecordDecl *FieldClassDecl
2726 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002727 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002728 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002729 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002730 }
2731 }
2732
2733 // Otherwise, the implicitly declared copy assignment operator will
2734 // have the form
2735 //
2736 // X& X::operator=(X&)
2737 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002738 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002739 if (HasConstCopyAssignment)
2740 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002741 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002742
2743 // An implicitly-declared copy assignment operator is an inline public
2744 // member of its class.
2745 DeclarationName Name =
2746 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2747 CXXMethodDecl *CopyAssignment =
2748 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2749 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002750 false, 0,
Chris Lattner5c02c2a2010-05-12 23:26:21 +00002751 /*FIXME: hasExceptionSpec*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002752 false, 0, 0,
2753 FunctionType::ExtInfo()),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002754 /*TInfo=*/0, /*isStatic=*/false,
2755 /*StorageClassAsWritten=*/FunctionDecl::None,
2756 /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002757 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002758 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002759 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002760 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002761
2762 // Add the parameter to the operator.
2763 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2764 ClassDecl->getLocation(),
Douglas Gregorb139cd52010-05-01 20:49:11 +00002765 /*Id=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002766 ArgType, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002767 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002768 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002769 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002770
2771 // Don't call addedAssignmentOperator. There is no way to distinguish an
2772 // implicit from an explicit assignment operator.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002773 if (S)
2774 PushOnScopeChains(CopyAssignment, S, true);
2775 else
2776 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002777 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002778 }
2779
Douglas Gregor1349b452008-12-15 21:24:18 +00002780 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002781 // C++ [class.dtor]p2:
2782 // If a class has no user-declared destructor, a destructor is
2783 // declared implicitly. An implicitly-declared destructor is an
2784 // inline public member of its class.
John McCall58f10c32010-03-11 09:03:00 +00002785 QualType Ty = Context.getFunctionType(Context.VoidTy,
2786 0, 0, false, 0,
Chris Lattner5c02c2a2010-05-12 23:26:21 +00002787 /*FIXME: hasExceptionSpec*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002788 false, 0, 0, FunctionType::ExtInfo());
John McCall58f10c32010-03-11 09:03:00 +00002789
Mike Stump11289f42009-09-09 15:08:12 +00002790 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002791 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002792 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002793 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall58f10c32010-03-11 09:03:00 +00002794 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002795 /*isInline=*/true,
2796 /*isImplicitlyDeclared=*/true);
2797 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002798 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002799 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregorb93b6062010-04-12 17:09:20 +00002800 if (S)
2801 PushOnScopeChains(Destructor, S, true);
2802 else
2803 ClassDecl->addDecl(Destructor);
John McCall58f10c32010-03-11 09:03:00 +00002804
2805 // This could be uniqued if it ever proves significant.
2806 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002807
2808 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002809 }
Douglas Gregor05379422008-11-03 17:51:48 +00002810}
2811
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002812void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002813 Decl *D = TemplateD.getAs<Decl>();
2814 if (!D)
2815 return;
2816
2817 TemplateParameterList *Params = 0;
2818 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2819 Params = Template->getTemplateParameters();
2820 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2821 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2822 Params = PartialSpec->getTemplateParameters();
2823 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002824 return;
2825
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002826 for (TemplateParameterList::iterator Param = Params->begin(),
2827 ParamEnd = Params->end();
2828 Param != ParamEnd; ++Param) {
2829 NamedDecl *Named = cast<NamedDecl>(*Param);
2830 if (Named->getDeclName()) {
2831 S->AddDecl(DeclPtrTy::make(Named));
2832 IdResolver.AddDecl(Named);
2833 }
2834 }
2835}
2836
John McCall6df5fef2009-12-19 10:49:29 +00002837void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2838 if (!RecordD) return;
2839 AdjustDeclIfTemplate(RecordD);
2840 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2841 PushDeclContext(S, Record);
2842}
2843
2844void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2845 if (!RecordD) return;
2846 PopDeclContext();
2847}
2848
Douglas Gregor4d87df52008-12-16 21:30:33 +00002849/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2850/// parsing a top-level (non-nested) C++ class, and we are now
2851/// parsing those parts of the given Method declaration that could
2852/// not be parsed earlier (C++ [class.mem]p2), such as default
2853/// arguments. This action should enter the scope of the given
2854/// Method declaration as if we had just parsed the qualified method
2855/// name. However, it should not bring the parameters into scope;
2856/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002857void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002858}
2859
2860/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2861/// C++ method declaration. We're (re-)introducing the given
2862/// function parameter into scope for use in parsing later parts of
2863/// the method declaration. For example, we could see an
2864/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002865void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002866 if (!ParamD)
2867 return;
Mike Stump11289f42009-09-09 15:08:12 +00002868
Chris Lattner83f095c2009-03-28 19:18:32 +00002869 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002870
2871 // If this parameter has an unparsed default argument, clear it out
2872 // to make way for the parsed default argument.
2873 if (Param->hasUnparsedDefaultArg())
2874 Param->setDefaultArg(0);
2875
Chris Lattner83f095c2009-03-28 19:18:32 +00002876 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002877 if (Param->getDeclName())
2878 IdResolver.AddDecl(Param);
2879}
2880
2881/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2882/// processing the delayed method declaration for Method. The method
2883/// declaration is now considered finished. There may be a separate
2884/// ActOnStartOfFunctionDef action later (not necessarily
2885/// immediately!) for this method, if it was also defined inside the
2886/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002887void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002888 if (!MethodD)
2889 return;
Mike Stump11289f42009-09-09 15:08:12 +00002890
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002891 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002892
Chris Lattner83f095c2009-03-28 19:18:32 +00002893 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002894
2895 // Now that we have our default arguments, check the constructor
2896 // again. It could produce additional diagnostics or affect whether
2897 // the class has implicitly-declared destructors, among other
2898 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002899 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2900 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002901
2902 // Check the default arguments, which we may have added.
2903 if (!Method->isInvalidDecl())
2904 CheckCXXDefaultArguments(Method);
2905}
2906
Douglas Gregor831c93f2008-11-05 20:51:48 +00002907/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002908/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002909/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002910/// emit diagnostics and set the invalid bit to true. In any case, the type
2911/// will be updated to reflect a well-formed type for the constructor and
2912/// returned.
2913QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2914 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002915 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002916
2917 // C++ [class.ctor]p3:
2918 // A constructor shall not be virtual (10.3) or static (9.4). A
2919 // constructor can be invoked for a const, volatile or const
2920 // volatile object. A constructor shall not be declared const,
2921 // volatile, or const volatile (9.3.2).
2922 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002923 if (!D.isInvalidType())
2924 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2925 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2926 << SourceRange(D.getIdentifierLoc());
2927 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002928 }
2929 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002930 if (!D.isInvalidType())
2931 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2932 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2933 << SourceRange(D.getIdentifierLoc());
2934 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002935 SC = FunctionDecl::None;
2936 }
Mike Stump11289f42009-09-09 15:08:12 +00002937
Chris Lattner38378bf2009-04-25 08:28:21 +00002938 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2939 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002940 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002941 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2942 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002943 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002944 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2945 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002946 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002947 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2948 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002949 }
Mike Stump11289f42009-09-09 15:08:12 +00002950
Douglas Gregor831c93f2008-11-05 20:51:48 +00002951 // Rebuild the function type "R" without any type qualifiers (in
2952 // case any of the errors above fired) and with "void" as the
2953 // return type, since constructors don't have return types. We
2954 // *always* have to do this, because GetTypeForDeclarator will
2955 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002956 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002957 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2958 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002959 Proto->isVariadic(), 0,
2960 Proto->hasExceptionSpec(),
2961 Proto->hasAnyExceptionSpec(),
2962 Proto->getNumExceptions(),
2963 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002964 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002965}
2966
Douglas Gregor4d87df52008-12-16 21:30:33 +00002967/// CheckConstructor - Checks a fully-formed constructor for
2968/// well-formedness, issuing any diagnostics required. Returns true if
2969/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002970void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002971 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002972 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2973 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002974 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002975
2976 // C++ [class.copy]p3:
2977 // A declaration of a constructor for a class X is ill-formed if
2978 // its first parameter is of type (optionally cv-qualified) X and
2979 // either there are no other parameters or else all other
2980 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002981 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002982 ((Constructor->getNumParams() == 1) ||
2983 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002984 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2985 Constructor->getTemplateSpecializationKind()
2986 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002987 QualType ParamType = Constructor->getParamDecl(0)->getType();
2988 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2989 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002990 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002991 const char *ConstRef
2992 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2993 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002994 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002995 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002996
2997 // FIXME: Rather that making the constructor invalid, we should endeavor
2998 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002999 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00003000 }
3001 }
Mike Stump11289f42009-09-09 15:08:12 +00003002
John McCall43314ab2010-04-13 07:45:41 +00003003 // Notify the class that we've added a constructor. In principle we
3004 // don't need to do this for out-of-line declarations; in practice
3005 // we only instantiate the most recent declaration of a method, so
3006 // we have to call this for everything but friends.
3007 if (!Constructor->getFriendObjectKind())
3008 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00003009}
3010
Anders Carlsson26a807d2009-11-30 21:24:50 +00003011/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
3012/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00003013bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00003014 CXXRecordDecl *RD = Destructor->getParent();
3015
3016 if (Destructor->isVirtual()) {
3017 SourceLocation Loc;
3018
3019 if (!Destructor->isImplicit())
3020 Loc = Destructor->getLocation();
3021 else
3022 Loc = RD->getLocation();
3023
3024 // If we have a virtual destructor, look up the deallocation function
3025 FunctionDecl *OperatorDelete = 0;
3026 DeclarationName Name =
3027 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00003028 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00003029 return true;
3030
3031 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00003032 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00003033
3034 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00003035}
3036
Mike Stump11289f42009-09-09 15:08:12 +00003037static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00003038FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
3039 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3040 FTI.ArgInfo[0].Param &&
3041 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
3042}
3043
Douglas Gregor831c93f2008-11-05 20:51:48 +00003044/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3045/// the well-formednes of the destructor declarator @p D with type @p
3046/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00003047/// emit diagnostics and set the declarator to invalid. Even if this happens,
3048/// will be updated to reflect a well-formed type for the destructor and
3049/// returned.
3050QualType Sema::CheckDestructorDeclarator(Declarator &D,
3051 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003052 // C++ [class.dtor]p1:
3053 // [...] A typedef-name that names a class is a class-name
3054 // (7.1.3); however, a typedef-name that names a class shall not
3055 // be used as the identifier in the declarator for a destructor
3056 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00003057 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00003058 if (isa<TypedefType>(DeclaratorType)) {
3059 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00003060 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00003061 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003062 }
3063
3064 // C++ [class.dtor]p2:
3065 // A destructor is used to destroy objects of its class type. A
3066 // destructor takes no parameters, and no return type can be
3067 // specified for it (not even void). The address of a destructor
3068 // shall not be taken. A destructor shall not be static. A
3069 // destructor can be invoked for a const, volatile or const
3070 // volatile object. A destructor shall not be declared const,
3071 // volatile or const volatile (9.3.2).
3072 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00003073 if (!D.isInvalidType())
3074 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
3075 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3076 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003077 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00003078 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003079 }
Chris Lattner38378bf2009-04-25 08:28:21 +00003080 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003081 // Destructors don't have return types, but the parser will
3082 // happily parse something like:
3083 //
3084 // class X {
3085 // float ~X();
3086 // };
3087 //
3088 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00003089 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
3090 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3091 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003092 }
Mike Stump11289f42009-09-09 15:08:12 +00003093
Chris Lattner38378bf2009-04-25 08:28:21 +00003094 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
3095 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003096 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00003097 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3098 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003099 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00003100 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3101 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00003102 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00003103 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
3104 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00003105 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003106 }
3107
3108 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00003109 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003110 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
3111
3112 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00003113 FTI.freeArgs();
3114 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00003115 }
3116
Mike Stump11289f42009-09-09 15:08:12 +00003117 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00003118 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00003119 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00003120 D.setInvalidType();
3121 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00003122
3123 // Rebuild the function type "R" without any type qualifiers or
3124 // parameters (in case any of the errors above fired) and with
3125 // "void" as the return type, since destructors don't have return
3126 // types. We *always* have to do this, because GetTypeForDeclarator
3127 // will put in a result type of "int" when none was specified.
Douglas Gregor36c569f2010-02-21 22:15:06 +00003128 // FIXME: Exceptions!
3129 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003130 false, false, 0, 0, FunctionType::ExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003131}
3132
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003133/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3134/// well-formednes of the conversion function declarator @p D with
3135/// type @p R. If there are any errors in the declarator, this routine
3136/// will emit diagnostics and return true. Otherwise, it will return
3137/// false. Either way, the type @p R will be updated to reflect a
3138/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003139void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003140 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003141 // C++ [class.conv.fct]p1:
3142 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003143 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003144 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003145 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003146 if (!D.isInvalidType())
3147 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3148 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3149 << SourceRange(D.getIdentifierLoc());
3150 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003151 SC = FunctionDecl::None;
3152 }
John McCall212fa2e2010-04-13 00:04:31 +00003153
3154 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3155
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003156 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003157 // Conversion functions don't have return types, but the parser will
3158 // happily parse something like:
3159 //
3160 // class X {
3161 // float operator bool();
3162 // };
3163 //
3164 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003165 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3166 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3167 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003168 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003169 }
3170
John McCall212fa2e2010-04-13 00:04:31 +00003171 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3172
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003173 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003174 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003175 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3176
3177 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003178 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003179 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003180 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003181 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003182 D.setInvalidType();
3183 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003184
John McCall212fa2e2010-04-13 00:04:31 +00003185 // Diagnose "&operator bool()" and other such nonsense. This
3186 // is actually a gcc extension which we don't support.
3187 if (Proto->getResultType() != ConvType) {
3188 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3189 << Proto->getResultType();
3190 D.setInvalidType();
3191 ConvType = Proto->getResultType();
3192 }
3193
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003194 // C++ [class.conv.fct]p4:
3195 // The conversion-type-id shall not represent a function type nor
3196 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003197 if (ConvType->isArrayType()) {
3198 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3199 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003200 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003201 } else if (ConvType->isFunctionType()) {
3202 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3203 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003204 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003205 }
3206
3207 // Rebuild the function type "R" without any parameters (in case any
3208 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003209 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003210 if (D.isInvalidType()) {
3211 R = Context.getFunctionType(ConvType, 0, 0, false,
3212 Proto->getTypeQuals(),
3213 Proto->hasExceptionSpec(),
3214 Proto->hasAnyExceptionSpec(),
3215 Proto->getNumExceptions(),
3216 Proto->exception_begin(),
3217 Proto->getExtInfo());
3218 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003219
Douglas Gregor5fb53972009-01-14 15:45:31 +00003220 // C++0x explicit conversion operators.
3221 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003222 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003223 diag::warn_explicit_conversion_functions)
3224 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003225}
3226
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003227/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3228/// the declaration of the given C++ conversion function. This routine
3229/// is responsible for recording the conversion function in the C++
3230/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00003231Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003232 assert(Conversion && "Expected to receive a conversion function declaration");
3233
Douglas Gregor4287b372008-12-12 08:25:50 +00003234 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003235
3236 // Make sure we aren't redeclaring the conversion function.
3237 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003238
3239 // C++ [class.conv.fct]p1:
3240 // [...] A conversion function is never used to convert a
3241 // (possibly cv-qualified) object to the (possibly cv-qualified)
3242 // same object type (or a reference to it), to a (possibly
3243 // cv-qualified) base class of that type (or a reference to it),
3244 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003245 // FIXME: Suppress this warning if the conversion function ends up being a
3246 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003247 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003248 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003249 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003250 ConvType = ConvTypeRef->getPointeeType();
3251 if (ConvType->isRecordType()) {
3252 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3253 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003254 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003255 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003256 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003257 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003258 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003259 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003260 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003261 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003262 }
3263
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003264 if (Conversion->getPrimaryTemplate()) {
3265 // ignore specializations
3266 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump11289f42009-09-09 15:08:12 +00003267 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor133bc742010-01-11 18:53:25 +00003268 = Conversion->getDescribedFunctionTemplate()) {
3269 if (ClassDecl->replaceConversion(
3270 ConversionTemplate->getPreviousDeclaration(),
3271 ConversionTemplate))
3272 return DeclPtrTy::make(ConversionTemplate);
3273 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3274 Conversion))
John McCalld14a8642009-11-21 08:51:07 +00003275 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00003276 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00003277 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003278 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003279 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003280 else
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003281 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003282
Chris Lattner83f095c2009-03-28 19:18:32 +00003283 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003284}
3285
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003286//===----------------------------------------------------------------------===//
3287// Namespace Handling
3288//===----------------------------------------------------------------------===//
3289
3290/// ActOnStartNamespaceDef - This is called at the start of a namespace
3291/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00003292Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3293 SourceLocation IdentLoc,
3294 IdentifierInfo *II,
Anders Carlssona7bcade2010-02-07 01:09:23 +00003295 SourceLocation LBrace,
3296 AttributeList *AttrList) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003297 NamespaceDecl *Namespc =
3298 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3299 Namespc->setLBracLoc(LBrace);
3300
3301 Scope *DeclRegionScope = NamespcScope->getParent();
3302
Anders Carlssona7bcade2010-02-07 01:09:23 +00003303 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3304
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003305 if (II) {
3306 // C++ [namespace.def]p2:
3307 // The identifier in an original-namespace-definition shall not have been
3308 // previously defined in the declarative region in which the
3309 // original-namespace-definition appears. The identifier in an
3310 // original-namespace-definition is the name of the namespace. Subsequently
3311 // in that declarative region, it is treated as an original-namespace-name.
3312
John McCall9f3059a2009-10-09 21:13:30 +00003313 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003314 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003315 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00003316
Douglas Gregor91f84212008-12-11 16:49:14 +00003317 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3318 // This is an extended namespace definition.
3319 // Attach this namespace decl to the chain of extended namespace
3320 // definitions.
3321 OrigNS->setNextNamespace(Namespc);
3322 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003323
Mike Stump11289f42009-09-09 15:08:12 +00003324 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003325 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003326 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00003327 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003328 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003329 } else if (PrevDecl) {
3330 // This is an invalid name redefinition.
3331 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3332 << Namespc->getDeclName();
3333 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3334 Namespc->setInvalidDecl();
3335 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003336 } else if (II->isStr("std") &&
3337 CurContext->getLookupContext()->isTranslationUnit()) {
3338 // This is the first "real" definition of the namespace "std", so update
3339 // our cache of the "std" namespace to point at this definition.
3340 if (StdNamespace) {
3341 // We had already defined a dummy namespace "std". Link this new
3342 // namespace definition to the dummy namespace "std".
3343 StdNamespace->setNextNamespace(Namespc);
3344 StdNamespace->setLocation(IdentLoc);
3345 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3346 }
3347
3348 // Make our StdNamespace cache point at the first real definition of the
3349 // "std" namespace.
3350 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003351 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003352
3353 PushOnScopeChains(Namespc, DeclRegionScope);
3354 } else {
John McCall4fa53422009-10-01 00:25:31 +00003355 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003356 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003357
3358 // Link the anonymous namespace into its parent.
3359 NamespaceDecl *PrevDecl;
3360 DeclContext *Parent = CurContext->getLookupContext();
3361 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3362 PrevDecl = TU->getAnonymousNamespace();
3363 TU->setAnonymousNamespace(Namespc);
3364 } else {
3365 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3366 PrevDecl = ND->getAnonymousNamespace();
3367 ND->setAnonymousNamespace(Namespc);
3368 }
3369
3370 // Link the anonymous namespace with its previous declaration.
3371 if (PrevDecl) {
3372 assert(PrevDecl->isAnonymousNamespace());
3373 assert(!PrevDecl->getNextNamespace());
3374 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3375 PrevDecl->setNextNamespace(Namespc);
3376 }
John McCall4fa53422009-10-01 00:25:31 +00003377
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003378 CurContext->addDecl(Namespc);
3379
John McCall4fa53422009-10-01 00:25:31 +00003380 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3381 // behaves as if it were replaced by
3382 // namespace unique { /* empty body */ }
3383 // using namespace unique;
3384 // namespace unique { namespace-body }
3385 // where all occurrences of 'unique' in a translation unit are
3386 // replaced by the same identifier and this identifier differs
3387 // from all other identifiers in the entire program.
3388
3389 // We just create the namespace with an empty name and then add an
3390 // implicit using declaration, just like the standard suggests.
3391 //
3392 // CodeGen enforces the "universally unique" aspect by giving all
3393 // declarations semantically contained within an anonymous
3394 // namespace internal linkage.
3395
John McCall0db42252009-12-16 02:06:49 +00003396 if (!PrevDecl) {
3397 UsingDirectiveDecl* UD
3398 = UsingDirectiveDecl::Create(Context, CurContext,
3399 /* 'using' */ LBrace,
3400 /* 'namespace' */ SourceLocation(),
3401 /* qualifier */ SourceRange(),
3402 /* NNS */ NULL,
3403 /* identifier */ SourceLocation(),
3404 Namespc,
3405 /* Ancestor */ CurContext);
3406 UD->setImplicit();
3407 CurContext->addDecl(UD);
3408 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003409 }
3410
3411 // Although we could have an invalid decl (i.e. the namespace name is a
3412 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003413 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3414 // for the namespace has the declarations that showed up in that particular
3415 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003416 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00003417 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003418}
3419
Sebastian Redla6602e92009-11-23 15:34:23 +00003420/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3421/// is a namespace alias, returns the namespace it points to.
3422static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3423 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3424 return AD->getNamespace();
3425 return dyn_cast_or_null<NamespaceDecl>(D);
3426}
3427
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003428/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3429/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00003430void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3431 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003432 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3433 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3434 Namespc->setRBracLoc(RBrace);
3435 PopDeclContext();
3436}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003437
Chris Lattner83f095c2009-03-28 19:18:32 +00003438Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3439 SourceLocation UsingLoc,
3440 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003441 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003442 SourceLocation IdentLoc,
3443 IdentifierInfo *NamespcName,
3444 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003445 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3446 assert(NamespcName && "Invalid NamespcName.");
3447 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003448 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003449
Douglas Gregor889ceb72009-02-03 19:21:40 +00003450 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00003451
Douglas Gregor34074322009-01-14 22:20:51 +00003452 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003453 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3454 LookupParsedName(R, S, &SS);
3455 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003456 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00003457
John McCall9f3059a2009-10-09 21:13:30 +00003458 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003459 NamedDecl *Named = R.getFoundDecl();
3460 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3461 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003462 // C++ [namespace.udir]p1:
3463 // A using-directive specifies that the names in the nominated
3464 // namespace can be used in the scope in which the
3465 // using-directive appears after the using-directive. During
3466 // unqualified name lookup (3.4.1), the names appear as if they
3467 // were declared in the nearest enclosing namespace which
3468 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003469 // namespace. [Note: in this context, "contains" means "contains
3470 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003471
3472 // Find enclosing context containing both using-directive and
3473 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003474 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003475 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3476 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3477 CommonAncestor = CommonAncestor->getParent();
3478
Sebastian Redla6602e92009-11-23 15:34:23 +00003479 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003480 SS.getRange(),
3481 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003482 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003483 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003484 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003485 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003486 }
3487
Douglas Gregor889ceb72009-02-03 19:21:40 +00003488 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003489 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00003490 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003491}
3492
3493void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3494 // If scope has associated entity, then using directive is at namespace
3495 // or translation unit scope. We add UsingDirectiveDecls, into
3496 // it's lookup structure.
3497 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003498 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003499 else
3500 // Otherwise it is block-sope. using-directives will affect lookup
3501 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003502 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00003503}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003504
Douglas Gregorfec52632009-06-20 00:51:54 +00003505
3506Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003507 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003508 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003509 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003510 CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003511 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003512 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003513 bool IsTypeName,
3514 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003515 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003516
Douglas Gregor220f4272009-11-04 16:30:06 +00003517 switch (Name.getKind()) {
3518 case UnqualifiedId::IK_Identifier:
3519 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003520 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003521 case UnqualifiedId::IK_ConversionFunctionId:
3522 break;
3523
3524 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003525 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003526 // C++0x inherited constructors.
3527 if (getLangOptions().CPlusPlus0x) break;
3528
Douglas Gregor220f4272009-11-04 16:30:06 +00003529 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3530 << SS.getRange();
3531 return DeclPtrTy();
3532
3533 case UnqualifiedId::IK_DestructorName:
3534 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3535 << SS.getRange();
3536 return DeclPtrTy();
3537
3538 case UnqualifiedId::IK_TemplateId:
3539 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3540 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3541 return DeclPtrTy();
3542 }
3543
3544 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3969e302009-12-08 07:46:18 +00003545 if (!TargetName)
3546 return DeclPtrTy();
3547
John McCalla0097262009-12-11 02:10:03 +00003548 // Warn about using declarations.
3549 // TODO: store that the declaration was written without 'using' and
3550 // talk about access decls instead of using decls in the
3551 // diagnostics.
3552 if (!HasUsingKeyword) {
3553 UsingLoc = Name.getSourceRange().getBegin();
3554
3555 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003556 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003557 }
3558
John McCall3f746822009-11-17 05:59:44 +00003559 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003560 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00003561 TargetName, AttrList,
3562 /* IsInstantiation */ false,
3563 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003564 if (UD)
3565 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003566
Anders Carlsson696a3f12009-08-28 05:40:36 +00003567 return DeclPtrTy::make(UD);
3568}
3569
John McCall84d87672009-12-10 09:41:52 +00003570/// Determines whether to create a using shadow decl for a particular
3571/// decl, given the set of decls existing prior to this using lookup.
3572bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3573 const LookupResult &Previous) {
3574 // Diagnose finding a decl which is not from a base class of the
3575 // current class. We do this now because there are cases where this
3576 // function will silently decide not to build a shadow decl, which
3577 // will pre-empt further diagnostics.
3578 //
3579 // We don't need to do this in C++0x because we do the check once on
3580 // the qualifier.
3581 //
3582 // FIXME: diagnose the following if we care enough:
3583 // struct A { int foo; };
3584 // struct B : A { using A::foo; };
3585 // template <class T> struct C : A {};
3586 // template <class T> struct D : C<T> { using B::foo; } // <---
3587 // This is invalid (during instantiation) in C++03 because B::foo
3588 // resolves to the using decl in B, which is not a base class of D<T>.
3589 // We can't diagnose it immediately because C<T> is an unknown
3590 // specialization. The UsingShadowDecl in D<T> then points directly
3591 // to A::foo, which will look well-formed when we instantiate.
3592 // The right solution is to not collapse the shadow-decl chain.
3593 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3594 DeclContext *OrigDC = Orig->getDeclContext();
3595
3596 // Handle enums and anonymous structs.
3597 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3598 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3599 while (OrigRec->isAnonymousStructOrUnion())
3600 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3601
3602 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3603 if (OrigDC == CurContext) {
3604 Diag(Using->getLocation(),
3605 diag::err_using_decl_nested_name_specifier_is_current_class)
3606 << Using->getNestedNameRange();
3607 Diag(Orig->getLocation(), diag::note_using_decl_target);
3608 return true;
3609 }
3610
3611 Diag(Using->getNestedNameRange().getBegin(),
3612 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3613 << Using->getTargetNestedNameDecl()
3614 << cast<CXXRecordDecl>(CurContext)
3615 << Using->getNestedNameRange();
3616 Diag(Orig->getLocation(), diag::note_using_decl_target);
3617 return true;
3618 }
3619 }
3620
3621 if (Previous.empty()) return false;
3622
3623 NamedDecl *Target = Orig;
3624 if (isa<UsingShadowDecl>(Target))
3625 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3626
John McCalla17e83e2009-12-11 02:33:26 +00003627 // If the target happens to be one of the previous declarations, we
3628 // don't have a conflict.
3629 //
3630 // FIXME: but we might be increasing its access, in which case we
3631 // should redeclare it.
3632 NamedDecl *NonTag = 0, *Tag = 0;
3633 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3634 I != E; ++I) {
3635 NamedDecl *D = (*I)->getUnderlyingDecl();
3636 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3637 return false;
3638
3639 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3640 }
3641
John McCall84d87672009-12-10 09:41:52 +00003642 if (Target->isFunctionOrFunctionTemplate()) {
3643 FunctionDecl *FD;
3644 if (isa<FunctionTemplateDecl>(Target))
3645 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3646 else
3647 FD = cast<FunctionDecl>(Target);
3648
3649 NamedDecl *OldDecl = 0;
3650 switch (CheckOverload(FD, Previous, OldDecl)) {
3651 case Ovl_Overload:
3652 return false;
3653
3654 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003655 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003656 break;
3657
3658 // We found a decl with the exact signature.
3659 case Ovl_Match:
3660 if (isa<UsingShadowDecl>(OldDecl)) {
3661 // Silently ignore the possible conflict.
3662 return false;
3663 }
3664
3665 // If we're in a record, we want to hide the target, so we
3666 // return true (without a diagnostic) to tell the caller not to
3667 // build a shadow decl.
3668 if (CurContext->isRecord())
3669 return true;
3670
3671 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003672 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003673 break;
3674 }
3675
3676 Diag(Target->getLocation(), diag::note_using_decl_target);
3677 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3678 return true;
3679 }
3680
3681 // Target is not a function.
3682
John McCall84d87672009-12-10 09:41:52 +00003683 if (isa<TagDecl>(Target)) {
3684 // No conflict between a tag and a non-tag.
3685 if (!Tag) return false;
3686
John McCalle29c5cd2009-12-10 19:51:03 +00003687 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003688 Diag(Target->getLocation(), diag::note_using_decl_target);
3689 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3690 return true;
3691 }
3692
3693 // No conflict between a tag and a non-tag.
3694 if (!NonTag) return false;
3695
John McCalle29c5cd2009-12-10 19:51:03 +00003696 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003697 Diag(Target->getLocation(), diag::note_using_decl_target);
3698 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3699 return true;
3700}
3701
John McCall3f746822009-11-17 05:59:44 +00003702/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003703UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003704 UsingDecl *UD,
3705 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003706
3707 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003708 NamedDecl *Target = Orig;
3709 if (isa<UsingShadowDecl>(Target)) {
3710 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3711 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003712 }
3713
3714 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003715 = UsingShadowDecl::Create(Context, CurContext,
3716 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003717 UD->addShadowDecl(Shadow);
3718
3719 if (S)
John McCall3969e302009-12-08 07:46:18 +00003720 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003721 else
John McCall3969e302009-12-08 07:46:18 +00003722 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003723 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003724
John McCallda4458e2010-03-31 01:36:47 +00003725 // Register it as a conversion if appropriate.
3726 if (Shadow->getDeclName().getNameKind()
3727 == DeclarationName::CXXConversionFunctionName)
3728 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3729
John McCall3969e302009-12-08 07:46:18 +00003730 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3731 Shadow->setInvalidDecl();
3732
John McCall84d87672009-12-10 09:41:52 +00003733 return Shadow;
3734}
John McCall3969e302009-12-08 07:46:18 +00003735
John McCall84d87672009-12-10 09:41:52 +00003736/// Hides a using shadow declaration. This is required by the current
3737/// using-decl implementation when a resolvable using declaration in a
3738/// class is followed by a declaration which would hide or override
3739/// one or more of the using decl's targets; for example:
3740///
3741/// struct Base { void foo(int); };
3742/// struct Derived : Base {
3743/// using Base::foo;
3744/// void foo(int);
3745/// };
3746///
3747/// The governing language is C++03 [namespace.udecl]p12:
3748///
3749/// When a using-declaration brings names from a base class into a
3750/// derived class scope, member functions in the derived class
3751/// override and/or hide member functions with the same name and
3752/// parameter types in a base class (rather than conflicting).
3753///
3754/// There are two ways to implement this:
3755/// (1) optimistically create shadow decls when they're not hidden
3756/// by existing declarations, or
3757/// (2) don't create any shadow decls (or at least don't make them
3758/// visible) until we've fully parsed/instantiated the class.
3759/// The problem with (1) is that we might have to retroactively remove
3760/// a shadow decl, which requires several O(n) operations because the
3761/// decl structures are (very reasonably) not designed for removal.
3762/// (2) avoids this but is very fiddly and phase-dependent.
3763void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003764 if (Shadow->getDeclName().getNameKind() ==
3765 DeclarationName::CXXConversionFunctionName)
3766 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3767
John McCall84d87672009-12-10 09:41:52 +00003768 // Remove it from the DeclContext...
3769 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003770
John McCall84d87672009-12-10 09:41:52 +00003771 // ...and the scope, if applicable...
3772 if (S) {
3773 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3774 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003775 }
3776
John McCall84d87672009-12-10 09:41:52 +00003777 // ...and the using decl.
3778 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3779
3780 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003781 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003782}
3783
John McCalle61f2ba2009-11-18 02:36:19 +00003784/// Builds a using declaration.
3785///
3786/// \param IsInstantiation - Whether this call arises from an
3787/// instantiation of an unresolved using declaration. We treat
3788/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003789NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3790 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003791 CXXScopeSpec &SS,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003792 SourceLocation IdentLoc,
3793 DeclarationName Name,
3794 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003795 bool IsInstantiation,
3796 bool IsTypeName,
3797 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003798 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3799 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003800
Anders Carlssonf038fc22009-08-28 05:49:21 +00003801 // FIXME: We ignore attributes for now.
3802 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003803
Anders Carlsson59140b32009-08-28 03:16:11 +00003804 if (SS.isEmpty()) {
3805 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003806 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003807 }
Mike Stump11289f42009-09-09 15:08:12 +00003808
John McCall84d87672009-12-10 09:41:52 +00003809 // Do the redeclaration lookup in the current scope.
3810 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3811 ForRedeclaration);
3812 Previous.setHideTags(false);
3813 if (S) {
3814 LookupName(Previous, S);
3815
3816 // It is really dumb that we have to do this.
3817 LookupResult::Filter F = Previous.makeFilter();
3818 while (F.hasNext()) {
3819 NamedDecl *D = F.next();
3820 if (!isDeclInScope(D, CurContext, S))
3821 F.erase();
3822 }
3823 F.done();
3824 } else {
3825 assert(IsInstantiation && "no scope in non-instantiation");
3826 assert(CurContext->isRecord() && "scope not record in instantiation");
3827 LookupQualifiedName(Previous, CurContext);
3828 }
3829
Mike Stump11289f42009-09-09 15:08:12 +00003830 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003831 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3832
John McCall84d87672009-12-10 09:41:52 +00003833 // Check for invalid redeclarations.
3834 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3835 return 0;
3836
3837 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003838 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3839 return 0;
3840
John McCall84c16cf2009-11-12 03:15:40 +00003841 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003842 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003843 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003844 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003845 // FIXME: not all declaration name kinds are legal here
3846 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3847 UsingLoc, TypenameLoc,
3848 SS.getRange(), NNS,
John McCalle61f2ba2009-11-18 02:36:19 +00003849 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00003850 } else {
3851 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3852 UsingLoc, SS.getRange(), NNS,
3853 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00003854 }
John McCallb96ec562009-12-04 22:46:56 +00003855 } else {
3856 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3857 SS.getRange(), UsingLoc, NNS, Name,
3858 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003859 }
John McCallb96ec562009-12-04 22:46:56 +00003860 D->setAccess(AS);
3861 CurContext->addDecl(D);
3862
3863 if (!LookupContext) return D;
3864 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003865
John McCall0b66eb32010-05-01 00:40:08 +00003866 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003867 UD->setInvalidDecl();
3868 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003869 }
3870
John McCall3969e302009-12-08 07:46:18 +00003871 // Look up the target name.
3872
John McCall27b18f82009-11-17 02:14:36 +00003873 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003874
John McCall3969e302009-12-08 07:46:18 +00003875 // Unlike most lookups, we don't always want to hide tag
3876 // declarations: tag names are visible through the using declaration
3877 // even if hidden by ordinary names, *except* in a dependent context
3878 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003879 if (!IsInstantiation)
3880 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003881
John McCall27b18f82009-11-17 02:14:36 +00003882 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003883
John McCall9f3059a2009-10-09 21:13:30 +00003884 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003885 Diag(IdentLoc, diag::err_no_member)
3886 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003887 UD->setInvalidDecl();
3888 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003889 }
3890
John McCallb96ec562009-12-04 22:46:56 +00003891 if (R.isAmbiguous()) {
3892 UD->setInvalidDecl();
3893 return UD;
3894 }
Mike Stump11289f42009-09-09 15:08:12 +00003895
John McCalle61f2ba2009-11-18 02:36:19 +00003896 if (IsTypeName) {
3897 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003898 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003899 Diag(IdentLoc, diag::err_using_typename_non_type);
3900 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3901 Diag((*I)->getUnderlyingDecl()->getLocation(),
3902 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003903 UD->setInvalidDecl();
3904 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003905 }
3906 } else {
3907 // If we asked for a non-typename and we got a type, error out,
3908 // but only if this is an instantiation of an unresolved using
3909 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003910 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003911 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3912 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003913 UD->setInvalidDecl();
3914 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003915 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003916 }
3917
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003918 // C++0x N2914 [namespace.udecl]p6:
3919 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003920 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003921 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3922 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003923 UD->setInvalidDecl();
3924 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003925 }
Mike Stump11289f42009-09-09 15:08:12 +00003926
John McCall84d87672009-12-10 09:41:52 +00003927 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3928 if (!CheckUsingShadowDecl(UD, *I, Previous))
3929 BuildUsingShadowDecl(S, UD, *I);
3930 }
John McCall3f746822009-11-17 05:59:44 +00003931
3932 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003933}
3934
John McCall84d87672009-12-10 09:41:52 +00003935/// Checks that the given using declaration is not an invalid
3936/// redeclaration. Note that this is checking only for the using decl
3937/// itself, not for any ill-formedness among the UsingShadowDecls.
3938bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3939 bool isTypeName,
3940 const CXXScopeSpec &SS,
3941 SourceLocation NameLoc,
3942 const LookupResult &Prev) {
3943 // C++03 [namespace.udecl]p8:
3944 // C++0x [namespace.udecl]p10:
3945 // A using-declaration is a declaration and can therefore be used
3946 // repeatedly where (and only where) multiple declarations are
3947 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00003948 //
3949 // That's in non-member contexts.
3950 if (!CurContext->getLookupContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00003951 return false;
3952
3953 NestedNameSpecifier *Qual
3954 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3955
3956 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3957 NamedDecl *D = *I;
3958
3959 bool DTypename;
3960 NestedNameSpecifier *DQual;
3961 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3962 DTypename = UD->isTypeName();
3963 DQual = UD->getTargetNestedNameDecl();
3964 } else if (UnresolvedUsingValueDecl *UD
3965 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3966 DTypename = false;
3967 DQual = UD->getTargetNestedNameSpecifier();
3968 } else if (UnresolvedUsingTypenameDecl *UD
3969 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3970 DTypename = true;
3971 DQual = UD->getTargetNestedNameSpecifier();
3972 } else continue;
3973
3974 // using decls differ if one says 'typename' and the other doesn't.
3975 // FIXME: non-dependent using decls?
3976 if (isTypeName != DTypename) continue;
3977
3978 // using decls differ if they name different scopes (but note that
3979 // template instantiation can cause this check to trigger when it
3980 // didn't before instantiation).
3981 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3982 Context.getCanonicalNestedNameSpecifier(DQual))
3983 continue;
3984
3985 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003986 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003987 return true;
3988 }
3989
3990 return false;
3991}
3992
John McCall3969e302009-12-08 07:46:18 +00003993
John McCallb96ec562009-12-04 22:46:56 +00003994/// Checks that the given nested-name qualifier used in a using decl
3995/// in the current context is appropriately related to the current
3996/// scope. If an error is found, diagnoses it and returns true.
3997bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3998 const CXXScopeSpec &SS,
3999 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00004000 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00004001
John McCall3969e302009-12-08 07:46:18 +00004002 if (!CurContext->isRecord()) {
4003 // C++03 [namespace.udecl]p3:
4004 // C++0x [namespace.udecl]p8:
4005 // A using-declaration for a class member shall be a member-declaration.
4006
4007 // If we weren't able to compute a valid scope, it must be a
4008 // dependent class scope.
4009 if (!NamedContext || NamedContext->isRecord()) {
4010 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
4011 << SS.getRange();
4012 return true;
4013 }
4014
4015 // Otherwise, everything is known to be fine.
4016 return false;
4017 }
4018
4019 // The current scope is a record.
4020
4021 // If the named context is dependent, we can't decide much.
4022 if (!NamedContext) {
4023 // FIXME: in C++0x, we can diagnose if we can prove that the
4024 // nested-name-specifier does not refer to a base class, which is
4025 // still possible in some cases.
4026
4027 // Otherwise we have to conservatively report that things might be
4028 // okay.
4029 return false;
4030 }
4031
4032 if (!NamedContext->isRecord()) {
4033 // Ideally this would point at the last name in the specifier,
4034 // but we don't have that level of source info.
4035 Diag(SS.getRange().getBegin(),
4036 diag::err_using_decl_nested_name_specifier_is_not_class)
4037 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
4038 return true;
4039 }
4040
4041 if (getLangOptions().CPlusPlus0x) {
4042 // C++0x [namespace.udecl]p3:
4043 // In a using-declaration used as a member-declaration, the
4044 // nested-name-specifier shall name a base class of the class
4045 // being defined.
4046
4047 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
4048 cast<CXXRecordDecl>(NamedContext))) {
4049 if (CurContext == NamedContext) {
4050 Diag(NameLoc,
4051 diag::err_using_decl_nested_name_specifier_is_current_class)
4052 << SS.getRange();
4053 return true;
4054 }
4055
4056 Diag(SS.getRange().getBegin(),
4057 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4058 << (NestedNameSpecifier*) SS.getScopeRep()
4059 << cast<CXXRecordDecl>(CurContext)
4060 << SS.getRange();
4061 return true;
4062 }
4063
4064 return false;
4065 }
4066
4067 // C++03 [namespace.udecl]p4:
4068 // A using-declaration used as a member-declaration shall refer
4069 // to a member of a base class of the class being defined [etc.].
4070
4071 // Salient point: SS doesn't have to name a base class as long as
4072 // lookup only finds members from base classes. Therefore we can
4073 // diagnose here only if we can prove that that can't happen,
4074 // i.e. if the class hierarchies provably don't intersect.
4075
4076 // TODO: it would be nice if "definitely valid" results were cached
4077 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4078 // need to be repeated.
4079
4080 struct UserData {
4081 llvm::DenseSet<const CXXRecordDecl*> Bases;
4082
4083 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4084 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4085 Data->Bases.insert(Base);
4086 return true;
4087 }
4088
4089 bool hasDependentBases(const CXXRecordDecl *Class) {
4090 return !Class->forallBases(collect, this);
4091 }
4092
4093 /// Returns true if the base is dependent or is one of the
4094 /// accumulated base classes.
4095 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4096 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4097 return !Data->Bases.count(Base);
4098 }
4099
4100 bool mightShareBases(const CXXRecordDecl *Class) {
4101 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4102 }
4103 };
4104
4105 UserData Data;
4106
4107 // Returns false if we find a dependent base.
4108 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4109 return false;
4110
4111 // Returns false if the class has a dependent base or if it or one
4112 // of its bases is present in the base set of the current context.
4113 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4114 return false;
4115
4116 Diag(SS.getRange().getBegin(),
4117 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4118 << (NestedNameSpecifier*) SS.getScopeRep()
4119 << cast<CXXRecordDecl>(CurContext)
4120 << SS.getRange();
4121
4122 return true;
John McCallb96ec562009-12-04 22:46:56 +00004123}
4124
Mike Stump11289f42009-09-09 15:08:12 +00004125Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004126 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004127 SourceLocation AliasLoc,
4128 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004129 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004130 SourceLocation IdentLoc,
4131 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004132
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004133 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004134 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4135 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004136
Anders Carlssondca83c42009-03-28 06:23:46 +00004137 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004138 NamedDecl *PrevDecl
4139 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4140 ForRedeclaration);
4141 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4142 PrevDecl = 0;
4143
4144 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004145 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004146 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004147 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004148 // FIXME: At some point, we'll want to create the (redundant)
4149 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004150 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004151 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004152 return DeclPtrTy();
4153 }
Mike Stump11289f42009-09-09 15:08:12 +00004154
Anders Carlssondca83c42009-03-28 06:23:46 +00004155 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4156 diag::err_redefinition_different_kind;
4157 Diag(AliasLoc, DiagID) << Alias;
4158 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00004159 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00004160 }
4161
John McCall27b18f82009-11-17 02:14:36 +00004162 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00004163 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00004164
John McCall9f3059a2009-10-09 21:13:30 +00004165 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00004166 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004167 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00004168 }
Mike Stump11289f42009-09-09 15:08:12 +00004169
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004170 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004171 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4172 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004173 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004174 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004175
John McCalld8d0d432010-02-16 06:53:13 +00004176 PushOnScopeChains(AliasDecl, S);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00004177 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00004178}
4179
Douglas Gregora57478e2010-05-01 15:04:51 +00004180namespace {
4181 /// \brief Scoped object used to handle the state changes required in Sema
4182 /// to implicitly define the body of a C++ member function;
4183 class ImplicitlyDefinedFunctionScope {
4184 Sema &S;
4185 DeclContext *PreviousContext;
4186
4187 public:
4188 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4189 : S(S), PreviousContext(S.CurContext)
4190 {
4191 S.CurContext = Method;
4192 S.PushFunctionScope();
4193 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4194 }
4195
4196 ~ImplicitlyDefinedFunctionScope() {
4197 S.PopExpressionEvaluationContext();
4198 S.PopFunctionOrBlockScope();
4199 S.CurContext = PreviousContext;
4200 }
4201 };
4202}
4203
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004204void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4205 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004206 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4207 !Constructor->isUsed()) &&
4208 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004209
Anders Carlsson423f5d82010-04-23 16:04:08 +00004210 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004211 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004212
Douglas Gregora57478e2010-05-01 15:04:51 +00004213 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00004214 ErrorTrap Trap(*this);
4215 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4216 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004217 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004218 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004219 Constructor->setInvalidDecl();
4220 } else {
4221 Constructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004222 MarkVTableUsed(CurrentLocation, ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004223 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004224}
4225
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004226void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004227 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004228 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4229 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004230 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004231 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004232
Douglas Gregor54818f02010-05-12 16:39:35 +00004233 if (Destructor->isInvalidDecl())
4234 return;
4235
Douglas Gregora57478e2010-05-01 15:04:51 +00004236 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004237
Douglas Gregor54818f02010-05-12 16:39:35 +00004238 ErrorTrap Trap(*this);
John McCalla6309952010-03-16 21:39:52 +00004239 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4240 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004241
Douglas Gregor54818f02010-05-12 16:39:35 +00004242 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004243 Diag(CurrentLocation, diag::note_member_synthesized_at)
4244 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4245
4246 Destructor->setInvalidDecl();
4247 return;
4248 }
4249
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004250 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004251 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004252}
4253
Douglas Gregorb139cd52010-05-01 20:49:11 +00004254/// \brief Builds a statement that copies the given entity from \p From to
4255/// \c To.
4256///
4257/// This routine is used to copy the members of a class with an
4258/// implicitly-declared copy assignment operator. When the entities being
4259/// copied are arrays, this routine builds for loops to copy them.
4260///
4261/// \param S The Sema object used for type-checking.
4262///
4263/// \param Loc The location where the implicit copy is being generated.
4264///
4265/// \param T The type of the expressions being copied. Both expressions must
4266/// have this type.
4267///
4268/// \param To The expression we are copying to.
4269///
4270/// \param From The expression we are copying from.
4271///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004272/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4273/// Otherwise, it's a non-static member subobject.
4274///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004275/// \param Depth Internal parameter recording the depth of the recursion.
4276///
4277/// \returns A statement or a loop that copies the expressions.
4278static Sema::OwningStmtResult
4279BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4280 Sema::OwningExprResult To, Sema::OwningExprResult From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004281 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004282 typedef Sema::OwningStmtResult OwningStmtResult;
4283 typedef Sema::OwningExprResult OwningExprResult;
4284
4285 // C++0x [class.copy]p30:
4286 // Each subobject is assigned in the manner appropriate to its type:
4287 //
4288 // - if the subobject is of class type, the copy assignment operator
4289 // for the class is used (as if by explicit qualification; that is,
4290 // ignoring any possible virtual overriding functions in more derived
4291 // classes);
4292 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4293 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4294
4295 // Look for operator=.
4296 DeclarationName Name
4297 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4298 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4299 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4300
4301 // Filter out any result that isn't a copy-assignment operator.
4302 LookupResult::Filter F = OpLookup.makeFilter();
4303 while (F.hasNext()) {
4304 NamedDecl *D = F.next();
4305 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4306 if (Method->isCopyAssignmentOperator())
4307 continue;
4308
4309 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004310 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004311 F.done();
4312
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004313 // Suppress the protected check (C++ [class.protected]) for each of the
4314 // assignment operators we found. This strange dance is required when
4315 // we're assigning via a base classes's copy-assignment operator. To
4316 // ensure that we're getting the right base class subobject (without
4317 // ambiguities), we need to cast "this" to that subobject type; to
4318 // ensure that we don't go through the virtual call mechanism, we need
4319 // to qualify the operator= name with the base class (see below). However,
4320 // this means that if the base class has a protected copy assignment
4321 // operator, the protected member access check will fail. So, we
4322 // rewrite "protected" access to "public" access in this case, since we
4323 // know by construction that we're calling from a derived class.
4324 if (CopyingBaseSubobject) {
4325 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4326 L != LEnd; ++L) {
4327 if (L.getAccess() == AS_protected)
4328 L.setAccess(AS_public);
4329 }
4330 }
4331
Douglas Gregorb139cd52010-05-01 20:49:11 +00004332 // Create the nested-name-specifier that will be used to qualify the
4333 // reference to operator=; this is required to suppress the virtual
4334 // call mechanism.
4335 CXXScopeSpec SS;
4336 SS.setRange(Loc);
4337 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4338 T.getTypePtr()));
4339
4340 // Create the reference to operator=.
4341 OwningExprResult OpEqualRef
4342 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4343 /*FirstQualifierInScope=*/0, OpLookup,
4344 /*TemplateArgs=*/0,
4345 /*SuppressQualifierCheck=*/true);
4346 if (OpEqualRef.isInvalid())
4347 return S.StmtError();
4348
4349 // Build the call to the assignment operator.
4350 Expr *FromE = From.takeAs<Expr>();
4351 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4352 OpEqualRef.takeAs<Expr>(),
4353 Loc, &FromE, 1, 0, Loc);
4354 if (Call.isInvalid())
4355 return S.StmtError();
4356
4357 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004358 }
John McCallab8c2732010-03-16 06:11:48 +00004359
Douglas Gregorb139cd52010-05-01 20:49:11 +00004360 // - if the subobject is of scalar type, the built-in assignment
4361 // operator is used.
4362 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4363 if (!ArrayTy) {
4364 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4365 BinaryOperator::Assign,
4366 To.takeAs<Expr>(),
4367 From.takeAs<Expr>());
4368 if (Assignment.isInvalid())
4369 return S.StmtError();
4370
4371 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004372 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004373
4374 // - if the subobject is an array, each element is assigned, in the
4375 // manner appropriate to the element type;
4376
4377 // Construct a loop over the array bounds, e.g.,
4378 //
4379 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4380 //
4381 // that will copy each of the array elements.
4382 QualType SizeType = S.Context.getSizeType();
4383
4384 // Create the iteration variable.
4385 IdentifierInfo *IterationVarName = 0;
4386 {
4387 llvm::SmallString<8> Str;
4388 llvm::raw_svector_ostream OS(Str);
4389 OS << "__i" << Depth;
4390 IterationVarName = &S.Context.Idents.get(OS.str());
4391 }
4392 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4393 IterationVarName, SizeType,
4394 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4395 VarDecl::None, VarDecl::None);
4396
4397 // Initialize the iteration variable to zero.
4398 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4399 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4400
4401 // Create a reference to the iteration variable; we'll use this several
4402 // times throughout.
4403 Expr *IterationVarRef
4404 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4405 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4406
4407 // Create the DeclStmt that holds the iteration variable.
4408 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4409
4410 // Create the comparison against the array bound.
4411 llvm::APInt Upper = ArrayTy->getSize();
4412 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4413 OwningExprResult Comparison
4414 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4415 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4416 BinaryOperator::NE, S.Context.BoolTy, Loc));
4417
4418 // Create the pre-increment of the iteration variable.
4419 OwningExprResult Increment
4420 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4421 UnaryOperator::PreInc,
4422 SizeType, Loc));
4423
4424 // Subscript the "from" and "to" expressions with the iteration variable.
4425 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4426 S.Owned(IterationVarRef->Retain()),
4427 Loc);
4428 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4429 S.Owned(IterationVarRef->Retain()),
4430 Loc);
4431 assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4432 assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4433
4434 // Build the copy for an individual element of the array.
4435 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4436 ArrayTy->getElementType(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004437 move(To), move(From),
4438 CopyingBaseSubobject, Depth+1);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004439 if (Copy.isInvalid()) {
4440 InitStmt->Destroy(S.Context);
4441 return S.StmtError();
4442 }
4443
4444 // Construct the loop that copies all elements of this array.
4445 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4446 S.MakeFullExpr(Comparison),
4447 Sema::DeclPtrTy(),
4448 S.MakeFullExpr(Increment),
4449 Loc, move(Copy));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004450}
4451
Douglas Gregorb139cd52010-05-01 20:49:11 +00004452void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4453 CXXMethodDecl *CopyAssignOperator) {
4454 assert((CopyAssignOperator->isImplicit() &&
4455 CopyAssignOperator->isOverloadedOperator() &&
4456 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
4457 !CopyAssignOperator->isUsed()) &&
4458 "DefineImplicitCopyAssignment called for wrong function");
4459
4460 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4461
4462 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4463 CopyAssignOperator->setInvalidDecl();
4464 return;
4465 }
4466
4467 CopyAssignOperator->setUsed();
4468
4469 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregor54818f02010-05-12 16:39:35 +00004470 ErrorTrap Trap(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004471
4472 // C++0x [class.copy]p30:
4473 // The implicitly-defined or explicitly-defaulted copy assignment operator
4474 // for a non-union class X performs memberwise copy assignment of its
4475 // subobjects. The direct base classes of X are assigned first, in the
4476 // order of their declaration in the base-specifier-list, and then the
4477 // immediate non-static data members of X are assigned, in the order in
4478 // which they were declared in the class definition.
4479
4480 // The statements that form the synthesized function body.
4481 ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this);
4482
4483 // The parameter for the "other" object, which we are copying from.
4484 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4485 Qualifiers OtherQuals = Other->getType().getQualifiers();
4486 QualType OtherRefType = Other->getType();
4487 if (const LValueReferenceType *OtherRef
4488 = OtherRefType->getAs<LValueReferenceType>()) {
4489 OtherRefType = OtherRef->getPointeeType();
4490 OtherQuals = OtherRefType.getQualifiers();
4491 }
4492
4493 // Our location for everything implicitly-generated.
4494 SourceLocation Loc = CopyAssignOperator->getLocation();
4495
4496 // Construct a reference to the "other" object. We'll be using this
4497 // throughout the generated ASTs.
4498 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4499 assert(OtherRef && "Reference to parameter cannot fail!");
4500
4501 // Construct the "this" pointer. We'll be using this throughout the generated
4502 // ASTs.
4503 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4504 assert(This && "Reference to this cannot fail!");
4505
4506 // Assign base classes.
4507 bool Invalid = false;
4508 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4509 E = ClassDecl->bases_end(); Base != E; ++Base) {
4510 // Form the assignment:
4511 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4512 QualType BaseType = Base->getType().getUnqualifiedType();
4513 CXXRecordDecl *BaseClassDecl = 0;
4514 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4515 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4516 else {
4517 Invalid = true;
4518 continue;
4519 }
4520
4521 // Construct the "from" expression, which is an implicit cast to the
4522 // appropriately-qualified base type.
4523 Expr *From = OtherRef->Retain();
4524 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
4525 CastExpr::CK_UncheckedDerivedToBase, /*isLvalue=*/true,
4526 CXXBaseSpecifierArray(Base));
4527
4528 // Dereference "this".
4529 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4530 Owned(This->Retain()));
4531
4532 // Implicitly cast "this" to the appropriately-qualified base type.
4533 Expr *ToE = To.takeAs<Expr>();
4534 ImpCastExprToType(ToE,
4535 Context.getCVRQualifiedType(BaseType,
4536 CopyAssignOperator->getTypeQualifiers()),
4537 CastExpr::CK_UncheckedDerivedToBase,
4538 /*isLvalue=*/true, CXXBaseSpecifierArray(Base));
4539 To = Owned(ToE);
4540
4541 // Build the copy.
4542 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004543 move(To), Owned(From),
4544 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004545 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004546 Diag(CurrentLocation, diag::note_member_synthesized_at)
4547 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4548 CopyAssignOperator->setInvalidDecl();
4549 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004550 }
4551
4552 // Success! Record the copy.
4553 Statements.push_back(Copy.takeAs<Expr>());
4554 }
4555
4556 // \brief Reference to the __builtin_memcpy function.
4557 Expr *BuiltinMemCpyRef = 0;
4558
4559 // Assign non-static members.
4560 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4561 FieldEnd = ClassDecl->field_end();
4562 Field != FieldEnd; ++Field) {
4563 // Check for members of reference type; we can't copy those.
4564 if (Field->getType()->isReferenceType()) {
4565 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4566 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4567 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004568 Diag(CurrentLocation, diag::note_member_synthesized_at)
4569 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004570 Invalid = true;
4571 continue;
4572 }
4573
4574 // Check for members of const-qualified, non-class type.
4575 QualType BaseType = Context.getBaseElementType(Field->getType());
4576 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4577 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4578 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4579 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004580 Diag(CurrentLocation, diag::note_member_synthesized_at)
4581 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004582 Invalid = true;
4583 continue;
4584 }
4585
4586 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004587 if (FieldType->isIncompleteArrayType()) {
4588 assert(ClassDecl->hasFlexibleArrayMember() &&
4589 "Incomplete array type is not valid");
4590 continue;
4591 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004592
4593 // Build references to the field in the object we're copying from and to.
4594 CXXScopeSpec SS; // Intentionally empty
4595 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4596 LookupMemberName);
4597 MemberLookup.addDecl(*Field);
4598 MemberLookup.resolveKind();
4599 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
4600 OtherRefType,
4601 Loc, /*IsArrow=*/false,
4602 SS, 0, MemberLookup, 0);
4603 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
4604 This->getType(),
4605 Loc, /*IsArrow=*/true,
4606 SS, 0, MemberLookup, 0);
4607 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4608 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4609
4610 // If the field should be copied with __builtin_memcpy rather than via
4611 // explicit assignments, do so. This optimization only applies for arrays
4612 // of scalars and arrays of class type with trivial copy-assignment
4613 // operators.
4614 if (FieldType->isArrayType() &&
4615 (!BaseType->isRecordType() ||
4616 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4617 ->hasTrivialCopyAssignment())) {
4618 // Compute the size of the memory buffer to be copied.
4619 QualType SizeType = Context.getSizeType();
4620 llvm::APInt Size(Context.getTypeSize(SizeType),
4621 Context.getTypeSizeInChars(BaseType).getQuantity());
4622 for (const ConstantArrayType *Array
4623 = Context.getAsConstantArrayType(FieldType);
4624 Array;
4625 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4626 llvm::APInt ArraySize = Array->getSize();
4627 ArraySize.zextOrTrunc(Size.getBitWidth());
4628 Size *= ArraySize;
4629 }
4630
4631 // Take the address of the field references for "from" and "to".
4632 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
4633 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
4634
4635 // Create a reference to the __builtin_memcpy builtin function.
4636 if (!BuiltinMemCpyRef) {
4637 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
4638 LookupOrdinaryName);
4639 LookupName(R, TUScope, true);
4640
4641 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
4642 if (!BuiltinMemCpy) {
4643 // Something went horribly wrong earlier, and we will have complained
4644 // about it.
4645 Invalid = true;
4646 continue;
4647 }
4648
4649 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
4650 BuiltinMemCpy->getType(),
4651 Loc, 0).takeAs<Expr>();
4652 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
4653 }
4654
4655 ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this);
4656 CallArgs.push_back(To.takeAs<Expr>());
4657 CallArgs.push_back(From.takeAs<Expr>());
4658 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
4659 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
4660 Commas.push_back(Loc);
4661 Commas.push_back(Loc);
4662 OwningExprResult Call = ActOnCallExpr(/*Scope=*/0,
4663 Owned(BuiltinMemCpyRef->Retain()),
4664 Loc, move_arg(CallArgs),
4665 Commas.data(), Loc);
4666 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
4667 Statements.push_back(Call.takeAs<Expr>());
4668 continue;
4669 }
4670
4671 // Build the copy of this field.
4672 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004673 move(To), move(From),
4674 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004675 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004676 Diag(CurrentLocation, diag::note_member_synthesized_at)
4677 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4678 CopyAssignOperator->setInvalidDecl();
4679 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004680 }
4681
4682 // Success! Record the copy.
4683 Statements.push_back(Copy.takeAs<Stmt>());
4684 }
4685
4686 if (!Invalid) {
4687 // Add a "return *this;"
4688 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4689 Owned(This->Retain()));
4690
4691 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
4692 if (Return.isInvalid())
4693 Invalid = true;
4694 else {
4695 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00004696
4697 if (Trap.hasErrorOccurred()) {
4698 Diag(CurrentLocation, diag::note_member_synthesized_at)
4699 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4700 Invalid = true;
4701 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004702 }
4703 }
4704
4705 if (Invalid) {
4706 CopyAssignOperator->setInvalidDecl();
4707 return;
4708 }
4709
4710 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
4711 /*isStmtExpr=*/false);
4712 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
4713 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004714}
4715
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004716void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4717 CXXConstructorDecl *CopyConstructor,
4718 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00004719 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00004720 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004721 !CopyConstructor->isUsed()) &&
4722 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004723
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00004724 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004725 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004726
Douglas Gregora57478e2010-05-01 15:04:51 +00004727 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00004728 ErrorTrap Trap(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004729
Douglas Gregor54818f02010-05-12 16:39:35 +00004730 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
4731 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00004732 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00004733 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00004734 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00004735 } else {
4736 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
4737 CopyConstructor->getLocation(),
4738 MultiStmtArg(*this, 0, 0),
4739 /*isStmtExpr=*/false)
4740 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00004741 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00004742
4743 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004744}
4745
Anders Carlsson6eb55572009-08-25 05:12:04 +00004746Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004747Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00004748 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004749 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004750 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004751 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson250aada2009-08-16 05:13:48 +00004752 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00004753
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004754 // C++0x [class.copy]p34:
4755 // When certain criteria are met, an implementation is allowed to
4756 // omit the copy/move construction of a class object, even if the
4757 // copy/move constructor and/or destructor for the object have
4758 // side effects. [...]
4759 // - when a temporary class object that has not been bound to a
4760 // reference (12.2) would be copied/moved to a class object
4761 // with the same cv-unqualified type, the copy/move operation
4762 // can be omitted by constructing the temporary object
4763 // directly into the target of the omitted copy/move
4764 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4765 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4766 Elidable = SubExpr->isTemporaryObject() &&
4767 Context.hasSameUnqualifiedType(SubExpr->getType(),
4768 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson250aada2009-08-16 05:13:48 +00004769 }
Mike Stump11289f42009-09-09 15:08:12 +00004770
4771 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004772 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004773 ConstructKind);
Anders Carlsson250aada2009-08-16 05:13:48 +00004774}
4775
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004776/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4777/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00004778Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004779Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4780 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004781 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004782 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004783 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004784 unsigned NumExprs = ExprArgs.size();
4785 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00004786
Douglas Gregor27381f32009-11-23 12:27:39 +00004787 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004788 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004789 Constructor, Elidable, Exprs, NumExprs,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004790 RequiresZeroInit, ConstructKind));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004791}
4792
Mike Stump11289f42009-09-09 15:08:12 +00004793bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004794 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004795 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00004796 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00004797 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004798 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004799 if (TempResult.isInvalid())
4800 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004801
Anders Carlsson6eb55572009-08-25 05:12:04 +00004802 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00004803 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00004804 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00004805 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00004806
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004807 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00004808}
4809
John McCall03c48482010-02-02 09:10:11 +00004810void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4811 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00004812 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00004813 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
John McCall6781b052010-02-02 08:45:54 +00004814 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4815 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00004816 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00004817 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00004818 << VD->getDeclName()
4819 << VD->getType());
John McCall6781b052010-02-02 08:45:54 +00004820 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004821}
4822
Mike Stump11289f42009-09-09 15:08:12 +00004823/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004824/// ActOnDeclarator, when a C++ direct initializer is present.
4825/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00004826void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4827 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00004828 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004829 SourceLocation *CommaLocs,
4830 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00004831 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00004832 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004833
4834 // If there is no declaration, there was an error parsing it. Just ignore
4835 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00004836 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004837 return;
Mike Stump11289f42009-09-09 15:08:12 +00004838
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004839 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4840 if (!VDecl) {
4841 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4842 RealDecl->setInvalidDecl();
4843 return;
4844 }
4845
Douglas Gregor402250f2009-08-26 21:14:46 +00004846 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004847 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004848 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4849 //
4850 // Clients that want to distinguish between the two forms, can check for
4851 // direct initializer using VarDecl::hasCXXDirectInitializer().
4852 // A major benefit is that clients that don't particularly care about which
4853 // exactly form was it (like the CodeGen) can handle both cases without
4854 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004855
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004856 // C++ 8.5p11:
4857 // The form of initialization (using parentheses or '=') is generally
4858 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004859 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004860 QualType DeclInitType = VDecl->getType();
4861 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00004862 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004863
Douglas Gregor50dc2192010-02-11 22:55:30 +00004864 if (!VDecl->getType()->isDependentType() &&
4865 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00004866 diag::err_typecheck_decl_incomplete_type)) {
4867 VDecl->setInvalidDecl();
4868 return;
4869 }
4870
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004871 // The variable can not have an abstract class type.
4872 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4873 diag::err_abstract_type_in_decl,
4874 AbstractVariableType))
4875 VDecl->setInvalidDecl();
4876
Sebastian Redl5ca79842010-02-01 20:16:42 +00004877 const VarDecl *Def;
4878 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004879 Diag(VDecl->getLocation(), diag::err_redefinition)
4880 << VDecl->getDeclName();
4881 Diag(Def->getLocation(), diag::note_previous_definition);
4882 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004883 return;
4884 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00004885
4886 // If either the declaration has a dependent type or if any of the
4887 // expressions is type-dependent, we represent the initialization
4888 // via a ParenListExpr for later use during template instantiation.
4889 if (VDecl->getType()->isDependentType() ||
4890 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4891 // Let clients know that initialization was done with a direct initializer.
4892 VDecl->setCXXDirectInitializer(true);
4893
4894 // Store the initialization expressions as a ParenListExpr.
4895 unsigned NumExprs = Exprs.size();
4896 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4897 (Expr **)Exprs.release(),
4898 NumExprs, RParenLoc));
4899 return;
4900 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004901
4902 // Capture the variable that is being initialized and the style of
4903 // initialization.
4904 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4905
4906 // FIXME: Poor source location information.
4907 InitializationKind Kind
4908 = InitializationKind::CreateDirect(VDecl->getLocation(),
4909 LParenLoc, RParenLoc);
4910
4911 InitializationSequence InitSeq(*this, Entity, Kind,
4912 (Expr**)Exprs.get(), Exprs.size());
4913 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4914 if (Result.isInvalid()) {
4915 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004916 return;
4917 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004918
4919 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregord5058122010-02-11 01:19:42 +00004920 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004921 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004922
John McCall03c48482010-02-02 09:10:11 +00004923 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4924 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004925}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004926
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004927/// \brief Given a constructor and the set of arguments provided for the
4928/// constructor, convert the arguments and add any required default arguments
4929/// to form a proper call to this constructor.
4930///
4931/// \returns true if an error occurred, false otherwise.
4932bool
4933Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4934 MultiExprArg ArgsPtr,
4935 SourceLocation Loc,
4936 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4937 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4938 unsigned NumArgs = ArgsPtr.size();
4939 Expr **Args = (Expr **)ArgsPtr.get();
4940
4941 const FunctionProtoType *Proto
4942 = Constructor->getType()->getAs<FunctionProtoType>();
4943 assert(Proto && "Constructor without a prototype?");
4944 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004945
4946 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004947 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004948 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004949 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004950 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004951
4952 VariadicCallType CallType =
4953 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4954 llvm::SmallVector<Expr *, 8> AllArgs;
4955 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4956 Proto, 0, Args, NumArgs, AllArgs,
4957 CallType);
4958 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4959 ConvertedArgs.push_back(AllArgs[i]);
4960 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004961}
4962
Anders Carlssone363c8e2009-12-12 00:32:00 +00004963static inline bool
4964CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4965 const FunctionDecl *FnDecl) {
4966 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4967 if (isa<NamespaceDecl>(DC)) {
4968 return SemaRef.Diag(FnDecl->getLocation(),
4969 diag::err_operator_new_delete_declared_in_namespace)
4970 << FnDecl->getDeclName();
4971 }
4972
4973 if (isa<TranslationUnitDecl>(DC) &&
4974 FnDecl->getStorageClass() == FunctionDecl::Static) {
4975 return SemaRef.Diag(FnDecl->getLocation(),
4976 diag::err_operator_new_delete_declared_static)
4977 << FnDecl->getDeclName();
4978 }
4979
Anders Carlsson60659a82009-12-12 02:43:16 +00004980 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00004981}
4982
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004983static inline bool
4984CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4985 CanQualType ExpectedResultType,
4986 CanQualType ExpectedFirstParamType,
4987 unsigned DependentParamTypeDiag,
4988 unsigned InvalidParamTypeDiag) {
4989 QualType ResultType =
4990 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4991
4992 // Check that the result type is not dependent.
4993 if (ResultType->isDependentType())
4994 return SemaRef.Diag(FnDecl->getLocation(),
4995 diag::err_operator_new_delete_dependent_result_type)
4996 << FnDecl->getDeclName() << ExpectedResultType;
4997
4998 // Check that the result type is what we expect.
4999 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5000 return SemaRef.Diag(FnDecl->getLocation(),
5001 diag::err_operator_new_delete_invalid_result_type)
5002 << FnDecl->getDeclName() << ExpectedResultType;
5003
5004 // A function template must have at least 2 parameters.
5005 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5006 return SemaRef.Diag(FnDecl->getLocation(),
5007 diag::err_operator_new_delete_template_too_few_parameters)
5008 << FnDecl->getDeclName();
5009
5010 // The function decl must have at least 1 parameter.
5011 if (FnDecl->getNumParams() == 0)
5012 return SemaRef.Diag(FnDecl->getLocation(),
5013 diag::err_operator_new_delete_too_few_parameters)
5014 << FnDecl->getDeclName();
5015
5016 // Check the the first parameter type is not dependent.
5017 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5018 if (FirstParamType->isDependentType())
5019 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5020 << FnDecl->getDeclName() << ExpectedFirstParamType;
5021
5022 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005023 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005024 ExpectedFirstParamType)
5025 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5026 << FnDecl->getDeclName() << ExpectedFirstParamType;
5027
5028 return false;
5029}
5030
Anders Carlsson12308f42009-12-11 23:23:22 +00005031static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005032CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005033 // C++ [basic.stc.dynamic.allocation]p1:
5034 // A program is ill-formed if an allocation function is declared in a
5035 // namespace scope other than global scope or declared static in global
5036 // scope.
5037 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5038 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005039
5040 CanQualType SizeTy =
5041 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5042
5043 // C++ [basic.stc.dynamic.allocation]p1:
5044 // The return type shall be void*. The first parameter shall have type
5045 // std::size_t.
5046 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5047 SizeTy,
5048 diag::err_operator_new_dependent_param_type,
5049 diag::err_operator_new_param_type))
5050 return true;
5051
5052 // C++ [basic.stc.dynamic.allocation]p1:
5053 // The first parameter shall not have an associated default argument.
5054 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005055 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005056 diag::err_operator_new_default_arg)
5057 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5058
5059 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005060}
5061
5062static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005063CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5064 // C++ [basic.stc.dynamic.deallocation]p1:
5065 // A program is ill-formed if deallocation functions are declared in a
5066 // namespace scope other than global scope or declared static in global
5067 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005068 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5069 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005070
5071 // C++ [basic.stc.dynamic.deallocation]p2:
5072 // Each deallocation function shall return void and its first parameter
5073 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005074 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5075 SemaRef.Context.VoidPtrTy,
5076 diag::err_operator_delete_dependent_param_type,
5077 diag::err_operator_delete_param_type))
5078 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005079
Anders Carlssonc0b2ce12009-12-12 00:16:02 +00005080 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5081 if (FirstParamType->isDependentType())
5082 return SemaRef.Diag(FnDecl->getLocation(),
5083 diag::err_operator_delete_dependent_param_type)
5084 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
5085
5086 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
5087 SemaRef.Context.VoidPtrTy)
Anders Carlsson12308f42009-12-11 23:23:22 +00005088 return SemaRef.Diag(FnDecl->getLocation(),
5089 diag::err_operator_delete_param_type)
5090 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson12308f42009-12-11 23:23:22 +00005091
5092 return false;
5093}
5094
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005095/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5096/// of this overloaded operator is well-formed. If so, returns false;
5097/// otherwise, emits appropriate diagnostics and returns true.
5098bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005099 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005100 "Expected an overloaded operator declaration");
5101
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005102 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5103
Mike Stump11289f42009-09-09 15:08:12 +00005104 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005105 // The allocation and deallocation functions, operator new,
5106 // operator new[], operator delete and operator delete[], are
5107 // described completely in 3.7.3. The attributes and restrictions
5108 // found in the rest of this subclause do not apply to them unless
5109 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005110 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005111 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005112
Anders Carlsson22f443f2009-12-12 00:26:23 +00005113 if (Op == OO_New || Op == OO_Array_New)
5114 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005115
5116 // C++ [over.oper]p6:
5117 // An operator function shall either be a non-static member
5118 // function or be a non-member function and have at least one
5119 // parameter whose type is a class, a reference to a class, an
5120 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005121 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5122 if (MethodDecl->isStatic())
5123 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005124 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005125 } else {
5126 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005127 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5128 ParamEnd = FnDecl->param_end();
5129 Param != ParamEnd; ++Param) {
5130 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005131 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5132 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005133 ClassOrEnumParam = true;
5134 break;
5135 }
5136 }
5137
Douglas Gregord69246b2008-11-17 16:14:12 +00005138 if (!ClassOrEnumParam)
5139 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005140 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005141 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005142 }
5143
5144 // C++ [over.oper]p8:
5145 // An operator function cannot have default arguments (8.3.6),
5146 // except where explicitly stated below.
5147 //
Mike Stump11289f42009-09-09 15:08:12 +00005148 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005149 // (C++ [over.call]p1).
5150 if (Op != OO_Call) {
5151 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5152 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005153 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005154 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005155 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005156 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005157 }
5158 }
5159
Douglas Gregor6cf08062008-11-10 13:38:07 +00005160 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5161 { false, false, false }
5162#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5163 , { Unary, Binary, MemberOnly }
5164#include "clang/Basic/OperatorKinds.def"
5165 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005166
Douglas Gregor6cf08062008-11-10 13:38:07 +00005167 bool CanBeUnaryOperator = OperatorUses[Op][0];
5168 bool CanBeBinaryOperator = OperatorUses[Op][1];
5169 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005170
5171 // C++ [over.oper]p8:
5172 // [...] Operator functions cannot have more or fewer parameters
5173 // than the number required for the corresponding operator, as
5174 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005175 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005176 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005177 if (Op != OO_Call &&
5178 ((NumParams == 1 && !CanBeUnaryOperator) ||
5179 (NumParams == 2 && !CanBeBinaryOperator) ||
5180 (NumParams < 1) || (NumParams > 2))) {
5181 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005182 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005183 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005184 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005185 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005186 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005187 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005188 assert(CanBeBinaryOperator &&
5189 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005190 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005191 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005192
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005193 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005194 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005195 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005196
Douglas Gregord69246b2008-11-17 16:14:12 +00005197 // Overloaded operators other than operator() cannot be variadic.
5198 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005199 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005200 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005201 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005202 }
5203
5204 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005205 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5206 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005207 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005208 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005209 }
5210
5211 // C++ [over.inc]p1:
5212 // The user-defined function called operator++ implements the
5213 // prefix and postfix ++ operator. If this function is a member
5214 // function with no parameters, or a non-member function with one
5215 // parameter of class or enumeration type, it defines the prefix
5216 // increment operator ++ for objects of that type. If the function
5217 // is a member function with one parameter (which shall be of type
5218 // int) or a non-member function with two parameters (the second
5219 // of which shall be of type int), it defines the postfix
5220 // increment operator ++ for objects of that type.
5221 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5222 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5223 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005224 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005225 ParamIsInt = BT->getKind() == BuiltinType::Int;
5226
Chris Lattner2b786902008-11-21 07:50:02 +00005227 if (!ParamIsInt)
5228 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005229 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005230 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005231 }
5232
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005233 // Notify the class if it got an assignment operator.
5234 if (Op == OO_Equal) {
5235 // Would have returned earlier otherwise.
5236 assert(isa<CXXMethodDecl>(FnDecl) &&
5237 "Overloaded = not member, but not filtered.");
5238 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5239 Method->getParent()->addedAssignmentOperator(Context, Method);
5240 }
5241
Douglas Gregord69246b2008-11-17 16:14:12 +00005242 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005243}
Chris Lattner3b024a32008-12-17 07:09:26 +00005244
Alexis Huntc88db062010-01-13 09:01:02 +00005245/// CheckLiteralOperatorDeclaration - Check whether the declaration
5246/// of this literal operator function is well-formed. If so, returns
5247/// false; otherwise, emits appropriate diagnostics and returns true.
5248bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5249 DeclContext *DC = FnDecl->getDeclContext();
5250 Decl::Kind Kind = DC->getDeclKind();
5251 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5252 Kind != Decl::LinkageSpec) {
5253 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5254 << FnDecl->getDeclName();
5255 return true;
5256 }
5257
5258 bool Valid = false;
5259
Alexis Hunt7dd26172010-04-07 23:11:06 +00005260 // template <char...> type operator "" name() is the only valid template
5261 // signature, and the only valid signature with no parameters.
5262 if (FnDecl->param_size() == 0) {
5263 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5264 // Must have only one template parameter
5265 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5266 if (Params->size() == 1) {
5267 NonTypeTemplateParmDecl *PmDecl =
5268 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005269
Alexis Hunt7dd26172010-04-07 23:11:06 +00005270 // The template parameter must be a char parameter pack.
5271 // FIXME: This test will always fail because non-type parameter packs
5272 // have not been implemented.
5273 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5274 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5275 Valid = true;
5276 }
5277 }
5278 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005279 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005280 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5281
Alexis Huntc88db062010-01-13 09:01:02 +00005282 QualType T = (*Param)->getType();
5283
Alexis Hunt079a6f72010-04-07 22:57:35 +00005284 // unsigned long long int, long double, and any character type are allowed
5285 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005286 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5287 Context.hasSameType(T, Context.LongDoubleTy) ||
5288 Context.hasSameType(T, Context.CharTy) ||
5289 Context.hasSameType(T, Context.WCharTy) ||
5290 Context.hasSameType(T, Context.Char16Ty) ||
5291 Context.hasSameType(T, Context.Char32Ty)) {
5292 if (++Param == FnDecl->param_end())
5293 Valid = true;
5294 goto FinishedParams;
5295 }
5296
Alexis Hunt079a6f72010-04-07 22:57:35 +00005297 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005298 const PointerType *PT = T->getAs<PointerType>();
5299 if (!PT)
5300 goto FinishedParams;
5301 T = PT->getPointeeType();
5302 if (!T.isConstQualified())
5303 goto FinishedParams;
5304 T = T.getUnqualifiedType();
5305
5306 // Move on to the second parameter;
5307 ++Param;
5308
5309 // If there is no second parameter, the first must be a const char *
5310 if (Param == FnDecl->param_end()) {
5311 if (Context.hasSameType(T, Context.CharTy))
5312 Valid = true;
5313 goto FinishedParams;
5314 }
5315
5316 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5317 // are allowed as the first parameter to a two-parameter function
5318 if (!(Context.hasSameType(T, Context.CharTy) ||
5319 Context.hasSameType(T, Context.WCharTy) ||
5320 Context.hasSameType(T, Context.Char16Ty) ||
5321 Context.hasSameType(T, Context.Char32Ty)))
5322 goto FinishedParams;
5323
5324 // The second and final parameter must be an std::size_t
5325 T = (*Param)->getType().getUnqualifiedType();
5326 if (Context.hasSameType(T, Context.getSizeType()) &&
5327 ++Param == FnDecl->param_end())
5328 Valid = true;
5329 }
5330
5331 // FIXME: This diagnostic is absolutely terrible.
5332FinishedParams:
5333 if (!Valid) {
5334 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5335 << FnDecl->getDeclName();
5336 return true;
5337 }
5338
5339 return false;
5340}
5341
Douglas Gregor07665a62009-01-05 19:45:36 +00005342/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5343/// linkage specification, including the language and (if present)
5344/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5345/// the location of the language string literal, which is provided
5346/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5347/// the '{' brace. Otherwise, this linkage specification does not
5348/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005349Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5350 SourceLocation ExternLoc,
5351 SourceLocation LangLoc,
Benjamin Kramerbebee842010-05-03 13:08:54 +00005352 llvm::StringRef Lang,
Chris Lattner83f095c2009-03-28 19:18:32 +00005353 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005354 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005355 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005356 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005357 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005358 Language = LinkageSpecDecl::lang_cxx;
5359 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005360 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00005361 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00005362 }
Mike Stump11289f42009-09-09 15:08:12 +00005363
Chris Lattner438e5012008-12-17 07:13:27 +00005364 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005365
Douglas Gregor07665a62009-01-05 19:45:36 +00005366 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005367 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005368 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005369 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005370 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005371 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00005372}
5373
Douglas Gregor07665a62009-01-05 19:45:36 +00005374/// ActOnFinishLinkageSpecification - Completely the definition of
5375/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5376/// valid, it's the position of the closing '}' brace in a linkage
5377/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005378Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5379 DeclPtrTy LinkageSpec,
5380 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005381 if (LinkageSpec)
5382 PopDeclContext();
5383 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005384}
5385
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005386/// \brief Perform semantic analysis for the variable declaration that
5387/// occurs within a C++ catch clause, returning the newly-created
5388/// variable.
5389VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00005390 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005391 IdentifierInfo *Name,
5392 SourceLocation Loc,
5393 SourceRange Range) {
5394 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005395
5396 // Arrays and functions decay.
5397 if (ExDeclType->isArrayType())
5398 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5399 else if (ExDeclType->isFunctionType())
5400 ExDeclType = Context.getPointerType(ExDeclType);
5401
5402 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5403 // The exception-declaration shall not denote a pointer or reference to an
5404 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005405 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005406 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005407 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00005408 Invalid = true;
5409 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005410
Douglas Gregor104ee002010-03-08 01:47:36 +00005411 // GCC allows catching pointers and references to incomplete types
5412 // as an extension; so do we, but we warn by default.
5413
Sebastian Redl54c04d42008-12-22 19:15:10 +00005414 QualType BaseType = ExDeclType;
5415 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005416 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00005417 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005418 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005419 BaseType = Ptr->getPointeeType();
5420 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00005421 DK = diag::ext_catch_incomplete_ptr;
5422 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00005423 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005424 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005425 BaseType = Ref->getPointeeType();
5426 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00005427 DK = diag::ext_catch_incomplete_ref;
5428 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005429 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005430 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00005431 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5432 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00005433 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005434
Mike Stump11289f42009-09-09 15:08:12 +00005435 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005436 RequireNonAbstractType(Loc, ExDeclType,
5437 diag::err_abstract_type_in_decl,
5438 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005439 Invalid = true;
5440
Mike Stump11289f42009-09-09 15:08:12 +00005441 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005442 Name, ExDeclType, TInfo, VarDecl::None,
5443 VarDecl::None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00005444 ExDecl->setExceptionVariable(true);
5445
Douglas Gregor6de584c2010-03-05 23:38:39 +00005446 if (!Invalid) {
5447 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5448 // C++ [except.handle]p16:
5449 // The object declared in an exception-declaration or, if the
5450 // exception-declaration does not specify a name, a temporary (12.2) is
5451 // copy-initialized (8.5) from the exception object. [...]
5452 // The object is destroyed when the handler exits, after the destruction
5453 // of any automatic objects initialized within the handler.
5454 //
5455 // We just pretend to initialize the object with itself, then make sure
5456 // it can be destroyed later.
5457 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5458 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5459 Loc, ExDeclType, 0);
5460 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5461 SourceLocation());
5462 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5463 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5464 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5465 if (Result.isInvalid())
5466 Invalid = true;
5467 else
5468 FinalizeVarWithDestructor(ExDecl, RecordTy);
5469 }
5470 }
5471
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005472 if (Invalid)
5473 ExDecl->setInvalidDecl();
5474
5475 return ExDecl;
5476}
5477
5478/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5479/// handler.
5480Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00005481 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5482 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005483
5484 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00005485 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005486 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00005487 LookupOrdinaryName,
5488 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005489 // The scope should be freshly made just for us. There is just no way
5490 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00005491 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00005492 if (PrevDecl->isTemplateParameter()) {
5493 // Maybe we will complain about the shadowed template parameter.
5494 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005495 }
5496 }
5497
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005498 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005499 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5500 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005501 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005502 }
5503
John McCallbcd03502009-12-07 02:54:59 +00005504 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005505 D.getIdentifier(),
5506 D.getIdentifierLoc(),
5507 D.getDeclSpec().getSourceRange());
5508
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005509 if (Invalid)
5510 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00005511
Sebastian Redl54c04d42008-12-22 19:15:10 +00005512 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005513 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005514 PushOnScopeChains(ExDecl, S);
5515 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005516 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005517
Douglas Gregor758a8692009-06-17 21:51:59 +00005518 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005519 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005520}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005521
Mike Stump11289f42009-09-09 15:08:12 +00005522Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005523 ExprArg assertexpr,
5524 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005525 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00005526 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005527 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5528
Anders Carlsson54b26982009-03-14 00:33:21 +00005529 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5530 llvm::APSInt Value(32);
5531 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5532 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5533 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00005534 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00005535 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005536
Anders Carlsson54b26982009-03-14 00:33:21 +00005537 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00005538 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00005539 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00005540 }
5541 }
Mike Stump11289f42009-09-09 15:08:12 +00005542
Anders Carlsson78e2bc02009-03-15 17:35:16 +00005543 assertexpr.release();
5544 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00005545 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005546 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00005547
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005548 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00005549 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005550}
Sebastian Redlf769df52009-03-24 22:27:57 +00005551
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005552/// \brief Perform semantic analysis of the given friend type declaration.
5553///
5554/// \returns A friend declaration that.
5555FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5556 TypeSourceInfo *TSInfo) {
5557 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5558
5559 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005560 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005561
Douglas Gregor3b4abb62010-04-07 17:57:12 +00005562 if (!getLangOptions().CPlusPlus0x) {
5563 // C++03 [class.friend]p2:
5564 // An elaborated-type-specifier shall be used in a friend declaration
5565 // for a class.*
5566 //
5567 // * The class-key of the elaborated-type-specifier is required.
5568 if (!ActiveTemplateInstantiations.empty()) {
5569 // Do not complain about the form of friend template types during
5570 // template instantiation; we will already have complained when the
5571 // template was declared.
5572 } else if (!T->isElaboratedTypeSpecifier()) {
5573 // If we evaluated the type to a record type, suggest putting
5574 // a tag in front.
5575 if (const RecordType *RT = T->getAs<RecordType>()) {
5576 RecordDecl *RD = RT->getDecl();
5577
5578 std::string InsertionText = std::string(" ") + RD->getKindName();
5579
5580 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5581 << (unsigned) RD->getTagKind()
5582 << T
5583 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5584 InsertionText);
5585 } else {
5586 Diag(FriendLoc, diag::ext_nonclass_type_friend)
5587 << T
5588 << SourceRange(FriendLoc, TypeRange.getEnd());
5589 }
5590 } else if (T->getAs<EnumType>()) {
5591 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005592 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005593 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005594 }
5595 }
5596
Douglas Gregor3b4abb62010-04-07 17:57:12 +00005597 // C++0x [class.friend]p3:
5598 // If the type specifier in a friend declaration designates a (possibly
5599 // cv-qualified) class type, that class is declared as a friend; otherwise,
5600 // the friend declaration is ignored.
5601
5602 // FIXME: C++0x has some syntactic restrictions on friend type declarations
5603 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005604
5605 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5606}
5607
John McCall11083da2009-09-16 22:47:08 +00005608/// Handle a friend type declaration. This works in tandem with
5609/// ActOnTag.
5610///
5611/// Notes on friend class templates:
5612///
5613/// We generally treat friend class declarations as if they were
5614/// declaring a class. So, for example, the elaborated type specifier
5615/// in a friend declaration is required to obey the restrictions of a
5616/// class-head (i.e. no typedefs in the scope chain), template
5617/// parameters are required to match up with simple template-ids, &c.
5618/// However, unlike when declaring a template specialization, it's
5619/// okay to refer to a template specialization without an empty
5620/// template parameter declaration, e.g.
5621/// friend class A<T>::B<unsigned>;
5622/// We permit this as a special case; if there are any template
5623/// parameters present at all, require proper matching, i.e.
5624/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00005625Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00005626 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005627 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00005628
5629 assert(DS.isFriendSpecified());
5630 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5631
John McCall11083da2009-09-16 22:47:08 +00005632 // Try to convert the decl specifier to a type. This works for
5633 // friend templates because ActOnTag never produces a ClassTemplateDecl
5634 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00005635 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00005636 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
5637 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00005638 if (TheDeclarator.isInvalidType())
5639 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005640
John McCall11083da2009-09-16 22:47:08 +00005641 // This is definitely an error in C++98. It's probably meant to
5642 // be forbidden in C++0x, too, but the specification is just
5643 // poorly written.
5644 //
5645 // The problem is with declarations like the following:
5646 // template <T> friend A<T>::foo;
5647 // where deciding whether a class C is a friend or not now hinges
5648 // on whether there exists an instantiation of A that causes
5649 // 'foo' to equal C. There are restrictions on class-heads
5650 // (which we declare (by fiat) elaborated friend declarations to
5651 // be) that makes this tractable.
5652 //
5653 // FIXME: handle "template <> friend class A<T>;", which
5654 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00005655 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00005656 Diag(Loc, diag::err_tagless_friend_type_template)
5657 << DS.getSourceRange();
5658 return DeclPtrTy();
5659 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005660
John McCallaa74a0c2009-08-28 07:59:38 +00005661 // C++98 [class.friend]p1: A friend of a class is a function
5662 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00005663 // This is fixed in DR77, which just barely didn't make the C++03
5664 // deadline. It's also a very silly restriction that seriously
5665 // affects inner classes and which nobody else seems to implement;
5666 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00005667 //
5668 // But note that we could warn about it: it's always useless to
5669 // friend one of your own members (it's not, however, worthless to
5670 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00005671
John McCall11083da2009-09-16 22:47:08 +00005672 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005673 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00005674 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005675 NumTempParamLists,
John McCall11083da2009-09-16 22:47:08 +00005676 (TemplateParameterList**) TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00005677 TSI,
John McCall11083da2009-09-16 22:47:08 +00005678 DS.getFriendSpecLoc());
5679 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005680 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5681
5682 if (!D)
5683 return DeclPtrTy();
5684
John McCall11083da2009-09-16 22:47:08 +00005685 D->setAccess(AS_public);
5686 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005687
John McCall11083da2009-09-16 22:47:08 +00005688 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005689}
5690
John McCall2f212b32009-09-11 21:02:39 +00005691Sema::DeclPtrTy
5692Sema::ActOnFriendFunctionDecl(Scope *S,
5693 Declarator &D,
5694 bool IsDefinition,
5695 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005696 const DeclSpec &DS = D.getDeclSpec();
5697
5698 assert(DS.isFriendSpecified());
5699 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5700
5701 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00005702 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5703 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00005704
5705 // C++ [class.friend]p1
5706 // A friend of a class is a function or class....
5707 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00005708 // It *doesn't* see through dependent types, which is correct
5709 // according to [temp.arg.type]p3:
5710 // If a declaration acquires a function type through a
5711 // type dependent on a template-parameter and this causes
5712 // a declaration that does not use the syntactic form of a
5713 // function declarator to have a function type, the program
5714 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00005715 if (!T->isFunctionType()) {
5716 Diag(Loc, diag::err_unexpected_friend);
5717
5718 // It might be worthwhile to try to recover by creating an
5719 // appropriate declaration.
5720 return DeclPtrTy();
5721 }
5722
5723 // C++ [namespace.memdef]p3
5724 // - If a friend declaration in a non-local class first declares a
5725 // class or function, the friend class or function is a member
5726 // of the innermost enclosing namespace.
5727 // - The name of the friend is not found by simple name lookup
5728 // until a matching declaration is provided in that namespace
5729 // scope (either before or after the class declaration granting
5730 // friendship).
5731 // - If a friend function is called, its name may be found by the
5732 // name lookup that considers functions from namespaces and
5733 // classes associated with the types of the function arguments.
5734 // - When looking for a prior declaration of a class or a function
5735 // declared as a friend, scopes outside the innermost enclosing
5736 // namespace scope are not considered.
5737
John McCallaa74a0c2009-08-28 07:59:38 +00005738 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5739 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00005740 assert(Name);
5741
John McCall07e91c02009-08-06 02:15:43 +00005742 // The context we found the declaration in, or in which we should
5743 // create the declaration.
5744 DeclContext *DC;
5745
5746 // FIXME: handle local classes
5747
5748 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00005749 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5750 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00005751 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5752 DC = computeDeclContext(ScopeQual);
5753
5754 // FIXME: handle dependent contexts
5755 if (!DC) return DeclPtrTy();
John McCall0b66eb32010-05-01 00:40:08 +00005756 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005757
John McCall1f82f242009-11-18 22:49:29 +00005758 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005759
John McCall45831862010-05-28 01:41:47 +00005760 // Ignore things found implicitly in the wrong scope.
John McCall07e91c02009-08-06 02:15:43 +00005761 // TODO: better diagnostics for this case. Suggesting the right
5762 // qualified scope would be nice...
John McCall45831862010-05-28 01:41:47 +00005763 LookupResult::Filter F = Previous.makeFilter();
5764 while (F.hasNext()) {
5765 NamedDecl *D = F.next();
5766 if (!D->getDeclContext()->getLookupContext()->Equals(DC))
5767 F.erase();
5768 }
5769 F.done();
5770
5771 if (Previous.empty()) {
John McCallaa74a0c2009-08-28 07:59:38 +00005772 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00005773 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5774 return DeclPtrTy();
5775 }
5776
5777 // C++ [class.friend]p1: A friend of a class is a function or
5778 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005779 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00005780 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5781
John McCall07e91c02009-08-06 02:15:43 +00005782 // Otherwise walk out to the nearest namespace scope looking for matches.
5783 } else {
5784 // TODO: handle local class contexts.
5785
5786 DC = CurContext;
5787 while (true) {
5788 // Skip class contexts. If someone can cite chapter and verse
5789 // for this behavior, that would be nice --- it's what GCC and
5790 // EDG do, and it seems like a reasonable intent, but the spec
5791 // really only says that checks for unqualified existing
5792 // declarations should stop at the nearest enclosing namespace,
5793 // not that they should only consider the nearest enclosing
5794 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005795 while (DC->isRecord())
5796 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00005797
John McCall1f82f242009-11-18 22:49:29 +00005798 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005799
5800 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00005801 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00005802 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005803
John McCall07e91c02009-08-06 02:15:43 +00005804 if (DC->isFileContext()) break;
5805 DC = DC->getParent();
5806 }
5807
5808 // C++ [class.friend]p1: A friend of a class is a function or
5809 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00005810 // C++0x changes this for both friend types and functions.
5811 // Most C++ 98 compilers do seem to give an error here, so
5812 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00005813 if (!Previous.empty() && DC->Equals(CurContext)
5814 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00005815 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5816 }
5817
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005818 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00005819 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00005820 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5821 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5822 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00005823 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00005824 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5825 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00005826 return DeclPtrTy();
5827 }
John McCall07e91c02009-08-06 02:15:43 +00005828 }
5829
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005830 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00005831 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005832 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00005833 IsDefinition,
5834 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00005835 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00005836
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005837 assert(ND->getDeclContext() == DC);
5838 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00005839
John McCall759e32b2009-08-31 22:39:49 +00005840 // Add the function declaration to the appropriate lookup tables,
5841 // adjusting the redeclarations list as necessary. We don't
5842 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00005843 //
John McCall759e32b2009-08-31 22:39:49 +00005844 // Also update the scope-based lookup if the target context's
5845 // lookup context is in lexical scope.
5846 if (!CurContext->isDependentContext()) {
5847 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005848 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005849 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005850 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005851 }
John McCallaa74a0c2009-08-28 07:59:38 +00005852
5853 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005854 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00005855 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00005856 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00005857 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00005858
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005859 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00005860}
5861
Chris Lattner83f095c2009-03-28 19:18:32 +00005862void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005863 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005864
Chris Lattner83f095c2009-03-28 19:18:32 +00005865 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00005866 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5867 if (!Fn) {
5868 Diag(DelLoc, diag::err_deleted_non_function);
5869 return;
5870 }
5871 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5872 Diag(DelLoc, diag::err_deleted_decl_not_first);
5873 Diag(Prev->getLocation(), diag::note_previous_declaration);
5874 // If the declaration wasn't the first, we delete the function anyway for
5875 // recovery.
5876 }
5877 Fn->setDeleted();
5878}
Sebastian Redl4c018662009-04-27 21:33:24 +00005879
5880static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5881 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5882 ++CI) {
5883 Stmt *SubStmt = *CI;
5884 if (!SubStmt)
5885 continue;
5886 if (isa<ReturnStmt>(SubStmt))
5887 Self.Diag(SubStmt->getSourceRange().getBegin(),
5888 diag::err_return_in_constructor_handler);
5889 if (!isa<Expr>(SubStmt))
5890 SearchForReturnInStmt(Self, SubStmt);
5891 }
5892}
5893
5894void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5895 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5896 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5897 SearchForReturnInStmt(*this, Handler);
5898 }
5899}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005900
Mike Stump11289f42009-09-09 15:08:12 +00005901bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005902 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00005903 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5904 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005905
Chandler Carruth284bb2e2010-02-15 11:53:20 +00005906 if (Context.hasSameType(NewTy, OldTy) ||
5907 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005908 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005909
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005910 // Check if the return types are covariant
5911 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00005912
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005913 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005914 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5915 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005916 NewClassTy = NewPT->getPointeeType();
5917 OldClassTy = OldPT->getPointeeType();
5918 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005919 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5920 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5921 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5922 NewClassTy = NewRT->getPointeeType();
5923 OldClassTy = OldRT->getPointeeType();
5924 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005925 }
5926 }
Mike Stump11289f42009-09-09 15:08:12 +00005927
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005928 // The return types aren't either both pointers or references to a class type.
5929 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00005930 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005931 diag::err_different_return_type_for_overriding_virtual_function)
5932 << New->getDeclName() << NewTy << OldTy;
5933 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00005934
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005935 return true;
5936 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005937
Anders Carlssone60365b2009-12-31 18:34:24 +00005938 // C++ [class.virtual]p6:
5939 // If the return type of D::f differs from the return type of B::f, the
5940 // class type in the return type of D::f shall be complete at the point of
5941 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005942 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5943 if (!RT->isBeingDefined() &&
5944 RequireCompleteType(New->getLocation(), NewClassTy,
5945 PDiag(diag::err_covariant_return_incomplete)
5946 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00005947 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005948 }
Anders Carlssone60365b2009-12-31 18:34:24 +00005949
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005950 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005951 // Check if the new class derives from the old class.
5952 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5953 Diag(New->getLocation(),
5954 diag::err_covariant_return_not_derived)
5955 << New->getDeclName() << NewTy << OldTy;
5956 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5957 return true;
5958 }
Mike Stump11289f42009-09-09 15:08:12 +00005959
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005960 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00005961 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00005962 diag::err_covariant_return_inaccessible_base,
5963 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5964 // FIXME: Should this point to the return type?
5965 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005966 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5967 return true;
5968 }
5969 }
Mike Stump11289f42009-09-09 15:08:12 +00005970
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005971 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005972 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005973 Diag(New->getLocation(),
5974 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005975 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005976 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5977 return true;
5978 };
Mike Stump11289f42009-09-09 15:08:12 +00005979
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005980
5981 // The new class type must have the same or less qualifiers as the old type.
5982 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5983 Diag(New->getLocation(),
5984 diag::err_covariant_return_type_class_type_more_qualified)
5985 << New->getDeclName() << NewTy << OldTy;
5986 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5987 return true;
5988 };
Mike Stump11289f42009-09-09 15:08:12 +00005989
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005990 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005991}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005992
Alexis Hunt96d5c762009-11-21 08:43:09 +00005993bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5994 const CXXMethodDecl *Old)
5995{
5996 if (Old->hasAttr<FinalAttr>()) {
5997 Diag(New->getLocation(), diag::err_final_function_overridden)
5998 << New->getDeclName();
5999 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6000 return true;
6001 }
6002
6003 return false;
6004}
6005
Douglas Gregor21920e372009-12-01 17:24:26 +00006006/// \brief Mark the given method pure.
6007///
6008/// \param Method the method to be marked pure.
6009///
6010/// \param InitRange the source range that covers the "0" initializer.
6011bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6012 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6013 Method->setPure();
6014
6015 // A class is abstract if at least one function is pure virtual.
6016 Method->getParent()->setAbstract(true);
6017 return false;
6018 }
6019
6020 if (!Method->isInvalidDecl())
6021 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6022 << Method->getDeclName() << InitRange;
6023 return true;
6024}
6025
John McCall1f4ee7b2009-12-19 09:28:58 +00006026/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6027/// an initializer for the out-of-line declaration 'Dcl'. The scope
6028/// is a fresh scope pushed for just this purpose.
6029///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006030/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6031/// static data member of class X, names should be looked up in the scope of
6032/// class X.
6033void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006034 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006035 Decl *D = Dcl.getAs<Decl>();
6036 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006037
John McCall1f4ee7b2009-12-19 09:28:58 +00006038 // We should only get called for declarations with scope specifiers, like:
6039 // int foo::bar;
6040 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006041 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006042}
6043
6044/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall1f4ee7b2009-12-19 09:28:58 +00006045/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006046void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006047 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006048 Decl *D = Dcl.getAs<Decl>();
6049 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006050
John McCall1f4ee7b2009-12-19 09:28:58 +00006051 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006052 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006053}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006054
6055/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6056/// C++ if/switch/while/for statement.
6057/// e.g: "if (int x = f()) {...}"
6058Action::DeclResult
6059Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
6060 // C++ 6.4p2:
6061 // The declarator shall not specify a function or an array.
6062 // The type-specifier-seq shall not contain typedef and shall not declare a
6063 // new class or enumeration.
6064 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6065 "Parser allowed 'typedef' as storage class of condition decl.");
6066
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006067 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006068 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6069 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006070
6071 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6072 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6073 // would be created and CXXConditionDeclExpr wants a VarDecl.
6074 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6075 << D.getSourceRange();
6076 return DeclResult();
6077 } else if (OwnedTag && OwnedTag->isDefinition()) {
6078 // The type-specifier-seq shall not declare a new class or enumeration.
6079 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6080 }
6081
6082 DeclPtrTy Dcl = ActOnDeclarator(S, D);
6083 if (!Dcl)
6084 return DeclResult();
6085
6086 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
6087 VD->setDeclaredInCondition(true);
6088 return Dcl;
6089}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006090
Douglas Gregor88d292c2010-05-13 16:44:06 +00006091void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6092 bool DefinitionRequired) {
6093 // Ignore any vtable uses in unevaluated operands or for classes that do
6094 // not have a vtable.
6095 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6096 CurContext->isDependentContext() ||
6097 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006098 return;
6099
Douglas Gregor88d292c2010-05-13 16:44:06 +00006100 // Try to insert this class into the map.
6101 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6102 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6103 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6104 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006105 // If we already had an entry, check to see if we are promoting this vtable
6106 // to required a definition. If so, we need to reappend to the VTableUses
6107 // list, since we may have already processed the first entry.
6108 if (DefinitionRequired && !Pos.first->second) {
6109 Pos.first->second = true;
6110 } else {
6111 // Otherwise, we can early exit.
6112 return;
6113 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006114 }
6115
6116 // Local classes need to have their virtual members marked
6117 // immediately. For all other classes, we mark their virtual members
6118 // at the end of the translation unit.
6119 if (Class->isLocalClass())
6120 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006121 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006122 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006123}
6124
Douglas Gregor88d292c2010-05-13 16:44:06 +00006125bool Sema::DefineUsedVTables() {
6126 // If any dynamic classes have their key function defined within
6127 // this translation unit, then those vtables are considered "used" and must
6128 // be emitted.
6129 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6130 if (const CXXMethodDecl *KeyFunction
6131 = Context.getKeyFunction(DynamicClasses[I])) {
6132 const FunctionDecl *Definition = 0;
Douglas Gregor83de20f2010-05-14 04:08:48 +00006133 if (KeyFunction->getBody(Definition))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006134 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6135 }
6136 }
6137
6138 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006139 return false;
6140
Douglas Gregor88d292c2010-05-13 16:44:06 +00006141 // Note: The VTableUses vector could grow as a result of marking
6142 // the members of a class as "used", so we check the size each
6143 // time through the loop and prefer indices (with are stable) to
6144 // iterators (which are not).
6145 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00006146 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006147 if (!Class)
6148 continue;
6149
6150 SourceLocation Loc = VTableUses[I].second;
6151
6152 // If this class has a key function, but that key function is
6153 // defined in another translation unit, we don't need to emit the
6154 // vtable even though we're using it.
6155 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
6156 if (KeyFunction && !KeyFunction->getBody()) {
6157 switch (KeyFunction->getTemplateSpecializationKind()) {
6158 case TSK_Undeclared:
6159 case TSK_ExplicitSpecialization:
6160 case TSK_ExplicitInstantiationDeclaration:
6161 // The key function is in another translation unit.
6162 continue;
6163
6164 case TSK_ExplicitInstantiationDefinition:
6165 case TSK_ImplicitInstantiation:
6166 // We will be instantiating the key function.
6167 break;
6168 }
6169 } else if (!KeyFunction) {
6170 // If we have a class with no key function that is the subject
6171 // of an explicit instantiation declaration, suppress the
6172 // vtable; it will live with the explicit instantiation
6173 // definition.
6174 bool IsExplicitInstantiationDeclaration
6175 = Class->getTemplateSpecializationKind()
6176 == TSK_ExplicitInstantiationDeclaration;
6177 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6178 REnd = Class->redecls_end();
6179 R != REnd; ++R) {
6180 TemplateSpecializationKind TSK
6181 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6182 if (TSK == TSK_ExplicitInstantiationDeclaration)
6183 IsExplicitInstantiationDeclaration = true;
6184 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6185 IsExplicitInstantiationDeclaration = false;
6186 break;
6187 }
6188 }
6189
6190 if (IsExplicitInstantiationDeclaration)
6191 continue;
6192 }
6193
6194 // Mark all of the virtual members of this class as referenced, so
6195 // that we can build a vtable. Then, tell the AST consumer that a
6196 // vtable for this class is required.
6197 MarkVirtualMembersReferenced(Loc, Class);
6198 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6199 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6200
6201 // Optionally warn if we're emitting a weak vtable.
6202 if (Class->getLinkage() == ExternalLinkage &&
6203 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
6204 if (!KeyFunction || (KeyFunction->getBody() && KeyFunction->isInlined()))
6205 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6206 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00006207 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006208 VTableUses.clear();
6209
Anders Carlsson82fccd02009-12-07 08:24:59 +00006210 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006211}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006212
Rafael Espindola5b334082010-03-26 00:36:59 +00006213void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6214 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006215 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6216 e = RD->method_end(); i != e; ++i) {
6217 CXXMethodDecl *MD = *i;
6218
6219 // C++ [basic.def.odr]p2:
6220 // [...] A virtual member function is used if it is not pure. [...]
6221 if (MD->isVirtual() && !MD->isPure())
6222 MarkDeclarationReferenced(Loc, MD);
6223 }
Rafael Espindola5b334082010-03-26 00:36:59 +00006224
6225 // Only classes that have virtual bases need a VTT.
6226 if (RD->getNumVBases() == 0)
6227 return;
6228
6229 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6230 e = RD->bases_end(); i != e; ++i) {
6231 const CXXRecordDecl *Base =
6232 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
6233 if (i->isVirtual())
6234 continue;
6235 if (Base->getNumVBases() == 0)
6236 continue;
6237 MarkVirtualMembersReferenced(Loc, Base);
6238 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006239}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006240
6241/// SetIvarInitializers - This routine builds initialization ASTs for the
6242/// Objective-C implementation whose ivars need be initialized.
6243void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6244 if (!getLangOptions().CPlusPlus)
6245 return;
6246 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
6247 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6248 CollectIvarsToConstructOrDestruct(OID, ivars);
6249 if (ivars.empty())
6250 return;
6251 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6252 for (unsigned i = 0; i < ivars.size(); i++) {
6253 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00006254 if (Field->isInvalidDecl())
6255 continue;
6256
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006257 CXXBaseOrMemberInitializer *Member;
6258 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6259 InitializationKind InitKind =
6260 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6261
6262 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6263 Sema::OwningExprResult MemberInit =
6264 InitSeq.Perform(*this, InitEntity, InitKind,
6265 Sema::MultiExprArg(*this, 0, 0));
6266 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6267 // Note, MemberInit could actually come back empty if no initialization
6268 // is required (e.g., because it would call a trivial default constructor)
6269 if (!MemberInit.get() || MemberInit.isInvalid())
6270 continue;
6271
6272 Member =
6273 new (Context) CXXBaseOrMemberInitializer(Context,
6274 Field, SourceLocation(),
6275 SourceLocation(),
6276 MemberInit.takeAs<Expr>(),
6277 SourceLocation());
6278 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00006279
6280 // Be sure that the destructor is accessible and is marked as referenced.
6281 if (const RecordType *RecordTy
6282 = Context.getBaseElementType(Field->getType())
6283 ->getAs<RecordType>()) {
6284 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
6285 if (CXXDestructorDecl *Destructor
6286 = const_cast<CXXDestructorDecl*>(RD->getDestructor(Context))) {
6287 MarkDeclarationReferenced(Field->getLocation(), Destructor);
6288 CheckDestructorAccess(Field->getLocation(), Destructor,
6289 PDiag(diag::err_access_dtor_ivar)
6290 << Context.getBaseElementType(Field->getType()));
6291 }
6292 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006293 }
6294 ObjCImplementation->setIvarInitializers(Context,
6295 AllToInit.data(), AllToInit.size());
6296 }
6297}