blob: 6259b85af480fd836732dfbe57774fdf213a6bb7 [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,
Douglas Gregor463421d2009-03-03 04:44:36 +0000464 Class->getTagKind() == RecordDecl::TK_class,
465 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.
507 // FIXME: Allocate via ASTContext?
508 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
509 Class->getTagKind() == RecordDecl::TK_class,
510 Access, BaseType);
511}
512
513void Sema::SetClassDeclAttributesFromBase(CXXRecordDecl *Class,
514 const CXXRecordDecl *BaseClass,
515 bool BaseIsVirtual) {
Eli Friedman89c038e2009-12-05 23:03:49 +0000516 // A class with a non-empty base class is not empty.
517 // FIXME: Standard ref?
518 if (!BaseClass->isEmpty())
519 Class->setEmpty(false);
520
521 // C++ [class.virtual]p1:
522 // A class that [...] inherits a virtual function is called a polymorphic
523 // class.
524 if (BaseClass->isPolymorphic())
525 Class->setPolymorphic(true);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000526
Douglas Gregor463421d2009-03-03 04:44:36 +0000527 // C++ [dcl.init.aggr]p1:
528 // An aggregate is [...] a class with [...] no base classes [...].
529 Class->setAggregate(false);
Eli Friedman89c038e2009-12-05 23:03:49 +0000530
531 // C++ [class]p4:
532 // A POD-struct is an aggregate class...
Douglas Gregor463421d2009-03-03 04:44:36 +0000533 Class->setPOD(false);
534
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000535 if (BaseIsVirtual) {
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000536 // C++ [class.ctor]p5:
537 // A constructor is trivial if its class has no virtual base classes.
538 Class->setHasTrivialConstructor(false);
Douglas Gregor8a273912009-07-22 18:25:24 +0000539
540 // C++ [class.copy]p6:
541 // A copy constructor is trivial if its class has no virtual base classes.
542 Class->setHasTrivialCopyConstructor(false);
543
544 // C++ [class.copy]p11:
545 // A copy assignment operator is trivial if its class has no virtual
546 // base classes.
547 Class->setHasTrivialCopyAssignment(false);
Eli Friedmanc96d4962009-08-15 21:55:26 +0000548
549 // C++0x [meta.unary.prop] is_empty:
550 // T is a class type, but not a union type, with ... no virtual base
551 // classes
552 Class->setEmpty(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000553 } else {
554 // C++ [class.ctor]p5:
Mike Stump11289f42009-09-09 15:08:12 +0000555 // A constructor is trivial if all the direct base classes of its
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000556 // class have trivial constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000557 if (!BaseClass->hasTrivialConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000558 Class->setHasTrivialConstructor(false);
559
560 // C++ [class.copy]p6:
561 // A copy constructor is trivial if all the direct base classes of its
562 // class have trivial copy constructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000563 if (!BaseClass->hasTrivialCopyConstructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000564 Class->setHasTrivialCopyConstructor(false);
565
566 // C++ [class.copy]p11:
567 // A copy assignment operator is trivial if all the direct base classes
568 // of its class have trivial copy assignment operators.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000569 if (!BaseClass->hasTrivialCopyAssignment())
Douglas Gregor8a273912009-07-22 18:25:24 +0000570 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonfe63dc52009-04-16 00:08:20 +0000571 }
Anders Carlsson6dc35752009-04-17 02:34:54 +0000572
573 // C++ [class.ctor]p3:
574 // A destructor is trivial if all the direct base classes of its class
575 // have trivial destructors.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000576 if (!BaseClass->hasTrivialDestructor())
Douglas Gregor8a273912009-07-22 18:25:24 +0000577 Class->setHasTrivialDestructor(false);
Douglas Gregor463421d2009-03-03 04:44:36 +0000578}
579
Douglas Gregor556877c2008-04-13 21:30:24 +0000580/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
581/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000582/// example:
583/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000584/// 'public bar' and 'virtual private baz' are each base-specifiers.
Mike Stump11289f42009-09-09 15:08:12 +0000585Sema::BaseResult
Chris Lattner83f095c2009-03-28 19:18:32 +0000586Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000587 bool Virtual, AccessSpecifier Access,
588 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000589 if (!classdecl)
590 return true;
591
Douglas Gregorc40290e2009-03-09 23:48:35 +0000592 AdjustDeclIfTemplate(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000593 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl.getAs<Decl>());
594 if (!Class)
595 return true;
596
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000597 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor463421d2009-03-03 04:44:36 +0000598 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
599 Virtual, Access,
600 BaseType, BaseLoc))
601 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000602
Douglas Gregor463421d2009-03-03 04:44:36 +0000603 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000604}
Douglas Gregor556877c2008-04-13 21:30:24 +0000605
Douglas Gregor463421d2009-03-03 04:44:36 +0000606/// \brief Performs the actual work of attaching the given base class
607/// specifiers to a C++ class.
608bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
609 unsigned NumBases) {
610 if (NumBases == 0)
611 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000612
613 // Used to keep track of which base types we have already seen, so
614 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000615 // that the key is always the unqualified canonical type of the base
616 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000617 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
618
619 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000620 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000621 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000622 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000623 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000624 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000625 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000626
Douglas Gregor29a92472008-10-22 17:49:05 +0000627 if (KnownBaseTypes[NewBaseType]) {
628 // C++ [class.mi]p3:
629 // A class shall not be specified as a direct base class of a
630 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000631 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000632 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000633 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000634 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000635
636 // Delete the duplicate base class specifier; we're going to
637 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000638 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000639
640 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000641 } else {
642 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000643 KnownBaseTypes[NewBaseType] = Bases[idx];
644 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000645 }
646 }
647
648 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000649 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000650
651 // Delete the remaining (good) base class specifiers, since their
652 // data has been copied into the CXXRecordDecl.
653 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000654 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000655
656 return Invalid;
657}
658
659/// ActOnBaseSpecifiers - Attach the given base specifiers to the
660/// class, after checking whether there are any duplicate base
661/// classes.
Mike Stump11289f42009-09-09 15:08:12 +0000662void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000663 unsigned NumBases) {
664 if (!ClassDecl || !Bases || !NumBases)
665 return;
666
667 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner83f095c2009-03-28 19:18:32 +0000668 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor463421d2009-03-03 04:44:36 +0000669 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000670}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000671
John McCalle78aac42010-03-10 03:28:59 +0000672static CXXRecordDecl *GetClassForType(QualType T) {
673 if (const RecordType *RT = T->getAs<RecordType>())
674 return cast<CXXRecordDecl>(RT->getDecl());
675 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
676 return ICT->getDecl();
677 else
678 return 0;
679}
680
Douglas Gregor36d1b142009-10-06 17:59:45 +0000681/// \brief Determine whether the type \p Derived is a C++ class that is
682/// derived from the type \p Base.
683bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
684 if (!getLangOptions().CPlusPlus)
685 return false;
John McCalle78aac42010-03-10 03:28:59 +0000686
687 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
688 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000689 return false;
690
John McCalle78aac42010-03-10 03:28:59 +0000691 CXXRecordDecl *BaseRD = GetClassForType(Base);
692 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000693 return false;
694
John McCall67da35c2010-02-04 22:26:26 +0000695 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
696 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000697}
698
699/// \brief Determine whether the type \p Derived is a C++ class that is
700/// derived from the type \p Base.
701bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
702 if (!getLangOptions().CPlusPlus)
703 return false;
704
John McCalle78aac42010-03-10 03:28:59 +0000705 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
706 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000707 return false;
708
John McCalle78aac42010-03-10 03:28:59 +0000709 CXXRecordDecl *BaseRD = GetClassForType(Base);
710 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000711 return false;
712
Douglas Gregor36d1b142009-10-06 17:59:45 +0000713 return DerivedRD->isDerivedFrom(BaseRD, Paths);
714}
715
Anders Carlssona70cff62010-04-24 19:06:50 +0000716void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
717 CXXBaseSpecifierArray &BasePathArray) {
718 assert(BasePathArray.empty() && "Base path array must be empty!");
719 assert(Paths.isRecordingPaths() && "Must record paths!");
720
721 const CXXBasePath &Path = Paths.front();
722
723 // We first go backward and check if we have a virtual base.
724 // FIXME: It would be better if CXXBasePath had the base specifier for
725 // the nearest virtual base.
726 unsigned Start = 0;
727 for (unsigned I = Path.size(); I != 0; --I) {
728 if (Path[I - 1].Base->isVirtual()) {
729 Start = I - 1;
730 break;
731 }
732 }
733
734 // Now add all bases.
735 for (unsigned I = Start, E = Path.size(); I != E; ++I)
736 BasePathArray.push_back(Path[I].Base);
737}
738
Douglas Gregor36d1b142009-10-06 17:59:45 +0000739/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
740/// conversion (where Derived and Base are class types) is
741/// well-formed, meaning that the conversion is unambiguous (and
742/// that all of the base classes are accessible). Returns true
743/// and emits a diagnostic if the code is ill-formed, returns false
744/// otherwise. Loc is the location where this routine should point to
745/// if there is an error, and Range is the source range to highlight
746/// if there is an error.
747bool
748Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000749 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000750 unsigned AmbigiousBaseConvID,
751 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000752 DeclarationName Name,
753 CXXBaseSpecifierArray *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000754 // First, determine whether the path from Derived to Base is
755 // ambiguous. This is slightly more expensive than checking whether
756 // the Derived to Base conversion exists, because here we need to
757 // explore multiple paths to determine if there is an ambiguity.
758 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
759 /*DetectVirtual=*/false);
760 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
761 assert(DerivationOkay &&
762 "Can only be used with a derived-to-base conversion");
763 (void)DerivationOkay;
764
765 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000766 if (InaccessibleBaseID) {
767 // Check that the base class can be accessed.
768 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
769 InaccessibleBaseID)) {
770 case AR_inaccessible:
771 return true;
772 case AR_accessible:
773 case AR_dependent:
774 case AR_delayed:
775 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000776 }
John McCall5b0829a2010-02-10 09:31:12 +0000777 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000778
779 // Build a base path if necessary.
780 if (BasePath)
781 BuildBasePathArray(Paths, *BasePath);
782 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000783 }
784
785 // We know that the derived-to-base conversion is ambiguous, and
786 // we're going to produce a diagnostic. Perform the derived-to-base
787 // search just one more time to compute all of the possible paths so
788 // that we can print them out. This is more expensive than any of
789 // the previous derived-to-base checks we've done, but at this point
790 // performance isn't as much of an issue.
791 Paths.clear();
792 Paths.setRecordingPaths(true);
793 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
794 assert(StillOkay && "Can only be used with a derived-to-base conversion");
795 (void)StillOkay;
796
797 // Build up a textual representation of the ambiguous paths, e.g.,
798 // D -> B -> A, that will be used to illustrate the ambiguous
799 // conversions in the diagnostic. We only print one of the paths
800 // to each base class subobject.
801 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
802
803 Diag(Loc, AmbigiousBaseConvID)
804 << Derived << Base << PathDisplayStr << Range << Name;
805 return true;
806}
807
808bool
809Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000810 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000811 CXXBaseSpecifierArray *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000812 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000813 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000814 IgnoreAccess ? 0
815 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000816 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000817 Loc, Range, DeclarationName(),
818 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000819}
820
821
822/// @brief Builds a string representing ambiguous paths from a
823/// specific derived class to different subobjects of the same base
824/// class.
825///
826/// This function builds a string that can be used in error messages
827/// to show the different paths that one can take through the
828/// inheritance hierarchy to go from the derived class to different
829/// subobjects of a base class. The result looks something like this:
830/// @code
831/// struct D -> struct B -> struct A
832/// struct D -> struct C -> struct A
833/// @endcode
834std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
835 std::string PathDisplayStr;
836 std::set<unsigned> DisplayedPaths;
837 for (CXXBasePaths::paths_iterator Path = Paths.begin();
838 Path != Paths.end(); ++Path) {
839 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
840 // We haven't displayed a path to this particular base
841 // class subobject yet.
842 PathDisplayStr += "\n ";
843 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
844 for (CXXBasePath::const_iterator Element = Path->begin();
845 Element != Path->end(); ++Element)
846 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
847 }
848 }
849
850 return PathDisplayStr;
851}
852
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000853//===----------------------------------------------------------------------===//
854// C++ class member Handling
855//===----------------------------------------------------------------------===//
856
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000857/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
858/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
859/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000860/// any.
Chris Lattner83f095c2009-03-28 19:18:32 +0000861Sema::DeclPtrTy
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000862Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000863 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000864 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
865 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000866 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor92751d42008-11-17 22:58:34 +0000867 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000868 Expr *BitWidth = static_cast<Expr*>(BW);
869 Expr *Init = static_cast<Expr*>(InitExpr);
870 SourceLocation Loc = D.getIdentifierLoc();
871
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000872 bool isFunc = D.isFunctionDeclarator();
873
John McCall07e91c02009-08-06 02:15:43 +0000874 assert(!DS.isFriendSpecified());
875
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000876 // C++ 9.2p6: A member shall not be declared to have automatic storage
877 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000878 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
879 // data members and cannot be applied to names declared const or static,
880 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000881 switch (DS.getStorageClassSpec()) {
882 case DeclSpec::SCS_unspecified:
883 case DeclSpec::SCS_typedef:
884 case DeclSpec::SCS_static:
885 // FALL THROUGH.
886 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000887 case DeclSpec::SCS_mutable:
888 if (isFunc) {
889 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000890 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000891 else
Chris Lattner3b054132008-11-19 05:08:23 +0000892 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000893
Sebastian Redl8071edb2008-11-17 23:24:37 +0000894 // FIXME: It would be nicer if the keyword was ignored only for this
895 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000896 D.getMutableDeclSpec().ClearStorageClassSpecs();
897 } else {
898 QualType T = GetTypeForDeclarator(D, S);
899 diag::kind err = static_cast<diag::kind>(0);
900 if (T->isReferenceType())
901 err = diag::err_mutable_reference;
902 else if (T.isConstQualified())
903 err = diag::err_mutable_const;
904 if (err != 0) {
905 if (DS.getStorageClassSpecLoc().isValid())
906 Diag(DS.getStorageClassSpecLoc(), err);
907 else
908 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl8071edb2008-11-17 23:24:37 +0000909 // FIXME: It would be nicer if the keyword was ignored only for this
910 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000911 D.getMutableDeclSpec().ClearStorageClassSpecs();
912 }
913 }
914 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000915 default:
916 if (DS.getStorageClassSpecLoc().isValid())
917 Diag(DS.getStorageClassSpecLoc(),
918 diag::err_storageclass_invalid_for_member);
919 else
920 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
921 D.getMutableDeclSpec().ClearStorageClassSpecs();
922 }
923
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000924 if (!isFunc &&
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000925 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidis2e3e7562008-10-15 20:23:22 +0000926 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000927 // Check also for this case:
928 //
929 // typedef int f();
930 // f a;
931 //
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000932 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000933 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000934 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000935
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000936 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
937 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000938 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000939
940 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000941 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000942 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000943 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
944 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000945 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000946 } else {
Sebastian Redld6f78502009-11-24 23:38:44 +0000947 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition)
Douglas Gregor3447e762009-08-20 22:52:58 +0000948 .getAs<Decl>();
Chris Lattner97e277e2009-03-05 23:03:49 +0000949 if (!Member) {
950 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000951 return DeclPtrTy();
Chris Lattner97e277e2009-03-05 23:03:49 +0000952 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000953
954 // Non-instance-fields can't have a bitfield.
955 if (BitWidth) {
956 if (Member->isInvalidDecl()) {
957 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000958 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000959 // C++ 9.6p3: A bit-field shall not be a static member.
960 // "static member 'A' cannot be a bit-field"
961 Diag(Loc, diag::err_static_not_bitfield)
962 << Name << BitWidth->getSourceRange();
963 } else if (isa<TypedefDecl>(Member)) {
964 // "typedef member 'x' cannot be a bit-field"
965 Diag(Loc, diag::err_typedef_not_bitfield)
966 << Name << BitWidth->getSourceRange();
967 } else {
968 // A function typedef ("typedef int f(); f a;").
969 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
970 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000971 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000972 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000973 }
Mike Stump11289f42009-09-09 15:08:12 +0000974
Chris Lattnerd26760a2009-03-05 23:01:03 +0000975 DeleteExpr(BitWidth);
976 BitWidth = 0;
977 Member->setInvalidDecl();
978 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000979
980 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000981
Douglas Gregor3447e762009-08-20 22:52:58 +0000982 // If we have declared a member function template, set the access of the
983 // templated declaration as well.
984 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
985 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000986 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000987
Douglas Gregor92751d42008-11-17 22:58:34 +0000988 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000989
Douglas Gregor0c880302009-03-11 23:00:04 +0000990 if (Init)
Chris Lattner83f095c2009-03-28 19:18:32 +0000991 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000992 if (Deleted) // FIXME: Source location is not very good.
993 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000994
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000995 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000996 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000997 return DeclPtrTy();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000998 }
Chris Lattner83f095c2009-03-28 19:18:32 +0000999 return DeclPtrTy::make(Member);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001000}
1001
Douglas Gregor15e77a22009-12-31 09:10:24 +00001002/// \brief Find the direct and/or virtual base specifiers that
1003/// correspond to the given base type, for use in base initialization
1004/// within a constructor.
1005static bool FindBaseInitializer(Sema &SemaRef,
1006 CXXRecordDecl *ClassDecl,
1007 QualType BaseType,
1008 const CXXBaseSpecifier *&DirectBaseSpec,
1009 const CXXBaseSpecifier *&VirtualBaseSpec) {
1010 // First, check for a direct base class.
1011 DirectBaseSpec = 0;
1012 for (CXXRecordDecl::base_class_const_iterator Base
1013 = ClassDecl->bases_begin();
1014 Base != ClassDecl->bases_end(); ++Base) {
1015 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1016 // We found a direct base of this type. That's what we're
1017 // initializing.
1018 DirectBaseSpec = &*Base;
1019 break;
1020 }
1021 }
1022
1023 // Check for a virtual base class.
1024 // FIXME: We might be able to short-circuit this if we know in advance that
1025 // there are no virtual bases.
1026 VirtualBaseSpec = 0;
1027 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1028 // We haven't found a base yet; search the class hierarchy for a
1029 // virtual base class.
1030 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1031 /*DetectVirtual=*/false);
1032 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1033 BaseType, Paths)) {
1034 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1035 Path != Paths.end(); ++Path) {
1036 if (Path->back().Base->isVirtual()) {
1037 VirtualBaseSpec = Path->back().Base;
1038 break;
1039 }
1040 }
1041 }
1042 }
1043
1044 return DirectBaseSpec || VirtualBaseSpec;
1045}
1046
Douglas Gregore8381c02008-11-05 04:29:56 +00001047/// ActOnMemInitializer - Handle a C++ member initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001048Sema::MemInitResult
Chris Lattner83f095c2009-03-28 19:18:32 +00001049Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +00001050 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001051 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +00001052 IdentifierInfo *MemberOrBase,
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001053 TypeTy *TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +00001054 SourceLocation IdLoc,
1055 SourceLocation LParenLoc,
1056 ExprTy **Args, unsigned NumArgs,
1057 SourceLocation *CommaLocs,
1058 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +00001059 if (!ConstructorD)
1060 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001061
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001062 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001063
1064 CXXConstructorDecl *Constructor
Chris Lattner83f095c2009-03-28 19:18:32 +00001065 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregore8381c02008-11-05 04:29:56 +00001066 if (!Constructor) {
1067 // The user wrote a constructor initializer on a function that is
1068 // not a C++ constructor. Ignore the error for now, because we may
1069 // have more member initializers coming; we'll diagnose it just
1070 // once in ActOnMemInitializers.
1071 return true;
1072 }
1073
1074 CXXRecordDecl *ClassDecl = Constructor->getParent();
1075
1076 // C++ [class.base.init]p2:
1077 // Names in a mem-initializer-id are looked up in the scope of the
1078 // constructor’s class and, if not found in that scope, are looked
1079 // up in the scope containing the constructor’s
1080 // definition. [Note: if the constructor’s class contains a member
1081 // with the same name as a direct or virtual base class of the
1082 // class, a mem-initializer-id naming the member or base class and
1083 // composed of a single identifier refers to the class member. A
1084 // mem-initializer-id for the hidden base class may be specified
1085 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001086 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001087 // Look for a member, first.
1088 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001089 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001090 = ClassDecl->lookup(MemberOrBase);
1091 if (Result.first != Result.second)
1092 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001093
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001094 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001095
Eli Friedman8e1433b2009-07-29 19:44:27 +00001096 if (Member)
1097 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001098 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001099 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001100 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001101 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001102 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001103
1104 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001105 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001106 } else {
1107 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1108 LookupParsedName(R, S, &SS);
1109
1110 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1111 if (!TyD) {
1112 if (R.isAmbiguous()) return true;
1113
John McCallda6841b2010-04-09 19:01:14 +00001114 // We don't want access-control diagnostics here.
1115 R.suppressDiagnostics();
1116
Douglas Gregora3b624a2010-01-19 06:46:48 +00001117 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1118 bool NotUnknownSpecialization = false;
1119 DeclContext *DC = computeDeclContext(SS, false);
1120 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1121 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1122
1123 if (!NotUnknownSpecialization) {
1124 // When the scope specifier can refer to a member of an unknown
1125 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001126 BaseType = CheckTypenameType(ETK_None,
1127 (NestedNameSpecifier *)SS.getScopeRep(),
Douglas Gregora3b624a2010-01-19 06:46:48 +00001128 *MemberOrBase, SS.getRange());
Douglas Gregor281c4862010-03-07 23:26:22 +00001129 if (BaseType.isNull())
1130 return true;
1131
Douglas Gregora3b624a2010-01-19 06:46:48 +00001132 R.clear();
1133 }
1134 }
1135
Douglas Gregor15e77a22009-12-31 09:10:24 +00001136 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001137 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001138 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1139 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001140 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1141 if (Member->getDeclContext()->getLookupContext()->Equals(ClassDecl)) {
1142 // We have found a non-static data member with a similar
1143 // name to what was typed; complain and initialize that
1144 // member.
1145 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1146 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001147 << FixItHint::CreateReplacement(R.getNameLoc(),
1148 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001149 Diag(Member->getLocation(), diag::note_previous_decl)
1150 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001151
1152 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1153 LParenLoc, RParenLoc);
1154 }
1155 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1156 const CXXBaseSpecifier *DirectBaseSpec;
1157 const CXXBaseSpecifier *VirtualBaseSpec;
1158 if (FindBaseInitializer(*this, ClassDecl,
1159 Context.getTypeDeclType(Type),
1160 DirectBaseSpec, VirtualBaseSpec)) {
1161 // We have found a direct or virtual base class with a
1162 // similar name to what was typed; complain and initialize
1163 // that base class.
1164 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1165 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001166 << FixItHint::CreateReplacement(R.getNameLoc(),
1167 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001168
1169 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1170 : VirtualBaseSpec;
1171 Diag(BaseSpec->getSourceRange().getBegin(),
1172 diag::note_base_class_specified_here)
1173 << BaseSpec->getType()
1174 << BaseSpec->getSourceRange();
1175
Douglas Gregor15e77a22009-12-31 09:10:24 +00001176 TyD = Type;
1177 }
1178 }
1179 }
1180
Douglas Gregora3b624a2010-01-19 06:46:48 +00001181 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001182 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1183 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1184 return true;
1185 }
John McCallb5a0d312009-12-21 10:41:20 +00001186 }
1187
Douglas Gregora3b624a2010-01-19 06:46:48 +00001188 if (BaseType.isNull()) {
1189 BaseType = Context.getTypeDeclType(TyD);
1190 if (SS.isSet()) {
1191 NestedNameSpecifier *Qualifier =
1192 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001193
Douglas Gregora3b624a2010-01-19 06:46:48 +00001194 // FIXME: preserve source range information
1195 BaseType = Context.getQualifiedNameType(Qualifier, BaseType);
1196 }
John McCallb5a0d312009-12-21 10:41:20 +00001197 }
1198 }
Mike Stump11289f42009-09-09 15:08:12 +00001199
John McCallbcd03502009-12-07 02:54:59 +00001200 if (!TInfo)
1201 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001202
John McCallbcd03502009-12-07 02:54:59 +00001203 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001204 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001205}
1206
John McCalle22a04a2009-11-04 23:02:40 +00001207/// Checks an initializer expression for use of uninitialized fields, such as
1208/// containing the field that is being initialized. Returns true if there is an
1209/// uninitialized field was used an updates the SourceLocation parameter; false
1210/// otherwise.
1211static bool InitExprContainsUninitializedFields(const Stmt* S,
1212 const FieldDecl* LhsField,
1213 SourceLocation* L) {
1214 const MemberExpr* ME = dyn_cast<MemberExpr>(S);
1215 if (ME) {
1216 const NamedDecl* RhsField = ME->getMemberDecl();
1217 if (RhsField == LhsField) {
1218 // Initializing a field with itself. Throw a warning.
1219 // But wait; there are exceptions!
1220 // Exception #1: The field may not belong to this record.
1221 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1222 const Expr* base = ME->getBase();
1223 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1224 // Even though the field matches, it does not belong to this record.
1225 return false;
1226 }
1227 // None of the exceptions triggered; return true to indicate an
1228 // uninitialized field was used.
1229 *L = ME->getMemberLoc();
1230 return true;
1231 }
1232 }
1233 bool found = false;
1234 for (Stmt::const_child_iterator it = S->child_begin();
1235 it != S->child_end() && found == false;
1236 ++it) {
1237 if (isa<CallExpr>(S)) {
1238 // Do not descend into function calls or constructors, as the use
1239 // of an uninitialized field may be valid. One would have to inspect
1240 // the contents of the function/ctor to determine if it is safe or not.
1241 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1242 // may be safe, depending on what the function/ctor does.
1243 continue;
1244 }
1245 found = InitExprContainsUninitializedFields(*it, LhsField, L);
1246 }
1247 return found;
1248}
1249
Eli Friedman8e1433b2009-07-29 19:44:27 +00001250Sema::MemInitResult
1251Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1252 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001253 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001254 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001255 // Diagnose value-uses of fields to initialize themselves, e.g.
1256 // foo(foo)
1257 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001258 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001259 for (unsigned i = 0; i < NumArgs; ++i) {
1260 SourceLocation L;
1261 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1262 // FIXME: Return true in the case when other fields are used before being
1263 // uninitialized. For example, let this field be the i'th field. When
1264 // initializing the i'th field, throw a warning if any of the >= i'th
1265 // fields are used, as they are not yet initialized.
1266 // Right now we are only handling the case where the i'th field uses
1267 // itself in its initializer.
1268 Diag(L, diag::warn_field_is_uninit);
1269 }
1270 }
1271
Eli Friedman8e1433b2009-07-29 19:44:27 +00001272 bool HasDependentArg = false;
1273 for (unsigned i = 0; i < NumArgs; i++)
1274 HasDependentArg |= Args[i]->isTypeDependent();
1275
Eli Friedman8e1433b2009-07-29 19:44:27 +00001276 QualType FieldType = Member->getType();
1277 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1278 FieldType = Array->getElementType();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001279 if (FieldType->isDependentType() || HasDependentArg) {
1280 // Can't check initialization for a member of dependent type or when
1281 // any of the arguments are type-dependent expressions.
1282 OwningExprResult Init
1283 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1284 RParenLoc));
1285
1286 // Erase any temporaries within this evaluation context; we're not
1287 // going to track them in the AST, since we'll be rebuilding the
1288 // ASTs during template instantiation.
1289 ExprTemporaries.erase(
1290 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1291 ExprTemporaries.end());
1292
1293 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1294 LParenLoc,
1295 Init.takeAs<Expr>(),
1296 RParenLoc);
1297
Douglas Gregore8381c02008-11-05 04:29:56 +00001298 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001299
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001300 if (Member->isInvalidDecl())
1301 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001302
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001303 // Initialize the member.
1304 InitializedEntity MemberEntity =
1305 InitializedEntity::InitializeMember(Member, 0);
1306 InitializationKind Kind =
1307 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1308
1309 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1310
1311 OwningExprResult MemberInit =
1312 InitSeq.Perform(*this, MemberEntity, Kind,
1313 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1314 if (MemberInit.isInvalid())
1315 return true;
1316
1317 // C++0x [class.base.init]p7:
1318 // The initialization of each base and member constitutes a
1319 // full-expression.
1320 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1321 if (MemberInit.isInvalid())
1322 return true;
1323
1324 // If we are in a dependent context, template instantiation will
1325 // perform this type-checking again. Just save the arguments that we
1326 // received in a ParenListExpr.
1327 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1328 // of the information that we have about the member
1329 // initializer. However, deconstructing the ASTs is a dicey process,
1330 // and this approach is far more likely to get the corner cases right.
1331 if (CurContext->isDependentContext()) {
1332 // Bump the reference count of all of the arguments.
1333 for (unsigned I = 0; I != NumArgs; ++I)
1334 Args[I]->Retain();
1335
1336 OwningExprResult Init
1337 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1338 RParenLoc));
1339 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1340 LParenLoc,
1341 Init.takeAs<Expr>(),
1342 RParenLoc);
1343 }
1344
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001345 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001346 LParenLoc,
1347 MemberInit.takeAs<Expr>(),
1348 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001349}
1350
1351Sema::MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001352Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001353 Expr **Args, unsigned NumArgs,
1354 SourceLocation LParenLoc, SourceLocation RParenLoc,
1355 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001356 bool HasDependentArg = false;
1357 for (unsigned i = 0; i < NumArgs; i++)
1358 HasDependentArg |= Args[i]->isTypeDependent();
1359
John McCallbcd03502009-12-07 02:54:59 +00001360 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001361 if (BaseType->isDependentType() || HasDependentArg) {
1362 // Can't check initialization for a base of dependent type or when
1363 // any of the arguments are type-dependent expressions.
1364 OwningExprResult BaseInit
1365 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1366 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001367
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001368 // Erase any temporaries within this evaluation context; we're not
1369 // going to track them in the AST, since we'll be rebuilding the
1370 // ASTs during template instantiation.
1371 ExprTemporaries.erase(
1372 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1373 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001374
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001375 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001376 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001377 LParenLoc,
1378 BaseInit.takeAs<Expr>(),
1379 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001380 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001381
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001382 if (!BaseType->isRecordType())
1383 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1384 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1385
1386 // C++ [class.base.init]p2:
1387 // [...] Unless the mem-initializer-id names a nonstatic data
1388 // member of the constructor’s class or a direct or virtual base
1389 // of that class, the mem-initializer is ill-formed. A
1390 // mem-initializer-list can initialize a base class using any
1391 // name that denotes that base class type.
1392
1393 // Check for direct and virtual base classes.
1394 const CXXBaseSpecifier *DirectBaseSpec = 0;
1395 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1396 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1397 VirtualBaseSpec);
1398
1399 // C++ [base.class.init]p2:
1400 // If a mem-initializer-id is ambiguous because it designates both
1401 // a direct non-virtual base class and an inherited virtual base
1402 // class, the mem-initializer is ill-formed.
1403 if (DirectBaseSpec && VirtualBaseSpec)
1404 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1405 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
1406 // C++ [base.class.init]p2:
1407 // Unless the mem-initializer-id names a nonstatic data membeer of the
1408 // constructor's class ot a direst or virtual base of that class, the
1409 // mem-initializer is ill-formed.
1410 if (!DirectBaseSpec && !VirtualBaseSpec)
1411 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
John McCall1e67dd62010-04-27 01:43:38 +00001412 << BaseType << Context.getTypeDeclType(ClassDecl)
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001413 << BaseTInfo->getTypeLoc().getSourceRange();
1414
1415 CXXBaseSpecifier *BaseSpec
1416 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1417 if (!BaseSpec)
1418 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1419
1420 // Initialize the base.
1421 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001422 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001423 InitializationKind Kind =
1424 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1425
1426 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1427
1428 OwningExprResult BaseInit =
1429 InitSeq.Perform(*this, BaseEntity, Kind,
1430 MultiExprArg(*this, (void**)Args, NumArgs), 0);
1431 if (BaseInit.isInvalid())
1432 return true;
1433
1434 // C++0x [class.base.init]p7:
1435 // The initialization of each base and member constitutes a
1436 // full-expression.
1437 BaseInit = MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1438 if (BaseInit.isInvalid())
1439 return true;
1440
1441 // If we are in a dependent context, template instantiation will
1442 // perform this type-checking again. Just save the arguments that we
1443 // received in a ParenListExpr.
1444 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1445 // of the information that we have about the base
1446 // initializer. However, deconstructing the ASTs is a dicey process,
1447 // and this approach is far more likely to get the corner cases right.
1448 if (CurContext->isDependentContext()) {
1449 // Bump the reference count of all of the arguments.
1450 for (unsigned I = 0; I != NumArgs; ++I)
1451 Args[I]->Retain();
1452
1453 OwningExprResult Init
1454 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1455 RParenLoc));
1456 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001457 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001458 LParenLoc,
1459 Init.takeAs<Expr>(),
1460 RParenLoc);
1461 }
1462
1463 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001464 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001465 LParenLoc,
1466 BaseInit.takeAs<Expr>(),
1467 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001468}
1469
Anders Carlsson1b00e242010-04-23 03:10:23 +00001470/// ImplicitInitializerKind - How an implicit base or member initializer should
1471/// initialize its base or member.
1472enum ImplicitInitializerKind {
1473 IIK_Default,
1474 IIK_Copy,
1475 IIK_Move
1476};
1477
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001478static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001479BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001480 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001481 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001482 bool IsInheritedVirtualBase,
1483 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001484 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001485 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1486 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001487
Anders Carlsson1b00e242010-04-23 03:10:23 +00001488 Sema::OwningExprResult BaseInit(SemaRef);
1489
1490 switch (ImplicitInitKind) {
1491 case IIK_Default: {
1492 InitializationKind InitKind
1493 = InitializationKind::CreateDefault(Constructor->getLocation());
1494 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1495 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1496 Sema::MultiExprArg(SemaRef, 0, 0));
1497 break;
1498 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001499
Anders Carlsson1b00e242010-04-23 03:10:23 +00001500 case IIK_Copy: {
1501 ParmVarDecl *Param = Constructor->getParamDecl(0);
1502 QualType ParamType = Param->getType().getNonReferenceType();
1503
1504 Expr *CopyCtorArg =
1505 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregored088b72010-05-03 15:43:53 +00001506 Constructor->getLocation(), ParamType, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001507
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001508 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001509 QualType ArgTy =
1510 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1511 ParamType.getQualifiers());
1512 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001513 CastExpr::CK_UncheckedDerivedToBase,
Anders Carlsson36db0d92010-04-24 22:54:32 +00001514 /*isLvalue=*/true,
1515 CXXBaseSpecifierArray(BaseSpec));
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001516
Anders Carlsson1b00e242010-04-23 03:10:23 +00001517 InitializationKind InitKind
1518 = InitializationKind::CreateDirect(Constructor->getLocation(),
1519 SourceLocation(), SourceLocation());
1520 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1521 &CopyCtorArg, 1);
1522 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1523 Sema::MultiExprArg(SemaRef,
1524 (void**)&CopyCtorArg, 1));
1525 break;
1526 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001527
Anders Carlsson1b00e242010-04-23 03:10:23 +00001528 case IIK_Move:
1529 assert(false && "Unhandled initializer kind!");
1530 }
1531
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001532 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(BaseInit));
1533 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001534 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001535
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001536 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001537 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1538 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1539 SourceLocation()),
1540 BaseSpec->isVirtual(),
1541 SourceLocation(),
1542 BaseInit.takeAs<Expr>(),
1543 SourceLocation());
1544
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001545 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001546}
1547
Anders Carlsson3c1db572010-04-23 02:15:47 +00001548static bool
1549BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001550 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001551 FieldDecl *Field,
1552 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Anders Carlsson423f5d82010-04-23 16:04:08 +00001553 if (ImplicitInitKind == IIK_Copy) {
Anders Carlsson79111502010-05-01 16:39:01 +00001554 // FIXME: We should not return early here, but will do so until
1555 // we know how to handle copy initialization of arrays.
1556 CXXMemberInit = 0;
1557 return false;
1558
Anders Carlsson423f5d82010-04-23 16:04:08 +00001559 ParmVarDecl *Param = Constructor->getParamDecl(0);
1560 QualType ParamType = Param->getType().getNonReferenceType();
1561
1562 Expr *MemberExprBase =
1563 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
1564 SourceLocation(), ParamType, 0);
1565
1566
1567 Expr *CopyCtorArg =
1568 MemberExpr::Create(SemaRef.Context, MemberExprBase, /*IsArrow=*/false,
1569 0, SourceRange(), Field,
1570 DeclAccessPair::make(Field, Field->getAccess()),
1571 SourceLocation(), 0,
1572 Field->getType().getNonReferenceType());
1573
1574 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
1575 InitializationKind InitKind =
1576 InitializationKind::CreateDirect(Constructor->getLocation(),
1577 SourceLocation(), SourceLocation());
1578
1579 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1580 &CopyCtorArg, 1);
1581
1582 Sema::OwningExprResult MemberInit =
1583 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1584 Sema::MultiExprArg(SemaRef, (void**)&CopyCtorArg, 1), 0);
1585 if (MemberInit.isInvalid())
1586 return true;
1587
Anders Carlsson1b00e242010-04-23 03:10:23 +00001588 CXXMemberInit = 0;
1589 return false;
1590 }
1591
Anders Carlsson423f5d82010-04-23 16:04:08 +00001592 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1593
Anders Carlsson3c1db572010-04-23 02:15:47 +00001594 QualType FieldBaseElementType =
1595 SemaRef.Context.getBaseElementType(Field->getType());
1596
Anders Carlsson3c1db572010-04-23 02:15:47 +00001597 if (FieldBaseElementType->isRecordType()) {
1598 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001599 InitializationKind InitKind =
1600 InitializationKind::CreateDefault(Constructor->getLocation());
Anders Carlsson3c1db572010-04-23 02:15:47 +00001601
1602 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1603 Sema::OwningExprResult MemberInit =
1604 InitSeq.Perform(SemaRef, InitEntity, InitKind,
1605 Sema::MultiExprArg(SemaRef, 0, 0));
1606 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(move(MemberInit));
1607 if (MemberInit.isInvalid())
1608 return true;
1609
1610 CXXMemberInit =
1611 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1612 Field, SourceLocation(),
1613 SourceLocation(),
1614 MemberInit.takeAs<Expr>(),
1615 SourceLocation());
1616 return false;
1617 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001618
1619 if (FieldBaseElementType->isReferenceType()) {
1620 SemaRef.Diag(Constructor->getLocation(),
1621 diag::err_uninitialized_member_in_ctor)
1622 << (int)Constructor->isImplicit()
1623 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1624 << 0 << Field->getDeclName();
1625 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1626 return true;
1627 }
1628
1629 if (FieldBaseElementType.isConstQualified()) {
1630 SemaRef.Diag(Constructor->getLocation(),
1631 diag::err_uninitialized_member_in_ctor)
1632 << (int)Constructor->isImplicit()
1633 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1634 << 1 << Field->getDeclName();
1635 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1636 return true;
1637 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001638
1639 // Nothing to initialize.
1640 CXXMemberInit = 0;
1641 return false;
1642}
1643
Eli Friedman9cf6b592009-11-09 19:20:36 +00001644bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001645Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001646 CXXBaseOrMemberInitializer **Initializers,
1647 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001648 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001649 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001650 // Just store the initializers as written, they will be checked during
1651 // instantiation.
1652 if (NumInitializers > 0) {
1653 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1654 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1655 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1656 memcpy(baseOrMemberInitializers, Initializers,
1657 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1658 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1659 }
1660
1661 return false;
1662 }
1663
Anders Carlsson1b00e242010-04-23 03:10:23 +00001664 ImplicitInitializerKind ImplicitInitKind = IIK_Default;
1665
1666 // FIXME: Handle implicit move constructors.
1667 if (Constructor->isImplicit() && Constructor->isCopyConstructor())
1668 ImplicitInitKind = IIK_Copy;
1669
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001670 // We need to build the initializer AST according to order of construction
1671 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001672 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001673 if (!ClassDecl)
1674 return true;
1675
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001676 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
1677 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
Eli Friedman9cf6b592009-11-09 19:20:36 +00001678 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001679
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001680 for (unsigned i = 0; i < NumInitializers; i++) {
1681 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001682
1683 if (Member->isBaseInitializer())
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001684 AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001685 else
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001686 AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001687 }
1688
Anders Carlsson43c64af2010-04-21 19:52:01 +00001689 // Keep track of the direct virtual bases.
1690 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1691 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1692 E = ClassDecl->bases_end(); I != E; ++I) {
1693 if (I->isVirtual())
1694 DirectVBases.insert(I);
1695 }
1696
Anders Carlssondb0a9652010-04-02 06:26:44 +00001697 // Push virtual bases before others.
1698 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1699 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1700
1701 if (CXXBaseOrMemberInitializer *Value
1702 = AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1703 AllToInit.push_back(Value);
1704 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001705 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001706 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001707 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1708 VBase, IsInheritedVirtualBase,
1709 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001710 HadError = true;
1711 continue;
1712 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001713
Anders Carlssondb0a9652010-04-02 06:26:44 +00001714 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001715 }
1716 }
Mike Stump11289f42009-09-09 15:08:12 +00001717
Anders Carlssondb0a9652010-04-02 06:26:44 +00001718 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1719 E = ClassDecl->bases_end(); Base != E; ++Base) {
1720 // Virtuals are in the virtual base list and already constructed.
1721 if (Base->isVirtual())
1722 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001723
Anders Carlssondb0a9652010-04-02 06:26:44 +00001724 if (CXXBaseOrMemberInitializer *Value
1725 = AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1726 AllToInit.push_back(Value);
1727 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001728 CXXBaseOrMemberInitializer *CXXBaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001729 if (BuildImplicitBaseInitializer(*this, Constructor, ImplicitInitKind,
1730 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001731 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001732 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001733 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001734 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001735
Anders Carlssondb0a9652010-04-02 06:26:44 +00001736 AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001737 }
1738 }
Mike Stump11289f42009-09-09 15:08:12 +00001739
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001740 // non-static data members.
1741 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1742 E = ClassDecl->field_end(); Field != E; ++Field) {
1743 if ((*Field)->isAnonymousStructOrUnion()) {
Mike Stump11289f42009-09-09 15:08:12 +00001744 if (const RecordType *FieldClassType =
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001745 Field->getType()->getAs<RecordType>()) {
1746 CXXRecordDecl *FieldClassDecl
Douglas Gregor07eae022009-11-13 18:34:26 +00001747 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001748 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001749 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1750 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*FA)) {
1751 // 'Member' is the anonymous union field and 'AnonUnionMember' is
1752 // set to the anonymous union data member used in the initializer
1753 // list.
1754 Value->setMember(*Field);
1755 Value->setAnonUnionMember(*FA);
1756 AllToInit.push_back(Value);
1757 break;
1758 }
1759 }
1760 }
1761 continue;
1762 }
1763 if (CXXBaseOrMemberInitializer *Value = AllBaseFields.lookup(*Field)) {
1764 AllToInit.push_back(Value);
1765 continue;
1766 }
Mike Stump11289f42009-09-09 15:08:12 +00001767
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001768 if (AnyErrors)
Douglas Gregor2de8f412009-11-04 17:16:11 +00001769 continue;
Douglas Gregor2de8f412009-11-04 17:16:11 +00001770
Anders Carlsson3c1db572010-04-23 02:15:47 +00001771 CXXBaseOrMemberInitializer *Member;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001772 if (BuildImplicitMemberInitializer(*this, Constructor, ImplicitInitKind,
1773 *Field, Member)) {
Anders Carlsson3c1db572010-04-23 02:15:47 +00001774 HadError = true;
1775 continue;
1776 }
1777
1778 // If the member doesn't need to be initialized, it will be null.
1779 if (Member)
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001780 AllToInit.push_back(Member);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001781 }
Mike Stump11289f42009-09-09 15:08:12 +00001782
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001783 NumInitializers = AllToInit.size();
1784 if (NumInitializers > 0) {
1785 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1786 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1787 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCalla6309952010-03-16 21:39:52 +00001788 memcpy(baseOrMemberInitializers, AllToInit.data(),
1789 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001790 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001791
John McCalla6309952010-03-16 21:39:52 +00001792 // Constructors implicitly reference the base and member
1793 // destructors.
1794 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1795 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001796 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001797
1798 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001799}
1800
Eli Friedman952c15d2009-07-21 19:28:10 +00001801static void *GetKeyForTopLevelField(FieldDecl *Field) {
1802 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001803 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001804 if (RT->getDecl()->isAnonymousStructOrUnion())
1805 return static_cast<void *>(RT->getDecl());
1806 }
1807 return static_cast<void *>(Field);
1808}
1809
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001810static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1811 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001812}
1813
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001814static void *GetKeyForMember(ASTContext &Context,
1815 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001816 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001817 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001818 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001819
Eli Friedman952c15d2009-07-21 19:28:10 +00001820 // For fields injected into the class via declaration of an anonymous union,
1821 // use its anonymous union class declaration as the unique key.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001822 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001823
Anders Carlssona942dcd2010-03-30 15:39:27 +00001824 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1825 // data member of the class. Data member used in the initializer list is
1826 // in AnonUnionMember field.
1827 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1828 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001829
John McCall23eebd92010-04-10 09:28:51 +00001830 // If the field is a member of an anonymous struct or union, our key
1831 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001832 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001833 if (RD->isAnonymousStructOrUnion()) {
1834 while (true) {
1835 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1836 if (Parent->isAnonymousStructOrUnion())
1837 RD = Parent;
1838 else
1839 break;
1840 }
1841
Anders Carlsson83ac3122010-03-30 16:19:37 +00001842 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001843 }
Mike Stump11289f42009-09-09 15:08:12 +00001844
Anders Carlssona942dcd2010-03-30 15:39:27 +00001845 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00001846}
1847
Anders Carlssone857b292010-04-02 03:37:03 +00001848static void
1849DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001850 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00001851 CXXBaseOrMemberInitializer **Inits,
1852 unsigned NumInits) {
1853 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001854 return;
Mike Stump11289f42009-09-09 15:08:12 +00001855
John McCallbb7b6582010-04-10 07:37:23 +00001856 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1857 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001858 return;
Anders Carlssone857b292010-04-02 03:37:03 +00001859
John McCallbb7b6582010-04-10 07:37:23 +00001860 // Build the list of bases and members in the order that they'll
1861 // actually be initialized. The explicit initializers should be in
1862 // this same order but may be missing things.
1863 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00001864
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001865 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1866
John McCallbb7b6582010-04-10 07:37:23 +00001867 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001868 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001869 ClassDecl->vbases_begin(),
1870 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00001871 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001872
John McCallbb7b6582010-04-10 07:37:23 +00001873 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001874 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001875 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00001876 if (Base->isVirtual())
1877 continue;
John McCallbb7b6582010-04-10 07:37:23 +00001878 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001879 }
Mike Stump11289f42009-09-09 15:08:12 +00001880
John McCallbb7b6582010-04-10 07:37:23 +00001881 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00001882 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1883 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00001884 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001885
John McCallbb7b6582010-04-10 07:37:23 +00001886 unsigned NumIdealInits = IdealInitKeys.size();
1887 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00001888
John McCallbb7b6582010-04-10 07:37:23 +00001889 CXXBaseOrMemberInitializer *PrevInit = 0;
1890 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1891 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1892 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
1893
1894 // Scan forward to try to find this initializer in the idealized
1895 // initializers list.
1896 for (; IdealIndex != NumIdealInits; ++IdealIndex)
1897 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001898 break;
John McCallbb7b6582010-04-10 07:37:23 +00001899
1900 // If we didn't find this initializer, it must be because we
1901 // scanned past it on a previous iteration. That can only
1902 // happen if we're out of order; emit a warning.
1903 if (IdealIndex == NumIdealInits) {
1904 assert(PrevInit && "initializer not found in initializer list");
1905
1906 Sema::SemaDiagnosticBuilder D =
1907 SemaRef.Diag(PrevInit->getSourceLocation(),
1908 diag::warn_initializer_out_of_order);
1909
1910 if (PrevInit->isMemberInitializer())
1911 D << 0 << PrevInit->getMember()->getDeclName();
1912 else
1913 D << 1 << PrevInit->getBaseClassInfo()->getType();
1914
1915 if (Init->isMemberInitializer())
1916 D << 0 << Init->getMember()->getDeclName();
1917 else
1918 D << 1 << Init->getBaseClassInfo()->getType();
1919
1920 // Move back to the initializer's location in the ideal list.
1921 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
1922 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001923 break;
John McCallbb7b6582010-04-10 07:37:23 +00001924
1925 assert(IdealIndex != NumIdealInits &&
1926 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001927 }
John McCallbb7b6582010-04-10 07:37:23 +00001928
1929 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00001930 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00001931}
1932
John McCall23eebd92010-04-10 09:28:51 +00001933namespace {
1934bool CheckRedundantInit(Sema &S,
1935 CXXBaseOrMemberInitializer *Init,
1936 CXXBaseOrMemberInitializer *&PrevInit) {
1937 if (!PrevInit) {
1938 PrevInit = Init;
1939 return false;
1940 }
1941
1942 if (FieldDecl *Field = Init->getMember())
1943 S.Diag(Init->getSourceLocation(),
1944 diag::err_multiple_mem_initialization)
1945 << Field->getDeclName()
1946 << Init->getSourceRange();
1947 else {
1948 Type *BaseClass = Init->getBaseClass();
1949 assert(BaseClass && "neither field nor base");
1950 S.Diag(Init->getSourceLocation(),
1951 diag::err_multiple_base_initialization)
1952 << QualType(BaseClass, 0)
1953 << Init->getSourceRange();
1954 }
1955 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
1956 << 0 << PrevInit->getSourceRange();
1957
1958 return true;
1959}
1960
1961typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
1962typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
1963
1964bool CheckRedundantUnionInit(Sema &S,
1965 CXXBaseOrMemberInitializer *Init,
1966 RedundantUnionMap &Unions) {
1967 FieldDecl *Field = Init->getMember();
1968 RecordDecl *Parent = Field->getParent();
1969 if (!Parent->isAnonymousStructOrUnion())
1970 return false;
1971
1972 NamedDecl *Child = Field;
1973 do {
1974 if (Parent->isUnion()) {
1975 UnionEntry &En = Unions[Parent];
1976 if (En.first && En.first != Child) {
1977 S.Diag(Init->getSourceLocation(),
1978 diag::err_multiple_mem_union_initialization)
1979 << Field->getDeclName()
1980 << Init->getSourceRange();
1981 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
1982 << 0 << En.second->getSourceRange();
1983 return true;
1984 } else if (!En.first) {
1985 En.first = Child;
1986 En.second = Init;
1987 }
1988 }
1989
1990 Child = Parent;
1991 Parent = cast<RecordDecl>(Parent->getDeclContext());
1992 } while (Parent->isAnonymousStructOrUnion());
1993
1994 return false;
1995}
1996}
1997
Anders Carlssone857b292010-04-02 03:37:03 +00001998/// ActOnMemInitializers - Handle the member initializers for a constructor.
1999void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
2000 SourceLocation ColonLoc,
2001 MemInitTy **meminits, unsigned NumMemInits,
2002 bool AnyErrors) {
2003 if (!ConstructorDecl)
2004 return;
2005
2006 AdjustDeclIfTemplate(ConstructorDecl);
2007
2008 CXXConstructorDecl *Constructor
2009 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
2010
2011 if (!Constructor) {
2012 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2013 return;
2014 }
2015
2016 CXXBaseOrMemberInitializer **MemInits =
2017 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002018
2019 // Mapping for the duplicate initializers check.
2020 // For member initializers, this is keyed with a FieldDecl*.
2021 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002022 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002023
2024 // Mapping for the inconsistent anonymous-union initializers check.
2025 RedundantUnionMap MemberUnions;
2026
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002027 bool HadError = false;
2028 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002029 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002030
John McCall23eebd92010-04-10 09:28:51 +00002031 if (Init->isMemberInitializer()) {
2032 FieldDecl *Field = Init->getMember();
2033 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2034 CheckRedundantUnionInit(*this, Init, MemberUnions))
2035 HadError = true;
2036 } else {
2037 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2038 if (CheckRedundantInit(*this, Init, Members[Key]))
2039 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002040 }
Anders Carlssone857b292010-04-02 03:37:03 +00002041 }
2042
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002043 if (HadError)
2044 return;
2045
Anders Carlssone857b292010-04-02 03:37:03 +00002046 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002047
2048 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002049}
2050
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002051void
John McCalla6309952010-03-16 21:39:52 +00002052Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2053 CXXRecordDecl *ClassDecl) {
2054 // Ignore dependent contexts.
2055 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002056 return;
John McCall1064d7e2010-03-16 05:22:47 +00002057
2058 // FIXME: all the access-control diagnostics are positioned on the
2059 // field/base declaration. That's probably good; that said, the
2060 // user might reasonably want to know why the destructor is being
2061 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002062
Anders Carlssondee9a302009-11-17 04:44:12 +00002063 // Non-static data members.
2064 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2065 E = ClassDecl->field_end(); I != E; ++I) {
2066 FieldDecl *Field = *I;
2067
2068 QualType FieldType = Context.getBaseElementType(Field->getType());
2069
2070 const RecordType* RT = FieldType->getAs<RecordType>();
2071 if (!RT)
2072 continue;
2073
2074 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2075 if (FieldClassDecl->hasTrivialDestructor())
2076 continue;
2077
John McCall1064d7e2010-03-16 05:22:47 +00002078 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor(Context);
2079 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002080 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002081 << Field->getDeclName()
2082 << FieldType);
2083
John McCalla6309952010-03-16 21:39:52 +00002084 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002085 }
2086
John McCall1064d7e2010-03-16 05:22:47 +00002087 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2088
Anders Carlssondee9a302009-11-17 04:44:12 +00002089 // Bases.
2090 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2091 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002092 // Bases are always records in a well-formed non-dependent class.
2093 const RecordType *RT = Base->getType()->getAs<RecordType>();
2094
2095 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002096 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002097 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002098
2099 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002100 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002101 if (BaseClassDecl->hasTrivialDestructor())
2102 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002103
2104 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2105
2106 // FIXME: caret should be on the start of the class name
2107 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002108 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002109 << Base->getType()
2110 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002111
John McCalla6309952010-03-16 21:39:52 +00002112 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002113 }
2114
2115 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002116 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2117 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002118
2119 // Bases are always records in a well-formed non-dependent class.
2120 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2121
2122 // Ignore direct virtual bases.
2123 if (DirectVirtualBases.count(RT))
2124 continue;
2125
Anders Carlssondee9a302009-11-17 04:44:12 +00002126 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002127 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002128 if (BaseClassDecl->hasTrivialDestructor())
2129 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002130
2131 CXXDestructorDecl *Dtor = BaseClassDecl->getDestructor(Context);
2132 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002133 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002134 << VBase->getType());
2135
John McCalla6309952010-03-16 21:39:52 +00002136 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002137 }
2138}
2139
Fariborz Jahanianaee31ac2009-07-21 22:36:06 +00002140void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002141 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002142 return;
Mike Stump11289f42009-09-09 15:08:12 +00002143
Mike Stump11289f42009-09-09 15:08:12 +00002144 if (CXXConstructorDecl *Constructor
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002145 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002146 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002147}
2148
Mike Stump11289f42009-09-09 15:08:12 +00002149bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002150 unsigned DiagID, AbstractDiagSelID SelID,
2151 const CXXRecordDecl *CurrentRD) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002152 if (SelID == -1)
2153 return RequireNonAbstractType(Loc, T,
2154 PDiag(DiagID), CurrentRD);
2155 else
2156 return RequireNonAbstractType(Loc, T,
2157 PDiag(DiagID) << SelID, CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002158}
2159
Anders Carlssoneabf7702009-08-27 00:13:57 +00002160bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2161 const PartialDiagnostic &PD,
2162 const CXXRecordDecl *CurrentRD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002163 if (!getLangOptions().CPlusPlus)
2164 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002165
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002166 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002167 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002168 CurrentRD);
Mike Stump11289f42009-09-09 15:08:12 +00002169
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002170 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002171 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002172 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002173 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002174
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002175 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssoneabf7702009-08-27 00:13:57 +00002176 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002177 }
Mike Stump11289f42009-09-09 15:08:12 +00002178
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002179 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002180 if (!RT)
2181 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002182
John McCall67da35c2010-02-04 22:26:26 +00002183 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002184
Anders Carlssonb57738b2009-03-24 17:23:42 +00002185 if (CurrentRD && CurrentRD != RD)
2186 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002187
John McCall67da35c2010-02-04 22:26:26 +00002188 // FIXME: is this reasonable? It matches current behavior, but....
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002189 if (!RD->getDefinition())
John McCall67da35c2010-02-04 22:26:26 +00002190 return false;
2191
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002192 if (!RD->isAbstract())
2193 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002194
Anders Carlssoneabf7702009-08-27 00:13:57 +00002195 Diag(Loc, PD) << RD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002196
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002197 // Check if we've already emitted the list of pure virtual functions for this
2198 // class.
2199 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2200 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002201
Douglas Gregor4165bd62010-03-23 23:47:56 +00002202 CXXFinalOverriderMap FinalOverriders;
2203 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002204
Douglas Gregor4165bd62010-03-23 23:47:56 +00002205 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2206 MEnd = FinalOverriders.end();
2207 M != MEnd;
2208 ++M) {
2209 for (OverridingMethods::iterator SO = M->second.begin(),
2210 SOEnd = M->second.end();
2211 SO != SOEnd; ++SO) {
2212 // C++ [class.abstract]p4:
2213 // A class is abstract if it contains or inherits at least one
2214 // pure virtual function for which the final overrider is pure
2215 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002216
Douglas Gregor4165bd62010-03-23 23:47:56 +00002217 //
2218 if (SO->second.size() != 1)
2219 continue;
2220
2221 if (!SO->second.front().Method->isPure())
2222 continue;
2223
2224 Diag(SO->second.front().Method->getLocation(),
2225 diag::note_pure_virtual_function)
2226 << SO->second.front().Method->getDeclName();
2227 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002228 }
2229
2230 if (!PureVirtualClassDiagSet)
2231 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2232 PureVirtualClassDiagSet->insert(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002233
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002234 return true;
2235}
2236
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002237namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +00002238 class AbstractClassUsageDiagnoser
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002239 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
2240 Sema &SemaRef;
2241 CXXRecordDecl *AbstractClass;
Mike Stump11289f42009-09-09 15:08:12 +00002242
Anders Carlssonb57738b2009-03-24 17:23:42 +00002243 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002244 bool Invalid = false;
2245
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002246 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
2247 E = DC->decls_end(); I != E; ++I)
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002248 Invalid |= Visit(*I);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002249
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002250 return Invalid;
2251 }
Mike Stump11289f42009-09-09 15:08:12 +00002252
Anders Carlssonb57738b2009-03-24 17:23:42 +00002253 public:
2254 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
2255 : SemaRef(SemaRef), AbstractClass(ac) {
2256 Visit(SemaRef.Context.getTranslationUnitDecl());
2257 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002258
Anders Carlssonb57738b2009-03-24 17:23:42 +00002259 bool VisitFunctionDecl(const FunctionDecl *FD) {
2260 if (FD->isThisDeclarationADefinition()) {
2261 // No need to do the check if we're in a definition, because it requires
2262 // that the return/param types are complete.
Mike Stump11289f42009-09-09 15:08:12 +00002263 // because that requires
Anders Carlssonb57738b2009-03-24 17:23:42 +00002264 return VisitDeclContext(FD);
2265 }
Mike Stump11289f42009-09-09 15:08:12 +00002266
Anders Carlssonb57738b2009-03-24 17:23:42 +00002267 // Check the return type.
John McCall9dd450b2009-09-21 23:43:11 +00002268 QualType RTy = FD->getType()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00002269 bool Invalid =
Anders Carlssonb57738b2009-03-24 17:23:42 +00002270 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
2271 diag::err_abstract_type_in_decl,
2272 Sema::AbstractReturnType,
2273 AbstractClass);
2274
Mike Stump11289f42009-09-09 15:08:12 +00002275 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
Anders Carlssonb57738b2009-03-24 17:23:42 +00002276 E = FD->param_end(); I != E; ++I) {
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002277 const ParmVarDecl *VD = *I;
Mike Stump11289f42009-09-09 15:08:12 +00002278 Invalid |=
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002279 SemaRef.RequireNonAbstractType(VD->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00002280 VD->getOriginalType(),
2281 diag::err_abstract_type_in_decl,
Anders Carlssonb57738b2009-03-24 17:23:42 +00002282 Sema::AbstractParamType,
2283 AbstractClass);
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002284 }
2285
2286 return Invalid;
2287 }
Mike Stump11289f42009-09-09 15:08:12 +00002288
Anders Carlssonb57738b2009-03-24 17:23:42 +00002289 bool VisitDecl(const Decl* D) {
2290 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
2291 return VisitDeclContext(DC);
Mike Stump11289f42009-09-09 15:08:12 +00002292
Anders Carlssonb57738b2009-03-24 17:23:42 +00002293 return false;
2294 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002295 };
2296}
2297
Douglas Gregorc99f1552009-12-03 18:33:45 +00002298/// \brief Perform semantic checks on a class definition that has been
2299/// completing, introducing implicitly-declared members, checking for
2300/// abstract types, etc.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002301void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
Douglas Gregorc99f1552009-12-03 18:33:45 +00002302 if (!Record || Record->isInvalidDecl())
2303 return;
2304
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002305 if (!Record->isDependentType())
Douglas Gregorb93b6062010-04-12 17:09:20 +00002306 AddImplicitlyDeclaredMembersToClass(S, Record);
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00002307
Eli Friedman5dd02a0f2009-12-16 20:00:27 +00002308 if (Record->isInvalidDecl())
2309 return;
2310
John McCall2cb94162010-01-28 07:38:46 +00002311 // Set access bits correctly on the directly-declared conversions.
2312 UnresolvedSetImpl *Convs = Record->getConversionFunctions();
2313 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); I != E; ++I)
2314 Convs->setAccess(I, (*I)->getAccess());
2315
Douglas Gregor4165bd62010-03-23 23:47:56 +00002316 // Determine whether we need to check for final overriders. We do
2317 // this either when there are virtual base classes (in which case we
2318 // may end up finding multiple final overriders for a given virtual
2319 // function) or any of the base classes is abstract (in which case
2320 // we might detect that this class is abstract).
2321 bool CheckFinalOverriders = false;
2322 if (Record->isPolymorphic() && !Record->isInvalidDecl() &&
2323 !Record->isDependentType()) {
2324 if (Record->getNumVBases())
2325 CheckFinalOverriders = true;
2326 else if (!Record->isAbstract()) {
2327 for (CXXRecordDecl::base_class_const_iterator B = Record->bases_begin(),
2328 BEnd = Record->bases_end();
2329 B != BEnd; ++B) {
2330 CXXRecordDecl *BaseDecl
2331 = cast<CXXRecordDecl>(B->getType()->getAs<RecordType>()->getDecl());
2332 if (BaseDecl->isAbstract()) {
2333 CheckFinalOverriders = true;
2334 break;
2335 }
2336 }
2337 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002338 }
2339
Douglas Gregor4165bd62010-03-23 23:47:56 +00002340 if (CheckFinalOverriders) {
2341 CXXFinalOverriderMap FinalOverriders;
2342 Record->getFinalOverriders(FinalOverriders);
2343
2344 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2345 MEnd = FinalOverriders.end();
2346 M != MEnd; ++M) {
2347 for (OverridingMethods::iterator SO = M->second.begin(),
2348 SOEnd = M->second.end();
2349 SO != SOEnd; ++SO) {
2350 assert(SO->second.size() > 0 &&
2351 "All virtual functions have overridding virtual functions");
2352 if (SO->second.size() == 1) {
2353 // C++ [class.abstract]p4:
2354 // A class is abstract if it contains or inherits at least one
2355 // pure virtual function for which the final overrider is pure
2356 // virtual.
2357 if (SO->second.front().Method->isPure())
2358 Record->setAbstract(true);
2359 continue;
2360 }
2361
2362 // C++ [class.virtual]p2:
2363 // In a derived class, if a virtual member function of a base
2364 // class subobject has more than one final overrider the
2365 // program is ill-formed.
2366 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
2367 << (NamedDecl *)M->first << Record;
2368 Diag(M->first->getLocation(), diag::note_overridden_virtual_function);
2369 for (OverridingMethods::overriding_iterator OM = SO->second.begin(),
2370 OMEnd = SO->second.end();
2371 OM != OMEnd; ++OM)
2372 Diag(OM->Method->getLocation(), diag::note_final_overrider)
2373 << (NamedDecl *)M->first << OM->Method->getParent();
2374
2375 Record->setInvalidDecl();
2376 }
2377 }
2378 }
2379
2380 if (Record->isAbstract() && !Record->isInvalidDecl())
Douglas Gregorc99f1552009-12-03 18:33:45 +00002381 (void)AbstractClassUsageDiagnoser(*this, Record);
Douglas Gregor454a5b62010-04-15 00:00:53 +00002382
2383 // If this is not an aggregate type and has no user-declared constructor,
2384 // complain about any non-static data members of reference or const scalar
2385 // type, since they will never get initializers.
2386 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2387 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2388 bool Complained = false;
2389 for (RecordDecl::field_iterator F = Record->field_begin(),
2390 FEnd = Record->field_end();
2391 F != FEnd; ++F) {
2392 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002393 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002394 if (!Complained) {
2395 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2396 << Record->getTagKind() << Record;
2397 Complained = true;
2398 }
2399
2400 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2401 << F->getType()->isReferenceType()
2402 << F->getDeclName();
2403 }
2404 }
2405 }
Douglas Gregorc99f1552009-12-03 18:33:45 +00002406}
2407
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002408void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00002409 DeclPtrTy TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002410 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002411 SourceLocation RBrac,
2412 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002413 if (!TagDecl)
2414 return;
Mike Stump11289f42009-09-09 15:08:12 +00002415
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002416 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002417
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002418 ActOnFields(S, RLoc, TagDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00002419 (DeclPtrTy*)FieldCollector->getCurFields(),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002420 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002421
Douglas Gregorb93b6062010-04-12 17:09:20 +00002422 CheckCompletedCXXClass(S,
Douglas Gregorc99f1552009-12-03 18:33:45 +00002423 dyn_cast_or_null<CXXRecordDecl>(TagDecl.getAs<Decl>()));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002424}
2425
Douglas Gregor05379422008-11-03 17:51:48 +00002426/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2427/// special functions, such as the default constructor, copy
2428/// constructor, or destructor, to the given C++ class (C++
2429/// [special]p1). This routine can only be executed just before the
2430/// definition of the class is complete.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002431///
2432/// The scope, if provided, is the class scope.
2433void Sema::AddImplicitlyDeclaredMembersToClass(Scope *S,
2434 CXXRecordDecl *ClassDecl) {
Mike Stump11289f42009-09-09 15:08:12 +00002435 CanQualType ClassType
Douglas Gregor2211d342009-08-05 05:36:45 +00002436 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor77324f32008-11-17 14:58:09 +00002437
Sebastian Redl5068f77ac2009-05-27 22:11:52 +00002438 // FIXME: Implicit declarations have exception specifications, which are
2439 // the union of the specifications of the implicitly called functions.
2440
Douglas Gregor05379422008-11-03 17:51:48 +00002441 if (!ClassDecl->hasUserDeclaredConstructor()) {
2442 // C++ [class.ctor]p5:
2443 // A default constructor for a class X is a constructor of class X
2444 // that can be called without an argument. If there is no
2445 // user-declared constructor for class X, a default constructor is
2446 // implicitly declared. An implicitly-declared default constructor
2447 // is an inline public member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002448 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002449 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002450 CXXConstructorDecl *DefaultCon =
Douglas Gregor05379422008-11-03 17:51:48 +00002451 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002452 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002453 Context.getFunctionType(Context.VoidTy,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002454 0, 0, false, 0,
2455 /*FIXME*/false, false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002456 0, 0,
2457 FunctionType::ExtInfo()),
John McCallbcd03502009-12-07 02:54:59 +00002458 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002459 /*isExplicit=*/false,
2460 /*isInline=*/true,
2461 /*isImplicitlyDeclared=*/true);
2462 DefaultCon->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002463 DefaultCon->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002464 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregorb93b6062010-04-12 17:09:20 +00002465 if (S)
2466 PushOnScopeChains(DefaultCon, S, true);
2467 else
2468 ClassDecl->addDecl(DefaultCon);
Douglas Gregor05379422008-11-03 17:51:48 +00002469 }
2470
2471 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
2472 // C++ [class.copy]p4:
2473 // If the class definition does not explicitly declare a copy
2474 // constructor, one is declared implicitly.
2475
2476 // C++ [class.copy]p5:
2477 // The implicitly-declared copy constructor for a class X will
2478 // have the form
2479 //
2480 // X::X(const X&)
2481 //
2482 // if
2483 bool HasConstCopyConstructor = true;
2484
2485 // -- each direct or virtual base class B of X has a copy
2486 // constructor whose first parameter is of type const B& or
2487 // const volatile B&, and
2488 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2489 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
2490 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002491 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002492 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002493 = BaseClassDecl->hasConstCopyConstructor(Context);
2494 }
2495
2496 // -- for all the nonstatic data members of X that are of a
2497 // class type M (or array thereof), each such class type
2498 // has a copy constructor whose first parameter is of type
2499 // const M& or const volatile M&.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002500 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2501 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002502 ++Field) {
Douglas Gregor05379422008-11-03 17:51:48 +00002503 QualType FieldType = (*Field)->getType();
2504 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2505 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002506 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002507 const CXXRecordDecl *FieldClassDecl
Douglas Gregor05379422008-11-03 17:51:48 +00002508 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00002509 HasConstCopyConstructor
Douglas Gregor05379422008-11-03 17:51:48 +00002510 = FieldClassDecl->hasConstCopyConstructor(Context);
2511 }
2512 }
2513
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002514 // Otherwise, the implicitly declared copy constructor will have
2515 // the form
Douglas Gregor05379422008-11-03 17:51:48 +00002516 //
2517 // X::X(X&)
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002518 QualType ArgType = ClassType;
Douglas Gregor05379422008-11-03 17:51:48 +00002519 if (HasConstCopyConstructor)
2520 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002521 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor05379422008-11-03 17:51:48 +00002522
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002523 // An implicitly-declared copy constructor is an inline public
2524 // member of its class.
Mike Stump11289f42009-09-09 15:08:12 +00002525 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002526 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor05379422008-11-03 17:51:48 +00002527 CXXConstructorDecl *CopyConstructor
2528 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor77324f32008-11-17 14:58:09 +00002529 ClassDecl->getLocation(), Name,
Douglas Gregor05379422008-11-03 17:51:48 +00002530 Context.getFunctionType(Context.VoidTy,
2531 &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002532 false, 0,
2533 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002534 false, 0, 0,
2535 FunctionType::ExtInfo()),
John McCallbcd03502009-12-07 02:54:59 +00002536 /*TInfo=*/0,
Douglas Gregor05379422008-11-03 17:51:48 +00002537 /*isExplicit=*/false,
2538 /*isInline=*/true,
2539 /*isImplicitlyDeclared=*/true);
2540 CopyConstructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002541 CopyConstructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002542 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor05379422008-11-03 17:51:48 +00002543
2544 // Add the parameter to the constructor.
2545 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
2546 ClassDecl->getLocation(),
2547 /*IdentifierInfo=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002548 ArgType, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002549 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002550 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002551 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregorb93b6062010-04-12 17:09:20 +00002552 if (S)
2553 PushOnScopeChains(CopyConstructor, S, true);
2554 else
2555 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor05379422008-11-03 17:51:48 +00002556 }
2557
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002558 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2559 // Note: The following rules are largely analoguous to the copy
2560 // constructor rules. Note that virtual bases are not taken into account
2561 // for determining the argument type of the operator. Note also that
2562 // operators taking an object instead of a reference are allowed.
2563 //
2564 // C++ [class.copy]p10:
2565 // If the class definition does not explicitly declare a copy
2566 // assignment operator, one is declared implicitly.
2567 // The implicitly-defined copy assignment operator for a class X
2568 // will have the form
2569 //
2570 // X& X::operator=(const X&)
2571 //
2572 // if
2573 bool HasConstCopyAssignment = true;
2574
2575 // -- each direct base class B of X has a copy assignment operator
2576 // whose parameter is of type const B&, const volatile B& or B,
2577 // and
2578 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2579 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
Sebastian Redl1054fae2009-10-25 17:03:50 +00002580 assert(!Base->getType()->isDependentType() &&
2581 "Cannot generate implicit members for class with dependent bases.");
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002582 const CXXRecordDecl *BaseClassDecl
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002583 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002584 const CXXMethodDecl *MD = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002585 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002586 MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002587 }
2588
2589 // -- for all the nonstatic data members of X that are of a class
2590 // type M (or array thereof), each such class type has a copy
2591 // assignment operator whose parameter is of type const M&,
2592 // const volatile M& or M.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002593 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
2594 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002595 ++Field) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002596 QualType FieldType = (*Field)->getType();
2597 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2598 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002599 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002600 const CXXRecordDecl *FieldClassDecl
2601 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002602 const CXXMethodDecl *MD = 0;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002603 HasConstCopyAssignment
Fariborz Jahanianbbd5e8c2009-08-12 23:34:46 +00002604 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002605 }
2606 }
2607
2608 // Otherwise, the implicitly declared copy assignment operator will
2609 // have the form
2610 //
2611 // X& X::operator=(X&)
2612 QualType ArgType = ClassType;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002613 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002614 if (HasConstCopyAssignment)
2615 ArgType = ArgType.withConst();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00002616 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002617
2618 // An implicitly-declared copy assignment operator is an inline public
2619 // member of its class.
2620 DeclarationName Name =
2621 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2622 CXXMethodDecl *CopyAssignment =
2623 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
2624 Context.getFunctionType(RetType, &ArgType, 1,
Douglas Gregor36c569f2010-02-21 22:15:06 +00002625 false, 0,
2626 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002627 false, 0, 0,
2628 FunctionType::ExtInfo()),
Douglas Gregorc4df4072010-04-19 22:54:31 +00002629 /*TInfo=*/0, /*isStatic=*/false,
2630 /*StorageClassAsWritten=*/FunctionDecl::None,
2631 /*isInline=*/true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002632 CopyAssignment->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002633 CopyAssignment->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002634 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahaniande7d4c22009-08-12 21:14:35 +00002635 CopyAssignment->setCopyAssignment(true);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002636
2637 // Add the parameter to the operator.
2638 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
2639 ClassDecl->getLocation(),
Douglas Gregorb139cd52010-05-01 20:49:11 +00002640 /*Id=*/0,
John McCallbcd03502009-12-07 02:54:59 +00002641 ArgType, /*TInfo=*/0,
Douglas Gregorc4df4072010-04-19 22:54:31 +00002642 VarDecl::None,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002643 VarDecl::None, 0);
Douglas Gregord5058122010-02-11 01:19:42 +00002644 CopyAssignment->setParams(&FromParam, 1);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002645
2646 // Don't call addedAssignmentOperator. There is no way to distinguish an
2647 // implicit from an explicit assignment operator.
Douglas Gregorb93b6062010-04-12 17:09:20 +00002648 if (S)
2649 PushOnScopeChains(CopyAssignment, S, true);
2650 else
2651 ClassDecl->addDecl(CopyAssignment);
Eli Friedman81bce6b2009-12-02 06:59:20 +00002652 AddOverriddenMethods(ClassDecl, CopyAssignment);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002653 }
2654
Douglas Gregor1349b452008-12-15 21:24:18 +00002655 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002656 // C++ [class.dtor]p2:
2657 // If a class has no user-declared destructor, a destructor is
2658 // declared implicitly. An implicitly-declared destructor is an
2659 // inline public member of its class.
John McCall58f10c32010-03-11 09:03:00 +00002660 QualType Ty = Context.getFunctionType(Context.VoidTy,
2661 0, 0, false, 0,
2662 /*FIXME:*/false,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002663 false, 0, 0, FunctionType::ExtInfo());
John McCall58f10c32010-03-11 09:03:00 +00002664
Mike Stump11289f42009-09-09 15:08:12 +00002665 DeclarationName Name
Douglas Gregor77324f32008-11-17 14:58:09 +00002666 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Mike Stump11289f42009-09-09 15:08:12 +00002667 CXXDestructorDecl *Destructor
Douglas Gregor831c93f2008-11-05 20:51:48 +00002668 = CXXDestructorDecl::Create(Context, ClassDecl,
John McCall58f10c32010-03-11 09:03:00 +00002669 ClassDecl->getLocation(), Name, Ty,
Douglas Gregor831c93f2008-11-05 20:51:48 +00002670 /*isInline=*/true,
2671 /*isImplicitlyDeclared=*/true);
2672 Destructor->setAccess(AS_public);
Douglas Gregorf4d33272009-01-07 19:46:03 +00002673 Destructor->setImplicit();
Douglas Gregor8a273912009-07-22 18:25:24 +00002674 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregorb93b6062010-04-12 17:09:20 +00002675 if (S)
2676 PushOnScopeChains(Destructor, S, true);
2677 else
2678 ClassDecl->addDecl(Destructor);
John McCall58f10c32010-03-11 09:03:00 +00002679
2680 // This could be uniqued if it ever proves significant.
2681 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
Anders Carlsson859d7bf2009-11-26 21:25:09 +00002682
2683 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor831c93f2008-11-05 20:51:48 +00002684 }
Douglas Gregor05379422008-11-03 17:51:48 +00002685}
2686
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002687void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002688 Decl *D = TemplateD.getAs<Decl>();
2689 if (!D)
2690 return;
2691
2692 TemplateParameterList *Params = 0;
2693 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2694 Params = Template->getTemplateParameters();
2695 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2696 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2697 Params = PartialSpec->getTemplateParameters();
2698 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002699 return;
2700
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002701 for (TemplateParameterList::iterator Param = Params->begin(),
2702 ParamEnd = Params->end();
2703 Param != ParamEnd; ++Param) {
2704 NamedDecl *Named = cast<NamedDecl>(*Param);
2705 if (Named->getDeclName()) {
2706 S->AddDecl(DeclPtrTy::make(Named));
2707 IdResolver.AddDecl(Named);
2708 }
2709 }
2710}
2711
John McCall6df5fef2009-12-19 10:49:29 +00002712void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2713 if (!RecordD) return;
2714 AdjustDeclIfTemplate(RecordD);
2715 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD.getAs<Decl>());
2716 PushDeclContext(S, Record);
2717}
2718
2719void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, DeclPtrTy RecordD) {
2720 if (!RecordD) return;
2721 PopDeclContext();
2722}
2723
Douglas Gregor4d87df52008-12-16 21:30:33 +00002724/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2725/// parsing a top-level (non-nested) C++ class, and we are now
2726/// parsing those parts of the given Method declaration that could
2727/// not be parsed earlier (C++ [class.mem]p2), such as default
2728/// arguments. This action should enter the scope of the given
2729/// Method declaration as if we had just parsed the qualified method
2730/// name. However, it should not bring the parameters into scope;
2731/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002732void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002733}
2734
2735/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2736/// C++ method declaration. We're (re-)introducing the given
2737/// function parameter into scope for use in parsing later parts of
2738/// the method declaration. For example, we could see an
2739/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner83f095c2009-03-28 19:18:32 +00002740void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002741 if (!ParamD)
2742 return;
Mike Stump11289f42009-09-09 15:08:12 +00002743
Chris Lattner83f095c2009-03-28 19:18:32 +00002744 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor58354032008-12-24 00:01:03 +00002745
2746 // If this parameter has an unparsed default argument, clear it out
2747 // to make way for the parsed default argument.
2748 if (Param->hasUnparsedDefaultArg())
2749 Param->setDefaultArg(0);
2750
Chris Lattner83f095c2009-03-28 19:18:32 +00002751 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor4d87df52008-12-16 21:30:33 +00002752 if (Param->getDeclName())
2753 IdResolver.AddDecl(Param);
2754}
2755
2756/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2757/// processing the delayed method declaration for Method. The method
2758/// declaration is now considered finished. There may be a separate
2759/// ActOnStartOfFunctionDef action later (not necessarily
2760/// immediately!) for this method, if it was also defined inside the
2761/// class body.
Chris Lattner83f095c2009-03-28 19:18:32 +00002762void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002763 if (!MethodD)
2764 return;
Mike Stump11289f42009-09-09 15:08:12 +00002765
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002766 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002767
Chris Lattner83f095c2009-03-28 19:18:32 +00002768 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor4d87df52008-12-16 21:30:33 +00002769
2770 // Now that we have our default arguments, check the constructor
2771 // again. It could produce additional diagnostics or affect whether
2772 // the class has implicitly-declared destructors, among other
2773 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002774 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2775 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002776
2777 // Check the default arguments, which we may have added.
2778 if (!Method->isInvalidDecl())
2779 CheckCXXDefaultArguments(Method);
2780}
2781
Douglas Gregor831c93f2008-11-05 20:51:48 +00002782/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002783/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002784/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002785/// emit diagnostics and set the invalid bit to true. In any case, the type
2786/// will be updated to reflect a well-formed type for the constructor and
2787/// returned.
2788QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
2789 FunctionDecl::StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002790 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002791
2792 // C++ [class.ctor]p3:
2793 // A constructor shall not be virtual (10.3) or static (9.4). A
2794 // constructor can be invoked for a const, volatile or const
2795 // volatile object. A constructor shall not be declared const,
2796 // volatile, or const volatile (9.3.2).
2797 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002798 if (!D.isInvalidType())
2799 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2800 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2801 << SourceRange(D.getIdentifierLoc());
2802 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002803 }
2804 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002805 if (!D.isInvalidType())
2806 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2807 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2808 << SourceRange(D.getIdentifierLoc());
2809 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002810 SC = FunctionDecl::None;
2811 }
Mike Stump11289f42009-09-09 15:08:12 +00002812
Chris Lattner38378bf2009-04-25 08:28:21 +00002813 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2814 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002815 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002816 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2817 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002818 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002819 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2820 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002821 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002822 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2823 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002824 }
Mike Stump11289f42009-09-09 15:08:12 +00002825
Douglas Gregor831c93f2008-11-05 20:51:48 +00002826 // Rebuild the function type "R" without any type qualifiers (in
2827 // case any of the errors above fired) and with "void" as the
2828 // return type, since constructors don't have return types. We
2829 // *always* have to do this, because GetTypeForDeclarator will
2830 // put in a result type of "int" when none was specified.
John McCall9dd450b2009-09-21 23:43:11 +00002831 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002832 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2833 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002834 Proto->isVariadic(), 0,
2835 Proto->hasExceptionSpec(),
2836 Proto->hasAnyExceptionSpec(),
2837 Proto->getNumExceptions(),
2838 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002839 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002840}
2841
Douglas Gregor4d87df52008-12-16 21:30:33 +00002842/// CheckConstructor - Checks a fully-formed constructor for
2843/// well-formedness, issuing any diagnostics required. Returns true if
2844/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002845void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002846 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002847 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2848 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002849 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002850
2851 // C++ [class.copy]p3:
2852 // A declaration of a constructor for a class X is ill-formed if
2853 // its first parameter is of type (optionally cv-qualified) X and
2854 // either there are no other parameters or else all other
2855 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002856 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002857 ((Constructor->getNumParams() == 1) ||
2858 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002859 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2860 Constructor->getTemplateSpecializationKind()
2861 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002862 QualType ParamType = Constructor->getParamDecl(0)->getType();
2863 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2864 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002865 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
2866 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregora771f462010-03-31 17:46:05 +00002867 << FixItHint::CreateInsertion(ParamLoc, " const &");
Douglas Gregorffe14e32009-11-14 01:20:54 +00002868
2869 // FIXME: Rather that making the constructor invalid, we should endeavor
2870 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002871 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002872 }
2873 }
Mike Stump11289f42009-09-09 15:08:12 +00002874
John McCall43314ab2010-04-13 07:45:41 +00002875 // Notify the class that we've added a constructor. In principle we
2876 // don't need to do this for out-of-line declarations; in practice
2877 // we only instantiate the most recent declaration of a method, so
2878 // we have to call this for everything but friends.
2879 if (!Constructor->getFriendObjectKind())
2880 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002881}
2882
Anders Carlsson26a807d2009-11-30 21:24:50 +00002883/// CheckDestructor - Checks a fully-formed destructor for well-formedness,
2884/// issuing any diagnostics required. Returns true on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002885bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002886 CXXRecordDecl *RD = Destructor->getParent();
2887
2888 if (Destructor->isVirtual()) {
2889 SourceLocation Loc;
2890
2891 if (!Destructor->isImplicit())
2892 Loc = Destructor->getLocation();
2893 else
2894 Loc = RD->getLocation();
2895
2896 // If we have a virtual destructor, look up the deallocation function
2897 FunctionDecl *OperatorDelete = 0;
2898 DeclarationName Name =
2899 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002900 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002901 return true;
2902
2903 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002904 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002905
2906 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002907}
2908
Mike Stump11289f42009-09-09 15:08:12 +00002909static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002910FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2911 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2912 FTI.ArgInfo[0].Param &&
2913 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
2914}
2915
Douglas Gregor831c93f2008-11-05 20:51:48 +00002916/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2917/// the well-formednes of the destructor declarator @p D with type @p
2918/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002919/// emit diagnostics and set the declarator to invalid. Even if this happens,
2920/// will be updated to reflect a well-formed type for the destructor and
2921/// returned.
2922QualType Sema::CheckDestructorDeclarator(Declarator &D,
2923 FunctionDecl::StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002924 // C++ [class.dtor]p1:
2925 // [...] A typedef-name that names a class is a class-name
2926 // (7.1.3); however, a typedef-name that names a class shall not
2927 // be used as the identifier in the declarator for a destructor
2928 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002929 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Chris Lattner38378bf2009-04-25 08:28:21 +00002930 if (isa<TypedefType>(DeclaratorType)) {
2931 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002932 << DeclaratorType;
Chris Lattner38378bf2009-04-25 08:28:21 +00002933 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002934 }
2935
2936 // C++ [class.dtor]p2:
2937 // A destructor is used to destroy objects of its class type. A
2938 // destructor takes no parameters, and no return type can be
2939 // specified for it (not even void). The address of a destructor
2940 // shall not be taken. A destructor shall not be static. A
2941 // destructor can be invoked for a const, volatile or const
2942 // volatile object. A destructor shall not be declared const,
2943 // volatile or const volatile (9.3.2).
2944 if (SC == FunctionDecl::Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002945 if (!D.isInvalidType())
2946 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2947 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2948 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002949 SC = FunctionDecl::None;
Chris Lattner38378bf2009-04-25 08:28:21 +00002950 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002951 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002952 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002953 // Destructors don't have return types, but the parser will
2954 // happily parse something like:
2955 //
2956 // class X {
2957 // float ~X();
2958 // };
2959 //
2960 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002961 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2962 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2963 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002964 }
Mike Stump11289f42009-09-09 15:08:12 +00002965
Chris Lattner38378bf2009-04-25 08:28:21 +00002966 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2967 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002968 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002969 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2970 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002971 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002972 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2973 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002974 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002975 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2976 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002977 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002978 }
2979
2980 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002981 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002982 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2983
2984 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002985 FTI.freeArgs();
2986 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002987 }
2988
Mike Stump11289f42009-09-09 15:08:12 +00002989 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002990 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002991 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002992 D.setInvalidType();
2993 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002994
2995 // Rebuild the function type "R" without any type qualifiers or
2996 // parameters (in case any of the errors above fired) and with
2997 // "void" as the return type, since destructors don't have return
2998 // types. We *always* have to do this, because GetTypeForDeclarator
2999 // will put in a result type of "int" when none was specified.
Douglas Gregor36c569f2010-02-21 22:15:06 +00003000 // FIXME: Exceptions!
3001 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00003002 false, false, 0, 0, FunctionType::ExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00003003}
3004
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003005/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3006/// well-formednes of the conversion function declarator @p D with
3007/// type @p R. If there are any errors in the declarator, this routine
3008/// will emit diagnostics and return true. Otherwise, it will return
3009/// false. Either way, the type @p R will be updated to reflect a
3010/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003011void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003012 FunctionDecl::StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003013 // C++ [class.conv.fct]p1:
3014 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00003015 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00003016 // parameter returning conversion-type-id."
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003017 if (SC == FunctionDecl::Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003018 if (!D.isInvalidType())
3019 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
3020 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
3021 << SourceRange(D.getIdentifierLoc());
3022 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003023 SC = FunctionDecl::None;
3024 }
John McCall212fa2e2010-04-13 00:04:31 +00003025
3026 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
3027
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003028 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003029 // Conversion functions don't have return types, but the parser will
3030 // happily parse something like:
3031 //
3032 // class X {
3033 // float operator bool();
3034 // };
3035 //
3036 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003037 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3038 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3039 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003040 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003041 }
3042
John McCall212fa2e2010-04-13 00:04:31 +00003043 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3044
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003045 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003046 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003047 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3048
3049 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003050 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003051 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003052 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003053 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003054 D.setInvalidType();
3055 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003056
John McCall212fa2e2010-04-13 00:04:31 +00003057 // Diagnose "&operator bool()" and other such nonsense. This
3058 // is actually a gcc extension which we don't support.
3059 if (Proto->getResultType() != ConvType) {
3060 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3061 << Proto->getResultType();
3062 D.setInvalidType();
3063 ConvType = Proto->getResultType();
3064 }
3065
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003066 // C++ [class.conv.fct]p4:
3067 // The conversion-type-id shall not represent a function type nor
3068 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003069 if (ConvType->isArrayType()) {
3070 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3071 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003072 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003073 } else if (ConvType->isFunctionType()) {
3074 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3075 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003076 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003077 }
3078
3079 // Rebuild the function type "R" without any parameters (in case any
3080 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003081 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003082 if (D.isInvalidType()) {
3083 R = Context.getFunctionType(ConvType, 0, 0, false,
3084 Proto->getTypeQuals(),
3085 Proto->hasExceptionSpec(),
3086 Proto->hasAnyExceptionSpec(),
3087 Proto->getNumExceptions(),
3088 Proto->exception_begin(),
3089 Proto->getExtInfo());
3090 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003091
Douglas Gregor5fb53972009-01-14 15:45:31 +00003092 // C++0x explicit conversion operators.
3093 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003094 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003095 diag::warn_explicit_conversion_functions)
3096 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003097}
3098
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003099/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3100/// the declaration of the given C++ conversion function. This routine
3101/// is responsible for recording the conversion function in the C++
3102/// class, if possible.
Chris Lattner83f095c2009-03-28 19:18:32 +00003103Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003104 assert(Conversion && "Expected to receive a conversion function declaration");
3105
Douglas Gregor4287b372008-12-12 08:25:50 +00003106 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003107
3108 // Make sure we aren't redeclaring the conversion function.
3109 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003110
3111 // C++ [class.conv.fct]p1:
3112 // [...] A conversion function is never used to convert a
3113 // (possibly cv-qualified) object to the (possibly cv-qualified)
3114 // same object type (or a reference to it), to a (possibly
3115 // cv-qualified) base class of that type (or a reference to it),
3116 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003117 // FIXME: Suppress this warning if the conversion function ends up being a
3118 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003119 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003120 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003121 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003122 ConvType = ConvTypeRef->getPointeeType();
3123 if (ConvType->isRecordType()) {
3124 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3125 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003126 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003127 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003128 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003129 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003130 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003131 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003132 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003133 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003134 }
3135
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003136 if (Conversion->getPrimaryTemplate()) {
3137 // ignore specializations
3138 } else if (Conversion->getPreviousDeclaration()) {
Mike Stump11289f42009-09-09 15:08:12 +00003139 if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor133bc742010-01-11 18:53:25 +00003140 = Conversion->getDescribedFunctionTemplate()) {
3141 if (ClassDecl->replaceConversion(
3142 ConversionTemplate->getPreviousDeclaration(),
3143 ConversionTemplate))
3144 return DeclPtrTy::make(ConversionTemplate);
3145 } else if (ClassDecl->replaceConversion(Conversion->getPreviousDeclaration(),
3146 Conversion))
John McCalld14a8642009-11-21 08:51:07 +00003147 return DeclPtrTy::make(Conversion);
Douglas Gregor1dc98262008-12-26 15:00:45 +00003148 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Mike Stump11289f42009-09-09 15:08:12 +00003149 } else if (FunctionTemplateDecl *ConversionTemplate
Douglas Gregor05155d82009-08-21 23:19:43 +00003150 = Conversion->getDescribedFunctionTemplate())
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003151 ClassDecl->addConversionFunction(ConversionTemplate);
Douglas Gregorea0a0a92010-01-11 18:40:55 +00003152 else
Fariborz Jahanianedca0bc2009-09-12 19:02:34 +00003153 ClassDecl->addConversionFunction(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003154
Chris Lattner83f095c2009-03-28 19:18:32 +00003155 return DeclPtrTy::make(Conversion);
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003156}
3157
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003158//===----------------------------------------------------------------------===//
3159// Namespace Handling
3160//===----------------------------------------------------------------------===//
3161
3162/// ActOnStartNamespaceDef - This is called at the start of a namespace
3163/// definition.
Chris Lattner83f095c2009-03-28 19:18:32 +00003164Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
3165 SourceLocation IdentLoc,
3166 IdentifierInfo *II,
Anders Carlssona7bcade2010-02-07 01:09:23 +00003167 SourceLocation LBrace,
3168 AttributeList *AttrList) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003169 NamespaceDecl *Namespc =
3170 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
3171 Namespc->setLBracLoc(LBrace);
3172
3173 Scope *DeclRegionScope = NamespcScope->getParent();
3174
Anders Carlssona7bcade2010-02-07 01:09:23 +00003175 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3176
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003177 if (II) {
3178 // C++ [namespace.def]p2:
3179 // The identifier in an original-namespace-definition shall not have been
3180 // previously defined in the declarative region in which the
3181 // original-namespace-definition appears. The identifier in an
3182 // original-namespace-definition is the name of the namespace. Subsequently
3183 // in that declarative region, it is treated as an original-namespace-name.
3184
John McCall9f3059a2009-10-09 21:13:30 +00003185 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003186 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003187 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00003188
Douglas Gregor91f84212008-12-11 16:49:14 +00003189 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3190 // This is an extended namespace definition.
3191 // Attach this namespace decl to the chain of extended namespace
3192 // definitions.
3193 OrigNS->setNextNamespace(Namespc);
3194 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003195
Mike Stump11289f42009-09-09 15:08:12 +00003196 // Remove the previous declaration from the scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003197 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003198 IdResolver.RemoveDecl(OrigNS);
Chris Lattner83f095c2009-03-28 19:18:32 +00003199 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003200 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003201 } else if (PrevDecl) {
3202 // This is an invalid name redefinition.
3203 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3204 << Namespc->getDeclName();
3205 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3206 Namespc->setInvalidDecl();
3207 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003208 } else if (II->isStr("std") &&
3209 CurContext->getLookupContext()->isTranslationUnit()) {
3210 // This is the first "real" definition of the namespace "std", so update
3211 // our cache of the "std" namespace to point at this definition.
3212 if (StdNamespace) {
3213 // We had already defined a dummy namespace "std". Link this new
3214 // namespace definition to the dummy namespace "std".
3215 StdNamespace->setNextNamespace(Namespc);
3216 StdNamespace->setLocation(IdentLoc);
3217 Namespc->setOriginalNamespace(StdNamespace->getOriginalNamespace());
3218 }
3219
3220 // Make our StdNamespace cache point at the first real definition of the
3221 // "std" namespace.
3222 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003223 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003224
3225 PushOnScopeChains(Namespc, DeclRegionScope);
3226 } else {
John McCall4fa53422009-10-01 00:25:31 +00003227 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003228 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003229
3230 // Link the anonymous namespace into its parent.
3231 NamespaceDecl *PrevDecl;
3232 DeclContext *Parent = CurContext->getLookupContext();
3233 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3234 PrevDecl = TU->getAnonymousNamespace();
3235 TU->setAnonymousNamespace(Namespc);
3236 } else {
3237 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3238 PrevDecl = ND->getAnonymousNamespace();
3239 ND->setAnonymousNamespace(Namespc);
3240 }
3241
3242 // Link the anonymous namespace with its previous declaration.
3243 if (PrevDecl) {
3244 assert(PrevDecl->isAnonymousNamespace());
3245 assert(!PrevDecl->getNextNamespace());
3246 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3247 PrevDecl->setNextNamespace(Namespc);
3248 }
John McCall4fa53422009-10-01 00:25:31 +00003249
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003250 CurContext->addDecl(Namespc);
3251
John McCall4fa53422009-10-01 00:25:31 +00003252 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3253 // behaves as if it were replaced by
3254 // namespace unique { /* empty body */ }
3255 // using namespace unique;
3256 // namespace unique { namespace-body }
3257 // where all occurrences of 'unique' in a translation unit are
3258 // replaced by the same identifier and this identifier differs
3259 // from all other identifiers in the entire program.
3260
3261 // We just create the namespace with an empty name and then add an
3262 // implicit using declaration, just like the standard suggests.
3263 //
3264 // CodeGen enforces the "universally unique" aspect by giving all
3265 // declarations semantically contained within an anonymous
3266 // namespace internal linkage.
3267
John McCall0db42252009-12-16 02:06:49 +00003268 if (!PrevDecl) {
3269 UsingDirectiveDecl* UD
3270 = UsingDirectiveDecl::Create(Context, CurContext,
3271 /* 'using' */ LBrace,
3272 /* 'namespace' */ SourceLocation(),
3273 /* qualifier */ SourceRange(),
3274 /* NNS */ NULL,
3275 /* identifier */ SourceLocation(),
3276 Namespc,
3277 /* Ancestor */ CurContext);
3278 UD->setImplicit();
3279 CurContext->addDecl(UD);
3280 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003281 }
3282
3283 // Although we could have an invalid decl (i.e. the namespace name is a
3284 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003285 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3286 // for the namespace has the declarations that showed up in that particular
3287 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003288 PushDeclContext(NamespcScope, Namespc);
Chris Lattner83f095c2009-03-28 19:18:32 +00003289 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003290}
3291
Sebastian Redla6602e92009-11-23 15:34:23 +00003292/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3293/// is a namespace alias, returns the namespace it points to.
3294static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3295 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3296 return AD->getNamespace();
3297 return dyn_cast_or_null<NamespaceDecl>(D);
3298}
3299
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003300/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3301/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner83f095c2009-03-28 19:18:32 +00003302void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
3303 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003304 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3305 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3306 Namespc->setRBracLoc(RBrace);
3307 PopDeclContext();
3308}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003309
Chris Lattner83f095c2009-03-28 19:18:32 +00003310Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
3311 SourceLocation UsingLoc,
3312 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003313 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003314 SourceLocation IdentLoc,
3315 IdentifierInfo *NamespcName,
3316 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003317 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3318 assert(NamespcName && "Invalid NamespcName.");
3319 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003320 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003321
Douglas Gregor889ceb72009-02-03 19:21:40 +00003322 UsingDirectiveDecl *UDir = 0;
Douglas Gregord7c4d982008-12-30 03:27:21 +00003323
Douglas Gregor34074322009-01-14 22:20:51 +00003324 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003325 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3326 LookupParsedName(R, S, &SS);
3327 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00003328 return DeclPtrTy();
John McCall27b18f82009-11-17 02:14:36 +00003329
John McCall9f3059a2009-10-09 21:13:30 +00003330 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003331 NamedDecl *Named = R.getFoundDecl();
3332 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3333 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003334 // C++ [namespace.udir]p1:
3335 // A using-directive specifies that the names in the nominated
3336 // namespace can be used in the scope in which the
3337 // using-directive appears after the using-directive. During
3338 // unqualified name lookup (3.4.1), the names appear as if they
3339 // were declared in the nearest enclosing namespace which
3340 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003341 // namespace. [Note: in this context, "contains" means "contains
3342 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003343
3344 // Find enclosing context containing both using-directive and
3345 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003346 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003347 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3348 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3349 CommonAncestor = CommonAncestor->getParent();
3350
Sebastian Redla6602e92009-11-23 15:34:23 +00003351 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003352 SS.getRange(),
3353 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003354 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003355 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003356 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003357 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003358 }
3359
Douglas Gregor889ceb72009-02-03 19:21:40 +00003360 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003361 delete AttrList;
Chris Lattner83f095c2009-03-28 19:18:32 +00003362 return DeclPtrTy::make(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003363}
3364
3365void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3366 // If scope has associated entity, then using directive is at namespace
3367 // or translation unit scope. We add UsingDirectiveDecls, into
3368 // it's lookup structure.
3369 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003370 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003371 else
3372 // Otherwise it is block-sope. using-directives will affect lookup
3373 // only to the end of scope.
Chris Lattner83f095c2009-03-28 19:18:32 +00003374 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregord7c4d982008-12-30 03:27:21 +00003375}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003376
Douglas Gregorfec52632009-06-20 00:51:54 +00003377
3378Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003379 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003380 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003381 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003382 CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003383 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003384 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003385 bool IsTypeName,
3386 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003387 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003388
Douglas Gregor220f4272009-11-04 16:30:06 +00003389 switch (Name.getKind()) {
3390 case UnqualifiedId::IK_Identifier:
3391 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003392 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003393 case UnqualifiedId::IK_ConversionFunctionId:
3394 break;
3395
3396 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003397 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003398 // C++0x inherited constructors.
3399 if (getLangOptions().CPlusPlus0x) break;
3400
Douglas Gregor220f4272009-11-04 16:30:06 +00003401 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3402 << SS.getRange();
3403 return DeclPtrTy();
3404
3405 case UnqualifiedId::IK_DestructorName:
3406 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3407 << SS.getRange();
3408 return DeclPtrTy();
3409
3410 case UnqualifiedId::IK_TemplateId:
3411 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3412 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
3413 return DeclPtrTy();
3414 }
3415
3416 DeclarationName TargetName = GetNameFromUnqualifiedId(Name);
John McCall3969e302009-12-08 07:46:18 +00003417 if (!TargetName)
3418 return DeclPtrTy();
3419
John McCalla0097262009-12-11 02:10:03 +00003420 // Warn about using declarations.
3421 // TODO: store that the declaration was written without 'using' and
3422 // talk about access decls instead of using decls in the
3423 // diagnostics.
3424 if (!HasUsingKeyword) {
3425 UsingLoc = Name.getSourceRange().getBegin();
3426
3427 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003428 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003429 }
3430
John McCall3f746822009-11-17 05:59:44 +00003431 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003432 Name.getSourceRange().getBegin(),
John McCalle61f2ba2009-11-18 02:36:19 +00003433 TargetName, AttrList,
3434 /* IsInstantiation */ false,
3435 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003436 if (UD)
3437 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003438
Anders Carlsson696a3f12009-08-28 05:40:36 +00003439 return DeclPtrTy::make(UD);
3440}
3441
John McCall84d87672009-12-10 09:41:52 +00003442/// Determines whether to create a using shadow decl for a particular
3443/// decl, given the set of decls existing prior to this using lookup.
3444bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3445 const LookupResult &Previous) {
3446 // Diagnose finding a decl which is not from a base class of the
3447 // current class. We do this now because there are cases where this
3448 // function will silently decide not to build a shadow decl, which
3449 // will pre-empt further diagnostics.
3450 //
3451 // We don't need to do this in C++0x because we do the check once on
3452 // the qualifier.
3453 //
3454 // FIXME: diagnose the following if we care enough:
3455 // struct A { int foo; };
3456 // struct B : A { using A::foo; };
3457 // template <class T> struct C : A {};
3458 // template <class T> struct D : C<T> { using B::foo; } // <---
3459 // This is invalid (during instantiation) in C++03 because B::foo
3460 // resolves to the using decl in B, which is not a base class of D<T>.
3461 // We can't diagnose it immediately because C<T> is an unknown
3462 // specialization. The UsingShadowDecl in D<T> then points directly
3463 // to A::foo, which will look well-formed when we instantiate.
3464 // The right solution is to not collapse the shadow-decl chain.
3465 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3466 DeclContext *OrigDC = Orig->getDeclContext();
3467
3468 // Handle enums and anonymous structs.
3469 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3470 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3471 while (OrigRec->isAnonymousStructOrUnion())
3472 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3473
3474 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3475 if (OrigDC == CurContext) {
3476 Diag(Using->getLocation(),
3477 diag::err_using_decl_nested_name_specifier_is_current_class)
3478 << Using->getNestedNameRange();
3479 Diag(Orig->getLocation(), diag::note_using_decl_target);
3480 return true;
3481 }
3482
3483 Diag(Using->getNestedNameRange().getBegin(),
3484 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3485 << Using->getTargetNestedNameDecl()
3486 << cast<CXXRecordDecl>(CurContext)
3487 << Using->getNestedNameRange();
3488 Diag(Orig->getLocation(), diag::note_using_decl_target);
3489 return true;
3490 }
3491 }
3492
3493 if (Previous.empty()) return false;
3494
3495 NamedDecl *Target = Orig;
3496 if (isa<UsingShadowDecl>(Target))
3497 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3498
John McCalla17e83e2009-12-11 02:33:26 +00003499 // If the target happens to be one of the previous declarations, we
3500 // don't have a conflict.
3501 //
3502 // FIXME: but we might be increasing its access, in which case we
3503 // should redeclare it.
3504 NamedDecl *NonTag = 0, *Tag = 0;
3505 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3506 I != E; ++I) {
3507 NamedDecl *D = (*I)->getUnderlyingDecl();
3508 if (D->getCanonicalDecl() == Target->getCanonicalDecl())
3509 return false;
3510
3511 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3512 }
3513
John McCall84d87672009-12-10 09:41:52 +00003514 if (Target->isFunctionOrFunctionTemplate()) {
3515 FunctionDecl *FD;
3516 if (isa<FunctionTemplateDecl>(Target))
3517 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3518 else
3519 FD = cast<FunctionDecl>(Target);
3520
3521 NamedDecl *OldDecl = 0;
3522 switch (CheckOverload(FD, Previous, OldDecl)) {
3523 case Ovl_Overload:
3524 return false;
3525
3526 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003527 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003528 break;
3529
3530 // We found a decl with the exact signature.
3531 case Ovl_Match:
3532 if (isa<UsingShadowDecl>(OldDecl)) {
3533 // Silently ignore the possible conflict.
3534 return false;
3535 }
3536
3537 // If we're in a record, we want to hide the target, so we
3538 // return true (without a diagnostic) to tell the caller not to
3539 // build a shadow decl.
3540 if (CurContext->isRecord())
3541 return true;
3542
3543 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003544 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003545 break;
3546 }
3547
3548 Diag(Target->getLocation(), diag::note_using_decl_target);
3549 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3550 return true;
3551 }
3552
3553 // Target is not a function.
3554
John McCall84d87672009-12-10 09:41:52 +00003555 if (isa<TagDecl>(Target)) {
3556 // No conflict between a tag and a non-tag.
3557 if (!Tag) return false;
3558
John McCalle29c5cd2009-12-10 19:51:03 +00003559 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003560 Diag(Target->getLocation(), diag::note_using_decl_target);
3561 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3562 return true;
3563 }
3564
3565 // No conflict between a tag and a non-tag.
3566 if (!NonTag) return false;
3567
John McCalle29c5cd2009-12-10 19:51:03 +00003568 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003569 Diag(Target->getLocation(), diag::note_using_decl_target);
3570 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3571 return true;
3572}
3573
John McCall3f746822009-11-17 05:59:44 +00003574/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003575UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003576 UsingDecl *UD,
3577 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003578
3579 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003580 NamedDecl *Target = Orig;
3581 if (isa<UsingShadowDecl>(Target)) {
3582 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3583 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003584 }
3585
3586 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003587 = UsingShadowDecl::Create(Context, CurContext,
3588 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003589 UD->addShadowDecl(Shadow);
3590
3591 if (S)
John McCall3969e302009-12-08 07:46:18 +00003592 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003593 else
John McCall3969e302009-12-08 07:46:18 +00003594 CurContext->addDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003595 Shadow->setAccess(UD->getAccess());
John McCall3f746822009-11-17 05:59:44 +00003596
John McCallda4458e2010-03-31 01:36:47 +00003597 // Register it as a conversion if appropriate.
3598 if (Shadow->getDeclName().getNameKind()
3599 == DeclarationName::CXXConversionFunctionName)
3600 cast<CXXRecordDecl>(CurContext)->addConversionFunction(Shadow);
3601
John McCall3969e302009-12-08 07:46:18 +00003602 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3603 Shadow->setInvalidDecl();
3604
John McCall84d87672009-12-10 09:41:52 +00003605 return Shadow;
3606}
John McCall3969e302009-12-08 07:46:18 +00003607
John McCall84d87672009-12-10 09:41:52 +00003608/// Hides a using shadow declaration. This is required by the current
3609/// using-decl implementation when a resolvable using declaration in a
3610/// class is followed by a declaration which would hide or override
3611/// one or more of the using decl's targets; for example:
3612///
3613/// struct Base { void foo(int); };
3614/// struct Derived : Base {
3615/// using Base::foo;
3616/// void foo(int);
3617/// };
3618///
3619/// The governing language is C++03 [namespace.udecl]p12:
3620///
3621/// When a using-declaration brings names from a base class into a
3622/// derived class scope, member functions in the derived class
3623/// override and/or hide member functions with the same name and
3624/// parameter types in a base class (rather than conflicting).
3625///
3626/// There are two ways to implement this:
3627/// (1) optimistically create shadow decls when they're not hidden
3628/// by existing declarations, or
3629/// (2) don't create any shadow decls (or at least don't make them
3630/// visible) until we've fully parsed/instantiated the class.
3631/// The problem with (1) is that we might have to retroactively remove
3632/// a shadow decl, which requires several O(n) operations because the
3633/// decl structures are (very reasonably) not designed for removal.
3634/// (2) avoids this but is very fiddly and phase-dependent.
3635void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003636 if (Shadow->getDeclName().getNameKind() ==
3637 DeclarationName::CXXConversionFunctionName)
3638 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3639
John McCall84d87672009-12-10 09:41:52 +00003640 // Remove it from the DeclContext...
3641 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003642
John McCall84d87672009-12-10 09:41:52 +00003643 // ...and the scope, if applicable...
3644 if (S) {
3645 S->RemoveDecl(DeclPtrTy::make(static_cast<Decl*>(Shadow)));
3646 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003647 }
3648
John McCall84d87672009-12-10 09:41:52 +00003649 // ...and the using decl.
3650 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3651
3652 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003653 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003654}
3655
John McCalle61f2ba2009-11-18 02:36:19 +00003656/// Builds a using declaration.
3657///
3658/// \param IsInstantiation - Whether this call arises from an
3659/// instantiation of an unresolved using declaration. We treat
3660/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003661NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3662 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003663 CXXScopeSpec &SS,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003664 SourceLocation IdentLoc,
3665 DeclarationName Name,
3666 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003667 bool IsInstantiation,
3668 bool IsTypeName,
3669 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003670 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3671 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003672
Anders Carlssonf038fc22009-08-28 05:49:21 +00003673 // FIXME: We ignore attributes for now.
3674 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003675
Anders Carlsson59140b32009-08-28 03:16:11 +00003676 if (SS.isEmpty()) {
3677 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003678 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003679 }
Mike Stump11289f42009-09-09 15:08:12 +00003680
John McCall84d87672009-12-10 09:41:52 +00003681 // Do the redeclaration lookup in the current scope.
3682 LookupResult Previous(*this, Name, IdentLoc, LookupUsingDeclName,
3683 ForRedeclaration);
3684 Previous.setHideTags(false);
3685 if (S) {
3686 LookupName(Previous, S);
3687
3688 // It is really dumb that we have to do this.
3689 LookupResult::Filter F = Previous.makeFilter();
3690 while (F.hasNext()) {
3691 NamedDecl *D = F.next();
3692 if (!isDeclInScope(D, CurContext, S))
3693 F.erase();
3694 }
3695 F.done();
3696 } else {
3697 assert(IsInstantiation && "no scope in non-instantiation");
3698 assert(CurContext->isRecord() && "scope not record in instantiation");
3699 LookupQualifiedName(Previous, CurContext);
3700 }
3701
Mike Stump11289f42009-09-09 15:08:12 +00003702 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003703 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3704
John McCall84d87672009-12-10 09:41:52 +00003705 // Check for invalid redeclarations.
3706 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3707 return 0;
3708
3709 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003710 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3711 return 0;
3712
John McCall84c16cf2009-11-12 03:15:40 +00003713 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003714 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003715 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003716 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003717 // FIXME: not all declaration name kinds are legal here
3718 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3719 UsingLoc, TypenameLoc,
3720 SS.getRange(), NNS,
John McCalle61f2ba2009-11-18 02:36:19 +00003721 IdentLoc, Name);
John McCallb96ec562009-12-04 22:46:56 +00003722 } else {
3723 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
3724 UsingLoc, SS.getRange(), NNS,
3725 IdentLoc, Name);
John McCalle61f2ba2009-11-18 02:36:19 +00003726 }
John McCallb96ec562009-12-04 22:46:56 +00003727 } else {
3728 D = UsingDecl::Create(Context, CurContext, IdentLoc,
3729 SS.getRange(), UsingLoc, NNS, Name,
3730 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003731 }
John McCallb96ec562009-12-04 22:46:56 +00003732 D->setAccess(AS);
3733 CurContext->addDecl(D);
3734
3735 if (!LookupContext) return D;
3736 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003737
John McCall0b66eb32010-05-01 00:40:08 +00003738 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003739 UD->setInvalidDecl();
3740 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003741 }
3742
John McCall3969e302009-12-08 07:46:18 +00003743 // Look up the target name.
3744
John McCall27b18f82009-11-17 02:14:36 +00003745 LookupResult R(*this, Name, IdentLoc, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003746
John McCall3969e302009-12-08 07:46:18 +00003747 // Unlike most lookups, we don't always want to hide tag
3748 // declarations: tag names are visible through the using declaration
3749 // even if hidden by ordinary names, *except* in a dependent context
3750 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003751 if (!IsInstantiation)
3752 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003753
John McCall27b18f82009-11-17 02:14:36 +00003754 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003755
John McCall9f3059a2009-10-09 21:13:30 +00003756 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003757 Diag(IdentLoc, diag::err_no_member)
3758 << Name << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003759 UD->setInvalidDecl();
3760 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003761 }
3762
John McCallb96ec562009-12-04 22:46:56 +00003763 if (R.isAmbiguous()) {
3764 UD->setInvalidDecl();
3765 return UD;
3766 }
Mike Stump11289f42009-09-09 15:08:12 +00003767
John McCalle61f2ba2009-11-18 02:36:19 +00003768 if (IsTypeName) {
3769 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003770 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003771 Diag(IdentLoc, diag::err_using_typename_non_type);
3772 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3773 Diag((*I)->getUnderlyingDecl()->getLocation(),
3774 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003775 UD->setInvalidDecl();
3776 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003777 }
3778 } else {
3779 // If we asked for a non-typename and we got a type, error out,
3780 // but only if this is an instantiation of an unresolved using
3781 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003782 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003783 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3784 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003785 UD->setInvalidDecl();
3786 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003787 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003788 }
3789
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003790 // C++0x N2914 [namespace.udecl]p6:
3791 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003792 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003793 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3794 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003795 UD->setInvalidDecl();
3796 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003797 }
Mike Stump11289f42009-09-09 15:08:12 +00003798
John McCall84d87672009-12-10 09:41:52 +00003799 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3800 if (!CheckUsingShadowDecl(UD, *I, Previous))
3801 BuildUsingShadowDecl(S, UD, *I);
3802 }
John McCall3f746822009-11-17 05:59:44 +00003803
3804 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003805}
3806
John McCall84d87672009-12-10 09:41:52 +00003807/// Checks that the given using declaration is not an invalid
3808/// redeclaration. Note that this is checking only for the using decl
3809/// itself, not for any ill-formedness among the UsingShadowDecls.
3810bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3811 bool isTypeName,
3812 const CXXScopeSpec &SS,
3813 SourceLocation NameLoc,
3814 const LookupResult &Prev) {
3815 // C++03 [namespace.udecl]p8:
3816 // C++0x [namespace.udecl]p10:
3817 // A using-declaration is a declaration and can therefore be used
3818 // repeatedly where (and only where) multiple declarations are
3819 // allowed.
3820 // That's only in file contexts.
3821 if (CurContext->getLookupContext()->isFileContext())
3822 return false;
3823
3824 NestedNameSpecifier *Qual
3825 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3826
3827 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3828 NamedDecl *D = *I;
3829
3830 bool DTypename;
3831 NestedNameSpecifier *DQual;
3832 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3833 DTypename = UD->isTypeName();
3834 DQual = UD->getTargetNestedNameDecl();
3835 } else if (UnresolvedUsingValueDecl *UD
3836 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3837 DTypename = false;
3838 DQual = UD->getTargetNestedNameSpecifier();
3839 } else if (UnresolvedUsingTypenameDecl *UD
3840 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3841 DTypename = true;
3842 DQual = UD->getTargetNestedNameSpecifier();
3843 } else continue;
3844
3845 // using decls differ if one says 'typename' and the other doesn't.
3846 // FIXME: non-dependent using decls?
3847 if (isTypeName != DTypename) continue;
3848
3849 // using decls differ if they name different scopes (but note that
3850 // template instantiation can cause this check to trigger when it
3851 // didn't before instantiation).
3852 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3853 Context.getCanonicalNestedNameSpecifier(DQual))
3854 continue;
3855
3856 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003857 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003858 return true;
3859 }
3860
3861 return false;
3862}
3863
John McCall3969e302009-12-08 07:46:18 +00003864
John McCallb96ec562009-12-04 22:46:56 +00003865/// Checks that the given nested-name qualifier used in a using decl
3866/// in the current context is appropriately related to the current
3867/// scope. If an error is found, diagnoses it and returns true.
3868bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3869 const CXXScopeSpec &SS,
3870 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003871 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003872
John McCall3969e302009-12-08 07:46:18 +00003873 if (!CurContext->isRecord()) {
3874 // C++03 [namespace.udecl]p3:
3875 // C++0x [namespace.udecl]p8:
3876 // A using-declaration for a class member shall be a member-declaration.
3877
3878 // If we weren't able to compute a valid scope, it must be a
3879 // dependent class scope.
3880 if (!NamedContext || NamedContext->isRecord()) {
3881 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3882 << SS.getRange();
3883 return true;
3884 }
3885
3886 // Otherwise, everything is known to be fine.
3887 return false;
3888 }
3889
3890 // The current scope is a record.
3891
3892 // If the named context is dependent, we can't decide much.
3893 if (!NamedContext) {
3894 // FIXME: in C++0x, we can diagnose if we can prove that the
3895 // nested-name-specifier does not refer to a base class, which is
3896 // still possible in some cases.
3897
3898 // Otherwise we have to conservatively report that things might be
3899 // okay.
3900 return false;
3901 }
3902
3903 if (!NamedContext->isRecord()) {
3904 // Ideally this would point at the last name in the specifier,
3905 // but we don't have that level of source info.
3906 Diag(SS.getRange().getBegin(),
3907 diag::err_using_decl_nested_name_specifier_is_not_class)
3908 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3909 return true;
3910 }
3911
3912 if (getLangOptions().CPlusPlus0x) {
3913 // C++0x [namespace.udecl]p3:
3914 // In a using-declaration used as a member-declaration, the
3915 // nested-name-specifier shall name a base class of the class
3916 // being defined.
3917
3918 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3919 cast<CXXRecordDecl>(NamedContext))) {
3920 if (CurContext == NamedContext) {
3921 Diag(NameLoc,
3922 diag::err_using_decl_nested_name_specifier_is_current_class)
3923 << SS.getRange();
3924 return true;
3925 }
3926
3927 Diag(SS.getRange().getBegin(),
3928 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3929 << (NestedNameSpecifier*) SS.getScopeRep()
3930 << cast<CXXRecordDecl>(CurContext)
3931 << SS.getRange();
3932 return true;
3933 }
3934
3935 return false;
3936 }
3937
3938 // C++03 [namespace.udecl]p4:
3939 // A using-declaration used as a member-declaration shall refer
3940 // to a member of a base class of the class being defined [etc.].
3941
3942 // Salient point: SS doesn't have to name a base class as long as
3943 // lookup only finds members from base classes. Therefore we can
3944 // diagnose here only if we can prove that that can't happen,
3945 // i.e. if the class hierarchies provably don't intersect.
3946
3947 // TODO: it would be nice if "definitely valid" results were cached
3948 // in the UsingDecl and UsingShadowDecl so that these checks didn't
3949 // need to be repeated.
3950
3951 struct UserData {
3952 llvm::DenseSet<const CXXRecordDecl*> Bases;
3953
3954 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
3955 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3956 Data->Bases.insert(Base);
3957 return true;
3958 }
3959
3960 bool hasDependentBases(const CXXRecordDecl *Class) {
3961 return !Class->forallBases(collect, this);
3962 }
3963
3964 /// Returns true if the base is dependent or is one of the
3965 /// accumulated base classes.
3966 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
3967 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
3968 return !Data->Bases.count(Base);
3969 }
3970
3971 bool mightShareBases(const CXXRecordDecl *Class) {
3972 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
3973 }
3974 };
3975
3976 UserData Data;
3977
3978 // Returns false if we find a dependent base.
3979 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
3980 return false;
3981
3982 // Returns false if the class has a dependent base or if it or one
3983 // of its bases is present in the base set of the current context.
3984 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
3985 return false;
3986
3987 Diag(SS.getRange().getBegin(),
3988 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3989 << (NestedNameSpecifier*) SS.getScopeRep()
3990 << cast<CXXRecordDecl>(CurContext)
3991 << SS.getRange();
3992
3993 return true;
John McCallb96ec562009-12-04 22:46:56 +00003994}
3995
Mike Stump11289f42009-09-09 15:08:12 +00003996Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00003997 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00003998 SourceLocation AliasLoc,
3999 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004000 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004001 SourceLocation IdentLoc,
4002 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004003
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004004 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004005 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4006 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004007
Anders Carlssondca83c42009-03-28 06:23:46 +00004008 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004009 NamedDecl *PrevDecl
4010 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4011 ForRedeclaration);
4012 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4013 PrevDecl = 0;
4014
4015 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004016 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004017 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004018 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004019 // FIXME: At some point, we'll want to create the (redundant)
4020 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004021 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004022 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004023 return DeclPtrTy();
4024 }
Mike Stump11289f42009-09-09 15:08:12 +00004025
Anders Carlssondca83c42009-03-28 06:23:46 +00004026 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4027 diag::err_redefinition_different_kind;
4028 Diag(AliasLoc, DiagID) << Alias;
4029 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner83f095c2009-03-28 19:18:32 +00004030 return DeclPtrTy();
Anders Carlssondca83c42009-03-28 06:23:46 +00004031 }
4032
John McCall27b18f82009-11-17 02:14:36 +00004033 if (R.isAmbiguous())
Chris Lattner83f095c2009-03-28 19:18:32 +00004034 return DeclPtrTy();
Mike Stump11289f42009-09-09 15:08:12 +00004035
John McCall9f3059a2009-10-09 21:13:30 +00004036 if (R.empty()) {
Anders Carlssonac2c9652009-03-28 06:42:02 +00004037 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00004038 return DeclPtrTy();
Anders Carlssonac2c9652009-03-28 06:42:02 +00004039 }
Mike Stump11289f42009-09-09 15:08:12 +00004040
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004041 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004042 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4043 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004044 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004045 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004046
John McCalld8d0d432010-02-16 06:53:13 +00004047 PushOnScopeChains(AliasDecl, S);
Anders Carlssonff25fdf2009-03-28 22:58:02 +00004048 return DeclPtrTy::make(AliasDecl);
Anders Carlsson9205d552009-03-28 05:27:17 +00004049}
4050
Douglas Gregora57478e2010-05-01 15:04:51 +00004051namespace {
4052 /// \brief Scoped object used to handle the state changes required in Sema
4053 /// to implicitly define the body of a C++ member function;
4054 class ImplicitlyDefinedFunctionScope {
4055 Sema &S;
4056 DeclContext *PreviousContext;
4057
4058 public:
4059 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4060 : S(S), PreviousContext(S.CurContext)
4061 {
4062 S.CurContext = Method;
4063 S.PushFunctionScope();
4064 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4065 }
4066
4067 ~ImplicitlyDefinedFunctionScope() {
4068 S.PopExpressionEvaluationContext();
4069 S.PopFunctionOrBlockScope();
4070 S.CurContext = PreviousContext;
4071 }
4072 };
4073}
4074
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004075void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4076 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004077 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
4078 !Constructor->isUsed()) &&
4079 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004080
Anders Carlsson423f5d82010-04-23 16:04:08 +00004081 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004082 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004083
Douglas Gregora57478e2010-05-01 15:04:51 +00004084 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00004085 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false)) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004086 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004087 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004088 Constructor->setInvalidDecl();
4089 } else {
4090 Constructor->setUsed();
4091 }
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004092}
4093
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004094void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004095 CXXDestructorDecl *Destructor) {
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004096 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
4097 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004098 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004099 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004100
Douglas Gregora57478e2010-05-01 15:04:51 +00004101 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004102
John McCalla6309952010-03-16 21:39:52 +00004103 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4104 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004105
Anders Carlsson26a807d2009-11-30 21:24:50 +00004106 // FIXME: If CheckDestructor fails, we should emit a note about where the
4107 // implicit destructor was needed.
4108 if (CheckDestructor(Destructor)) {
4109 Diag(CurrentLocation, diag::note_member_synthesized_at)
4110 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4111
4112 Destructor->setInvalidDecl();
4113 return;
4114 }
4115
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004116 Destructor->setUsed();
4117}
4118
Douglas Gregorb139cd52010-05-01 20:49:11 +00004119/// \brief Builds a statement that copies the given entity from \p From to
4120/// \c To.
4121///
4122/// This routine is used to copy the members of a class with an
4123/// implicitly-declared copy assignment operator. When the entities being
4124/// copied are arrays, this routine builds for loops to copy them.
4125///
4126/// \param S The Sema object used for type-checking.
4127///
4128/// \param Loc The location where the implicit copy is being generated.
4129///
4130/// \param T The type of the expressions being copied. Both expressions must
4131/// have this type.
4132///
4133/// \param To The expression we are copying to.
4134///
4135/// \param From The expression we are copying from.
4136///
4137/// \param Depth Internal parameter recording the depth of the recursion.
4138///
4139/// \returns A statement or a loop that copies the expressions.
4140static Sema::OwningStmtResult
4141BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
4142 Sema::OwningExprResult To, Sema::OwningExprResult From,
4143 unsigned Depth = 0) {
4144 typedef Sema::OwningStmtResult OwningStmtResult;
4145 typedef Sema::OwningExprResult OwningExprResult;
4146
4147 // C++0x [class.copy]p30:
4148 // Each subobject is assigned in the manner appropriate to its type:
4149 //
4150 // - if the subobject is of class type, the copy assignment operator
4151 // for the class is used (as if by explicit qualification; that is,
4152 // ignoring any possible virtual overriding functions in more derived
4153 // classes);
4154 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4155 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4156
4157 // Look for operator=.
4158 DeclarationName Name
4159 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4160 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4161 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4162
4163 // Filter out any result that isn't a copy-assignment operator.
4164 LookupResult::Filter F = OpLookup.makeFilter();
4165 while (F.hasNext()) {
4166 NamedDecl *D = F.next();
4167 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4168 if (Method->isCopyAssignmentOperator())
4169 continue;
4170
4171 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004172 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004173 F.done();
4174
4175 // Create the nested-name-specifier that will be used to qualify the
4176 // reference to operator=; this is required to suppress the virtual
4177 // call mechanism.
4178 CXXScopeSpec SS;
4179 SS.setRange(Loc);
4180 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4181 T.getTypePtr()));
4182
4183 // Create the reference to operator=.
4184 OwningExprResult OpEqualRef
4185 = S.BuildMemberReferenceExpr(move(To), T, Loc, /*isArrow=*/false, SS,
4186 /*FirstQualifierInScope=*/0, OpLookup,
4187 /*TemplateArgs=*/0,
4188 /*SuppressQualifierCheck=*/true);
4189 if (OpEqualRef.isInvalid())
4190 return S.StmtError();
4191
4192 // Build the call to the assignment operator.
4193 Expr *FromE = From.takeAs<Expr>();
4194 OwningExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
4195 OpEqualRef.takeAs<Expr>(),
4196 Loc, &FromE, 1, 0, Loc);
4197 if (Call.isInvalid())
4198 return S.StmtError();
4199
4200 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004201 }
John McCallab8c2732010-03-16 06:11:48 +00004202
Douglas Gregorb139cd52010-05-01 20:49:11 +00004203 // - if the subobject is of scalar type, the built-in assignment
4204 // operator is used.
4205 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4206 if (!ArrayTy) {
4207 OwningExprResult Assignment = S.CreateBuiltinBinOp(Loc,
4208 BinaryOperator::Assign,
4209 To.takeAs<Expr>(),
4210 From.takeAs<Expr>());
4211 if (Assignment.isInvalid())
4212 return S.StmtError();
4213
4214 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004215 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004216
4217 // - if the subobject is an array, each element is assigned, in the
4218 // manner appropriate to the element type;
4219
4220 // Construct a loop over the array bounds, e.g.,
4221 //
4222 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4223 //
4224 // that will copy each of the array elements.
4225 QualType SizeType = S.Context.getSizeType();
4226
4227 // Create the iteration variable.
4228 IdentifierInfo *IterationVarName = 0;
4229 {
4230 llvm::SmallString<8> Str;
4231 llvm::raw_svector_ostream OS(Str);
4232 OS << "__i" << Depth;
4233 IterationVarName = &S.Context.Idents.get(OS.str());
4234 }
4235 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4236 IterationVarName, SizeType,
4237 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
4238 VarDecl::None, VarDecl::None);
4239
4240 // Initialize the iteration variable to zero.
4241 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
4242 IterationVar->setInit(new (S.Context) IntegerLiteral(Zero, SizeType, Loc));
4243
4244 // Create a reference to the iteration variable; we'll use this several
4245 // times throughout.
4246 Expr *IterationVarRef
4247 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4248 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4249
4250 // Create the DeclStmt that holds the iteration variable.
4251 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4252
4253 // Create the comparison against the array bound.
4254 llvm::APInt Upper = ArrayTy->getSize();
4255 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
4256 OwningExprResult Comparison
4257 = S.Owned(new (S.Context) BinaryOperator(IterationVarRef->Retain(),
4258 new (S.Context) IntegerLiteral(Upper, SizeType, Loc),
4259 BinaryOperator::NE, S.Context.BoolTy, Loc));
4260
4261 // Create the pre-increment of the iteration variable.
4262 OwningExprResult Increment
4263 = S.Owned(new (S.Context) UnaryOperator(IterationVarRef->Retain(),
4264 UnaryOperator::PreInc,
4265 SizeType, Loc));
4266
4267 // Subscript the "from" and "to" expressions with the iteration variable.
4268 From = S.CreateBuiltinArraySubscriptExpr(move(From), Loc,
4269 S.Owned(IterationVarRef->Retain()),
4270 Loc);
4271 To = S.CreateBuiltinArraySubscriptExpr(move(To), Loc,
4272 S.Owned(IterationVarRef->Retain()),
4273 Loc);
4274 assert(!From.isInvalid() && "Builtin subscripting can't fail!");
4275 assert(!To.isInvalid() && "Builtin subscripting can't fail!");
4276
4277 // Build the copy for an individual element of the array.
4278 OwningStmtResult Copy = BuildSingleCopyAssign(S, Loc,
4279 ArrayTy->getElementType(),
4280 move(To), move(From), Depth+1);
4281 if (Copy.isInvalid()) {
4282 InitStmt->Destroy(S.Context);
4283 return S.StmtError();
4284 }
4285
4286 // Construct the loop that copies all elements of this array.
4287 return S.ActOnForStmt(Loc, Loc, S.Owned(InitStmt),
4288 S.MakeFullExpr(Comparison),
4289 Sema::DeclPtrTy(),
4290 S.MakeFullExpr(Increment),
4291 Loc, move(Copy));
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004292}
4293
Douglas Gregorb139cd52010-05-01 20:49:11 +00004294void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4295 CXXMethodDecl *CopyAssignOperator) {
4296 assert((CopyAssignOperator->isImplicit() &&
4297 CopyAssignOperator->isOverloadedOperator() &&
4298 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
4299 !CopyAssignOperator->isUsed()) &&
4300 "DefineImplicitCopyAssignment called for wrong function");
4301
4302 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4303
4304 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4305 CopyAssignOperator->setInvalidDecl();
4306 return;
4307 }
4308
4309 CopyAssignOperator->setUsed();
4310
4311 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
4312
4313 // C++0x [class.copy]p30:
4314 // The implicitly-defined or explicitly-defaulted copy assignment operator
4315 // for a non-union class X performs memberwise copy assignment of its
4316 // subobjects. The direct base classes of X are assigned first, in the
4317 // order of their declaration in the base-specifier-list, and then the
4318 // immediate non-static data members of X are assigned, in the order in
4319 // which they were declared in the class definition.
4320
4321 // The statements that form the synthesized function body.
4322 ASTOwningVector<&ActionBase::DeleteStmt> Statements(*this);
4323
4324 // The parameter for the "other" object, which we are copying from.
4325 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4326 Qualifiers OtherQuals = Other->getType().getQualifiers();
4327 QualType OtherRefType = Other->getType();
4328 if (const LValueReferenceType *OtherRef
4329 = OtherRefType->getAs<LValueReferenceType>()) {
4330 OtherRefType = OtherRef->getPointeeType();
4331 OtherQuals = OtherRefType.getQualifiers();
4332 }
4333
4334 // Our location for everything implicitly-generated.
4335 SourceLocation Loc = CopyAssignOperator->getLocation();
4336
4337 // Construct a reference to the "other" object. We'll be using this
4338 // throughout the generated ASTs.
4339 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4340 assert(OtherRef && "Reference to parameter cannot fail!");
4341
4342 // Construct the "this" pointer. We'll be using this throughout the generated
4343 // ASTs.
4344 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4345 assert(This && "Reference to this cannot fail!");
4346
4347 // Assign base classes.
4348 bool Invalid = false;
4349 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4350 E = ClassDecl->bases_end(); Base != E; ++Base) {
4351 // Form the assignment:
4352 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4353 QualType BaseType = Base->getType().getUnqualifiedType();
4354 CXXRecordDecl *BaseClassDecl = 0;
4355 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4356 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4357 else {
4358 Invalid = true;
4359 continue;
4360 }
4361
4362 // Construct the "from" expression, which is an implicit cast to the
4363 // appropriately-qualified base type.
4364 Expr *From = OtherRef->Retain();
4365 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
4366 CastExpr::CK_UncheckedDerivedToBase, /*isLvalue=*/true,
4367 CXXBaseSpecifierArray(Base));
4368
4369 // Dereference "this".
4370 OwningExprResult To = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4371 Owned(This->Retain()));
4372
4373 // Implicitly cast "this" to the appropriately-qualified base type.
4374 Expr *ToE = To.takeAs<Expr>();
4375 ImpCastExprToType(ToE,
4376 Context.getCVRQualifiedType(BaseType,
4377 CopyAssignOperator->getTypeQualifiers()),
4378 CastExpr::CK_UncheckedDerivedToBase,
4379 /*isLvalue=*/true, CXXBaseSpecifierArray(Base));
4380 To = Owned(ToE);
4381
4382 // Build the copy.
4383 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
4384 move(To), Owned(From));
4385 if (Copy.isInvalid()) {
4386 Invalid = true;
4387 continue;
4388 }
4389
4390 // Success! Record the copy.
4391 Statements.push_back(Copy.takeAs<Expr>());
4392 }
4393
4394 // \brief Reference to the __builtin_memcpy function.
4395 Expr *BuiltinMemCpyRef = 0;
4396
4397 // Assign non-static members.
4398 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4399 FieldEnd = ClassDecl->field_end();
4400 Field != FieldEnd; ++Field) {
4401 // Check for members of reference type; we can't copy those.
4402 if (Field->getType()->isReferenceType()) {
4403 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4404 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4405 Diag(Field->getLocation(), diag::note_declared_at);
4406 Diag(Loc, diag::note_first_required_here);
4407 Invalid = true;
4408 continue;
4409 }
4410
4411 // Check for members of const-qualified, non-class type.
4412 QualType BaseType = Context.getBaseElementType(Field->getType());
4413 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4414 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4415 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4416 Diag(Field->getLocation(), diag::note_declared_at);
4417 Diag(Loc, diag::note_first_required_here);
4418 Invalid = true;
4419 continue;
4420 }
4421
4422 QualType FieldType = Field->getType().getNonReferenceType();
4423
4424 // Build references to the field in the object we're copying from and to.
4425 CXXScopeSpec SS; // Intentionally empty
4426 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4427 LookupMemberName);
4428 MemberLookup.addDecl(*Field);
4429 MemberLookup.resolveKind();
4430 OwningExprResult From = BuildMemberReferenceExpr(Owned(OtherRef->Retain()),
4431 OtherRefType,
4432 Loc, /*IsArrow=*/false,
4433 SS, 0, MemberLookup, 0);
4434 OwningExprResult To = BuildMemberReferenceExpr(Owned(This->Retain()),
4435 This->getType(),
4436 Loc, /*IsArrow=*/true,
4437 SS, 0, MemberLookup, 0);
4438 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4439 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4440
4441 // If the field should be copied with __builtin_memcpy rather than via
4442 // explicit assignments, do so. This optimization only applies for arrays
4443 // of scalars and arrays of class type with trivial copy-assignment
4444 // operators.
4445 if (FieldType->isArrayType() &&
4446 (!BaseType->isRecordType() ||
4447 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4448 ->hasTrivialCopyAssignment())) {
4449 // Compute the size of the memory buffer to be copied.
4450 QualType SizeType = Context.getSizeType();
4451 llvm::APInt Size(Context.getTypeSize(SizeType),
4452 Context.getTypeSizeInChars(BaseType).getQuantity());
4453 for (const ConstantArrayType *Array
4454 = Context.getAsConstantArrayType(FieldType);
4455 Array;
4456 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4457 llvm::APInt ArraySize = Array->getSize();
4458 ArraySize.zextOrTrunc(Size.getBitWidth());
4459 Size *= ArraySize;
4460 }
4461
4462 // Take the address of the field references for "from" and "to".
4463 From = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(From));
4464 To = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(To));
4465
4466 // Create a reference to the __builtin_memcpy builtin function.
4467 if (!BuiltinMemCpyRef) {
4468 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
4469 LookupOrdinaryName);
4470 LookupName(R, TUScope, true);
4471
4472 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
4473 if (!BuiltinMemCpy) {
4474 // Something went horribly wrong earlier, and we will have complained
4475 // about it.
4476 Invalid = true;
4477 continue;
4478 }
4479
4480 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
4481 BuiltinMemCpy->getType(),
4482 Loc, 0).takeAs<Expr>();
4483 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
4484 }
4485
4486 ASTOwningVector<&ActionBase::DeleteExpr> CallArgs(*this);
4487 CallArgs.push_back(To.takeAs<Expr>());
4488 CallArgs.push_back(From.takeAs<Expr>());
4489 CallArgs.push_back(new (Context) IntegerLiteral(Size, SizeType, Loc));
4490 llvm::SmallVector<SourceLocation, 4> Commas; // FIXME: Silly
4491 Commas.push_back(Loc);
4492 Commas.push_back(Loc);
4493 OwningExprResult Call = ActOnCallExpr(/*Scope=*/0,
4494 Owned(BuiltinMemCpyRef->Retain()),
4495 Loc, move_arg(CallArgs),
4496 Commas.data(), Loc);
4497 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
4498 Statements.push_back(Call.takeAs<Expr>());
4499 continue;
4500 }
4501
4502 // Build the copy of this field.
4503 OwningStmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
4504 move(To), move(From));
4505 if (Copy.isInvalid()) {
4506 Invalid = true;
4507 continue;
4508 }
4509
4510 // Success! Record the copy.
4511 Statements.push_back(Copy.takeAs<Stmt>());
4512 }
4513
4514 if (!Invalid) {
4515 // Add a "return *this;"
4516 OwningExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UnaryOperator::Deref,
4517 Owned(This->Retain()));
4518
4519 OwningStmtResult Return = ActOnReturnStmt(Loc, move(ThisObj));
4520 if (Return.isInvalid())
4521 Invalid = true;
4522 else {
4523 Statements.push_back(Return.takeAs<Stmt>());
4524 }
4525 }
4526
4527 if (Invalid) {
4528 CopyAssignOperator->setInvalidDecl();
4529 return;
4530 }
4531
4532 OwningStmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
4533 /*isStmtExpr=*/false);
4534 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
4535 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004536}
4537
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004538void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
4539 CXXConstructorDecl *CopyConstructor,
4540 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00004541 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00004542 CopyConstructor->isCopyConstructor(TypeQuals) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004543 !CopyConstructor->isUsed()) &&
4544 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004545
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00004546 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004547 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004548
Douglas Gregora57478e2010-05-01 15:04:51 +00004549 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004550
Anders Carlsson79111502010-05-01 16:39:01 +00004551 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false)) {
4552 Diag(CurrentLocation, diag::note_member_synthesized_at)
4553 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
4554 CopyConstructor->setInvalidDecl();
4555 } else {
4556 CopyConstructor->setUsed();
Anders Carlsson53e1ba92010-04-25 00:52:09 +00004557 }
Anders Carlsson79111502010-05-01 16:39:01 +00004558
4559 // FIXME: Once SetBaseOrMemberInitializers can handle copy initialization of
4560 // fields, this code below should be removed.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004561 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4562 FieldEnd = ClassDecl->field_end();
4563 Field != FieldEnd; ++Field) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004564 QualType FieldType = Context.getCanonicalType((*Field)->getType());
4565 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
4566 FieldType = Array->getElementType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004567 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004568 CXXRecordDecl *FieldClassDecl
4569 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004570 if (CXXConstructorDecl *FieldCopyCtor =
John McCallab8c2732010-03-16 06:11:48 +00004571 FieldClassDecl->getCopyConstructor(Context, TypeQuals)) {
4572 CheckDirectMemberAccess(Field->getLocation(),
4573 FieldCopyCtor,
Douglas Gregor89336232010-03-29 23:34:08 +00004574 PDiag(diag::err_access_copy_field)
John McCallab8c2732010-03-16 06:11:48 +00004575 << Field->getDeclName() << Field->getType());
4576
Fariborz Jahaniana83edb02009-06-23 23:42:10 +00004577 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
John McCallab8c2732010-03-16 06:11:48 +00004578 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004579 }
4580 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00004581}
4582
Anders Carlsson6eb55572009-08-25 05:12:04 +00004583Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004584Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00004585 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004586 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004587 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004588 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson250aada2009-08-16 05:13:48 +00004589 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00004590
Douglas Gregor45cf7e32010-04-02 18:24:57 +00004591 // C++0x [class.copy]p34:
4592 // When certain criteria are met, an implementation is allowed to
4593 // omit the copy/move construction of a class object, even if the
4594 // copy/move constructor and/or destructor for the object have
4595 // side effects. [...]
4596 // - when a temporary class object that has not been bound to a
4597 // reference (12.2) would be copied/moved to a class object
4598 // with the same cv-unqualified type, the copy/move operation
4599 // can be omitted by constructing the temporary object
4600 // directly into the target of the omitted copy/move
4601 if (Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
4602 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
4603 Elidable = SubExpr->isTemporaryObject() &&
4604 Context.hasSameUnqualifiedType(SubExpr->getType(),
4605 Context.getTypeDeclType(Constructor->getParent()));
Anders Carlsson250aada2009-08-16 05:13:48 +00004606 }
Mike Stump11289f42009-09-09 15:08:12 +00004607
4608 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004609 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004610 ConstructKind);
Anders Carlsson250aada2009-08-16 05:13:48 +00004611}
4612
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004613/// BuildCXXConstructExpr - Creates a complete call to a constructor,
4614/// including handling of its default argument expressions.
Anders Carlsson6eb55572009-08-25 05:12:04 +00004615Sema::OwningExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00004616Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
4617 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004618 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004619 bool RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004620 CXXConstructExpr::ConstructionKind ConstructKind) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004621 unsigned NumExprs = ExprArgs.size();
4622 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00004623
Douglas Gregor27381f32009-11-23 12:27:39 +00004624 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004625 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00004626 Constructor, Elidable, Exprs, NumExprs,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00004627 RequiresZeroInit, ConstructKind));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004628}
4629
Mike Stump11289f42009-09-09 15:08:12 +00004630bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00004631 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004632 MultiExprArg Exprs) {
Mike Stump11289f42009-09-09 15:08:12 +00004633 OwningExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00004634 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00004635 move(Exprs));
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004636 if (TempResult.isInvalid())
4637 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004638
Anders Carlsson6eb55572009-08-25 05:12:04 +00004639 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00004640 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00004641 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00004642 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00004643
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00004644 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00004645}
4646
John McCall03c48482010-02-02 09:10:11 +00004647void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
4648 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00004649 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
4650 !ClassDecl->hasTrivialDestructor()) {
John McCall6781b052010-02-02 08:45:54 +00004651 CXXDestructorDecl *Destructor = ClassDecl->getDestructor(Context);
4652 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00004653 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00004654 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00004655 << VD->getDeclName()
4656 << VD->getType());
John McCall6781b052010-02-02 08:45:54 +00004657 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004658}
4659
Mike Stump11289f42009-09-09 15:08:12 +00004660/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004661/// ActOnDeclarator, when a C++ direct initializer is present.
4662/// e.g: "int x(1);"
Chris Lattner83f095c2009-03-28 19:18:32 +00004663void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
4664 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00004665 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004666 SourceLocation *CommaLocs,
4667 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00004668 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Chris Lattner83f095c2009-03-28 19:18:32 +00004669 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004670
4671 // If there is no declaration, there was an error parsing it. Just ignore
4672 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00004673 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004674 return;
Mike Stump11289f42009-09-09 15:08:12 +00004675
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004676 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
4677 if (!VDecl) {
4678 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
4679 RealDecl->setInvalidDecl();
4680 return;
4681 }
4682
Douglas Gregor402250f2009-08-26 21:14:46 +00004683 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004684 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004685 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
4686 //
4687 // Clients that want to distinguish between the two forms, can check for
4688 // direct initializer using VarDecl::hasCXXDirectInitializer().
4689 // A major benefit is that clients that don't particularly care about which
4690 // exactly form was it (like the CodeGen) can handle both cases without
4691 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004692
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004693 // C++ 8.5p11:
4694 // The form of initialization (using parentheses or '=') is generally
4695 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004696 // class type.
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004697 QualType DeclInitType = VDecl->getType();
4698 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
Fariborz Jahaniand264ee02009-10-28 19:04:36 +00004699 DeclInitType = Context.getBaseElementType(Array);
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004700
Douglas Gregor50dc2192010-02-11 22:55:30 +00004701 if (!VDecl->getType()->isDependentType() &&
4702 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00004703 diag::err_typecheck_decl_incomplete_type)) {
4704 VDecl->setInvalidDecl();
4705 return;
4706 }
4707
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004708 // The variable can not have an abstract class type.
4709 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
4710 diag::err_abstract_type_in_decl,
4711 AbstractVariableType))
4712 VDecl->setInvalidDecl();
4713
Sebastian Redl5ca79842010-02-01 20:16:42 +00004714 const VarDecl *Def;
4715 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004716 Diag(VDecl->getLocation(), diag::err_redefinition)
4717 << VDecl->getDeclName();
4718 Diag(Def->getLocation(), diag::note_previous_definition);
4719 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00004720 return;
4721 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00004722
4723 // If either the declaration has a dependent type or if any of the
4724 // expressions is type-dependent, we represent the initialization
4725 // via a ParenListExpr for later use during template instantiation.
4726 if (VDecl->getType()->isDependentType() ||
4727 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
4728 // Let clients know that initialization was done with a direct initializer.
4729 VDecl->setCXXDirectInitializer(true);
4730
4731 // Store the initialization expressions as a ParenListExpr.
4732 unsigned NumExprs = Exprs.size();
4733 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
4734 (Expr **)Exprs.release(),
4735 NumExprs, RParenLoc));
4736 return;
4737 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004738
4739 // Capture the variable that is being initialized and the style of
4740 // initialization.
4741 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
4742
4743 // FIXME: Poor source location information.
4744 InitializationKind Kind
4745 = InitializationKind::CreateDirect(VDecl->getLocation(),
4746 LParenLoc, RParenLoc);
4747
4748 InitializationSequence InitSeq(*this, Entity, Kind,
4749 (Expr**)Exprs.get(), Exprs.size());
4750 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
4751 if (Result.isInvalid()) {
4752 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004753 return;
4754 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004755
4756 Result = MaybeCreateCXXExprWithTemporaries(move(Result));
Douglas Gregord5058122010-02-11 01:19:42 +00004757 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004758 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00004759
John McCall03c48482010-02-02 09:10:11 +00004760 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
4761 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00004762}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004763
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004764/// \brief Given a constructor and the set of arguments provided for the
4765/// constructor, convert the arguments and add any required default arguments
4766/// to form a proper call to this constructor.
4767///
4768/// \returns true if an error occurred, false otherwise.
4769bool
4770Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
4771 MultiExprArg ArgsPtr,
4772 SourceLocation Loc,
4773 ASTOwningVector<&ActionBase::DeleteExpr> &ConvertedArgs) {
4774 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
4775 unsigned NumArgs = ArgsPtr.size();
4776 Expr **Args = (Expr **)ArgsPtr.get();
4777
4778 const FunctionProtoType *Proto
4779 = Constructor->getType()->getAs<FunctionProtoType>();
4780 assert(Proto && "Constructor without a prototype?");
4781 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004782
4783 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004784 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004785 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004786 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00004787 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00004788
4789 VariadicCallType CallType =
4790 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4791 llvm::SmallVector<Expr *, 8> AllArgs;
4792 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
4793 Proto, 0, Args, NumArgs, AllArgs,
4794 CallType);
4795 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
4796 ConvertedArgs.push_back(AllArgs[i]);
4797 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00004798}
4799
Anders Carlssone363c8e2009-12-12 00:32:00 +00004800static inline bool
4801CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
4802 const FunctionDecl *FnDecl) {
4803 const DeclContext *DC = FnDecl->getDeclContext()->getLookupContext();
4804 if (isa<NamespaceDecl>(DC)) {
4805 return SemaRef.Diag(FnDecl->getLocation(),
4806 diag::err_operator_new_delete_declared_in_namespace)
4807 << FnDecl->getDeclName();
4808 }
4809
4810 if (isa<TranslationUnitDecl>(DC) &&
4811 FnDecl->getStorageClass() == FunctionDecl::Static) {
4812 return SemaRef.Diag(FnDecl->getLocation(),
4813 diag::err_operator_new_delete_declared_static)
4814 << FnDecl->getDeclName();
4815 }
4816
Anders Carlsson60659a82009-12-12 02:43:16 +00004817 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00004818}
4819
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004820static inline bool
4821CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
4822 CanQualType ExpectedResultType,
4823 CanQualType ExpectedFirstParamType,
4824 unsigned DependentParamTypeDiag,
4825 unsigned InvalidParamTypeDiag) {
4826 QualType ResultType =
4827 FnDecl->getType()->getAs<FunctionType>()->getResultType();
4828
4829 // Check that the result type is not dependent.
4830 if (ResultType->isDependentType())
4831 return SemaRef.Diag(FnDecl->getLocation(),
4832 diag::err_operator_new_delete_dependent_result_type)
4833 << FnDecl->getDeclName() << ExpectedResultType;
4834
4835 // Check that the result type is what we expect.
4836 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
4837 return SemaRef.Diag(FnDecl->getLocation(),
4838 diag::err_operator_new_delete_invalid_result_type)
4839 << FnDecl->getDeclName() << ExpectedResultType;
4840
4841 // A function template must have at least 2 parameters.
4842 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
4843 return SemaRef.Diag(FnDecl->getLocation(),
4844 diag::err_operator_new_delete_template_too_few_parameters)
4845 << FnDecl->getDeclName();
4846
4847 // The function decl must have at least 1 parameter.
4848 if (FnDecl->getNumParams() == 0)
4849 return SemaRef.Diag(FnDecl->getLocation(),
4850 diag::err_operator_new_delete_too_few_parameters)
4851 << FnDecl->getDeclName();
4852
4853 // Check the the first parameter type is not dependent.
4854 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4855 if (FirstParamType->isDependentType())
4856 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
4857 << FnDecl->getDeclName() << ExpectedFirstParamType;
4858
4859 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00004860 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004861 ExpectedFirstParamType)
4862 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
4863 << FnDecl->getDeclName() << ExpectedFirstParamType;
4864
4865 return false;
4866}
4867
Anders Carlsson12308f42009-12-11 23:23:22 +00004868static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004869CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00004870 // C++ [basic.stc.dynamic.allocation]p1:
4871 // A program is ill-formed if an allocation function is declared in a
4872 // namespace scope other than global scope or declared static in global
4873 // scope.
4874 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4875 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004876
4877 CanQualType SizeTy =
4878 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
4879
4880 // C++ [basic.stc.dynamic.allocation]p1:
4881 // The return type shall be void*. The first parameter shall have type
4882 // std::size_t.
4883 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
4884 SizeTy,
4885 diag::err_operator_new_dependent_param_type,
4886 diag::err_operator_new_param_type))
4887 return true;
4888
4889 // C++ [basic.stc.dynamic.allocation]p1:
4890 // The first parameter shall not have an associated default argument.
4891 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00004892 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004893 diag::err_operator_new_default_arg)
4894 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
4895
4896 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00004897}
4898
4899static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00004900CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
4901 // C++ [basic.stc.dynamic.deallocation]p1:
4902 // A program is ill-formed if deallocation functions are declared in a
4903 // namespace scope other than global scope or declared static in global
4904 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00004905 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
4906 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004907
4908 // C++ [basic.stc.dynamic.deallocation]p2:
4909 // Each deallocation function shall return void and its first parameter
4910 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004911 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
4912 SemaRef.Context.VoidPtrTy,
4913 diag::err_operator_delete_dependent_param_type,
4914 diag::err_operator_delete_param_type))
4915 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00004916
Anders Carlssonc0b2ce12009-12-12 00:16:02 +00004917 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
4918 if (FirstParamType->isDependentType())
4919 return SemaRef.Diag(FnDecl->getLocation(),
4920 diag::err_operator_delete_dependent_param_type)
4921 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
4922
4923 if (SemaRef.Context.getCanonicalType(FirstParamType) !=
4924 SemaRef.Context.VoidPtrTy)
Anders Carlsson12308f42009-12-11 23:23:22 +00004925 return SemaRef.Diag(FnDecl->getLocation(),
4926 diag::err_operator_delete_param_type)
4927 << FnDecl->getDeclName() << SemaRef.Context.VoidPtrTy;
Anders Carlsson12308f42009-12-11 23:23:22 +00004928
4929 return false;
4930}
4931
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004932/// CheckOverloadedOperatorDeclaration - Check whether the declaration
4933/// of this overloaded operator is well-formed. If so, returns false;
4934/// otherwise, emits appropriate diagnostics and returns true.
4935bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00004936 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004937 "Expected an overloaded operator declaration");
4938
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004939 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
4940
Mike Stump11289f42009-09-09 15:08:12 +00004941 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004942 // The allocation and deallocation functions, operator new,
4943 // operator new[], operator delete and operator delete[], are
4944 // described completely in 3.7.3. The attributes and restrictions
4945 // found in the rest of this subclause do not apply to them unless
4946 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00004947 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00004948 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00004949
Anders Carlsson22f443f2009-12-12 00:26:23 +00004950 if (Op == OO_New || Op == OO_Array_New)
4951 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004952
4953 // C++ [over.oper]p6:
4954 // An operator function shall either be a non-static member
4955 // function or be a non-member function and have at least one
4956 // parameter whose type is a class, a reference to a class, an
4957 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00004958 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
4959 if (MethodDecl->isStatic())
4960 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004961 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004962 } else {
4963 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00004964 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
4965 ParamEnd = FnDecl->param_end();
4966 Param != ParamEnd; ++Param) {
4967 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00004968 if (ParamType->isDependentType() || ParamType->isRecordType() ||
4969 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004970 ClassOrEnumParam = true;
4971 break;
4972 }
4973 }
4974
Douglas Gregord69246b2008-11-17 16:14:12 +00004975 if (!ClassOrEnumParam)
4976 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00004977 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004978 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004979 }
4980
4981 // C++ [over.oper]p8:
4982 // An operator function cannot have default arguments (8.3.6),
4983 // except where explicitly stated below.
4984 //
Mike Stump11289f42009-09-09 15:08:12 +00004985 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004986 // (C++ [over.call]p1).
4987 if (Op != OO_Call) {
4988 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
4989 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004990 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00004991 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00004992 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00004993 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00004994 }
4995 }
4996
Douglas Gregor6cf08062008-11-10 13:38:07 +00004997 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
4998 { false, false, false }
4999#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5000 , { Unary, Binary, MemberOnly }
5001#include "clang/Basic/OperatorKinds.def"
5002 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005003
Douglas Gregor6cf08062008-11-10 13:38:07 +00005004 bool CanBeUnaryOperator = OperatorUses[Op][0];
5005 bool CanBeBinaryOperator = OperatorUses[Op][1];
5006 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005007
5008 // C++ [over.oper]p8:
5009 // [...] Operator functions cannot have more or fewer parameters
5010 // than the number required for the corresponding operator, as
5011 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005012 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005013 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005014 if (Op != OO_Call &&
5015 ((NumParams == 1 && !CanBeUnaryOperator) ||
5016 (NumParams == 2 && !CanBeBinaryOperator) ||
5017 (NumParams < 1) || (NumParams > 2))) {
5018 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005019 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005020 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005021 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005022 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005023 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005024 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005025 assert(CanBeBinaryOperator &&
5026 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005027 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005028 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005029
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005030 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005031 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005032 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005033
Douglas Gregord69246b2008-11-17 16:14:12 +00005034 // Overloaded operators other than operator() cannot be variadic.
5035 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005036 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005037 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005038 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005039 }
5040
5041 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005042 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5043 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005044 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005045 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005046 }
5047
5048 // C++ [over.inc]p1:
5049 // The user-defined function called operator++ implements the
5050 // prefix and postfix ++ operator. If this function is a member
5051 // function with no parameters, or a non-member function with one
5052 // parameter of class or enumeration type, it defines the prefix
5053 // increment operator ++ for objects of that type. If the function
5054 // is a member function with one parameter (which shall be of type
5055 // int) or a non-member function with two parameters (the second
5056 // of which shall be of type int), it defines the postfix
5057 // increment operator ++ for objects of that type.
5058 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5059 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5060 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005061 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005062 ParamIsInt = BT->getKind() == BuiltinType::Int;
5063
Chris Lattner2b786902008-11-21 07:50:02 +00005064 if (!ParamIsInt)
5065 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005066 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005067 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005068 }
5069
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005070 // Notify the class if it got an assignment operator.
5071 if (Op == OO_Equal) {
5072 // Would have returned earlier otherwise.
5073 assert(isa<CXXMethodDecl>(FnDecl) &&
5074 "Overloaded = not member, but not filtered.");
5075 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5076 Method->getParent()->addedAssignmentOperator(Context, Method);
5077 }
5078
Douglas Gregord69246b2008-11-17 16:14:12 +00005079 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005080}
Chris Lattner3b024a32008-12-17 07:09:26 +00005081
Alexis Huntc88db062010-01-13 09:01:02 +00005082/// CheckLiteralOperatorDeclaration - Check whether the declaration
5083/// of this literal operator function is well-formed. If so, returns
5084/// false; otherwise, emits appropriate diagnostics and returns true.
5085bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5086 DeclContext *DC = FnDecl->getDeclContext();
5087 Decl::Kind Kind = DC->getDeclKind();
5088 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5089 Kind != Decl::LinkageSpec) {
5090 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5091 << FnDecl->getDeclName();
5092 return true;
5093 }
5094
5095 bool Valid = false;
5096
Alexis Hunt7dd26172010-04-07 23:11:06 +00005097 // template <char...> type operator "" name() is the only valid template
5098 // signature, and the only valid signature with no parameters.
5099 if (FnDecl->param_size() == 0) {
5100 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5101 // Must have only one template parameter
5102 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5103 if (Params->size() == 1) {
5104 NonTypeTemplateParmDecl *PmDecl =
5105 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005106
Alexis Hunt7dd26172010-04-07 23:11:06 +00005107 // The template parameter must be a char parameter pack.
5108 // FIXME: This test will always fail because non-type parameter packs
5109 // have not been implemented.
5110 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5111 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5112 Valid = true;
5113 }
5114 }
5115 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005116 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005117 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5118
Alexis Huntc88db062010-01-13 09:01:02 +00005119 QualType T = (*Param)->getType();
5120
Alexis Hunt079a6f72010-04-07 22:57:35 +00005121 // unsigned long long int, long double, and any character type are allowed
5122 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005123 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5124 Context.hasSameType(T, Context.LongDoubleTy) ||
5125 Context.hasSameType(T, Context.CharTy) ||
5126 Context.hasSameType(T, Context.WCharTy) ||
5127 Context.hasSameType(T, Context.Char16Ty) ||
5128 Context.hasSameType(T, Context.Char32Ty)) {
5129 if (++Param == FnDecl->param_end())
5130 Valid = true;
5131 goto FinishedParams;
5132 }
5133
Alexis Hunt079a6f72010-04-07 22:57:35 +00005134 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005135 const PointerType *PT = T->getAs<PointerType>();
5136 if (!PT)
5137 goto FinishedParams;
5138 T = PT->getPointeeType();
5139 if (!T.isConstQualified())
5140 goto FinishedParams;
5141 T = T.getUnqualifiedType();
5142
5143 // Move on to the second parameter;
5144 ++Param;
5145
5146 // If there is no second parameter, the first must be a const char *
5147 if (Param == FnDecl->param_end()) {
5148 if (Context.hasSameType(T, Context.CharTy))
5149 Valid = true;
5150 goto FinishedParams;
5151 }
5152
5153 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5154 // are allowed as the first parameter to a two-parameter function
5155 if (!(Context.hasSameType(T, Context.CharTy) ||
5156 Context.hasSameType(T, Context.WCharTy) ||
5157 Context.hasSameType(T, Context.Char16Ty) ||
5158 Context.hasSameType(T, Context.Char32Ty)))
5159 goto FinishedParams;
5160
5161 // The second and final parameter must be an std::size_t
5162 T = (*Param)->getType().getUnqualifiedType();
5163 if (Context.hasSameType(T, Context.getSizeType()) &&
5164 ++Param == FnDecl->param_end())
5165 Valid = true;
5166 }
5167
5168 // FIXME: This diagnostic is absolutely terrible.
5169FinishedParams:
5170 if (!Valid) {
5171 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5172 << FnDecl->getDeclName();
5173 return true;
5174 }
5175
5176 return false;
5177}
5178
Douglas Gregor07665a62009-01-05 19:45:36 +00005179/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5180/// linkage specification, including the language and (if present)
5181/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5182/// the location of the language string literal, which is provided
5183/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5184/// the '{' brace. Otherwise, this linkage specification does not
5185/// have any braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005186Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
5187 SourceLocation ExternLoc,
5188 SourceLocation LangLoc,
Benjamin Kramerbebee842010-05-03 13:08:54 +00005189 llvm::StringRef Lang,
Chris Lattner83f095c2009-03-28 19:18:32 +00005190 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005191 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005192 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005193 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005194 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005195 Language = LinkageSpecDecl::lang_cxx;
5196 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005197 Diag(LangLoc, diag::err_bad_language);
Chris Lattner83f095c2009-03-28 19:18:32 +00005198 return DeclPtrTy();
Chris Lattner438e5012008-12-17 07:13:27 +00005199 }
Mike Stump11289f42009-09-09 15:08:12 +00005200
Chris Lattner438e5012008-12-17 07:13:27 +00005201 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005202
Douglas Gregor07665a62009-01-05 19:45:36 +00005203 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005204 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005205 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005206 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005207 PushDeclContext(S, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005208 return DeclPtrTy::make(D);
Chris Lattner438e5012008-12-17 07:13:27 +00005209}
5210
Douglas Gregor07665a62009-01-05 19:45:36 +00005211/// ActOnFinishLinkageSpecification - Completely the definition of
5212/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5213/// valid, it's the position of the closing '}' brace in a linkage
5214/// specification that uses braces.
Chris Lattner83f095c2009-03-28 19:18:32 +00005215Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
5216 DeclPtrTy LinkageSpec,
5217 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005218 if (LinkageSpec)
5219 PopDeclContext();
5220 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005221}
5222
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005223/// \brief Perform semantic analysis for the variable declaration that
5224/// occurs within a C++ catch clause, returning the newly-created
5225/// variable.
5226VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
John McCallbcd03502009-12-07 02:54:59 +00005227 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005228 IdentifierInfo *Name,
5229 SourceLocation Loc,
5230 SourceRange Range) {
5231 bool Invalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005232
5233 // Arrays and functions decay.
5234 if (ExDeclType->isArrayType())
5235 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5236 else if (ExDeclType->isFunctionType())
5237 ExDeclType = Context.getPointerType(ExDeclType);
5238
5239 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5240 // The exception-declaration shall not denote a pointer or reference to an
5241 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005242 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005243 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005244 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlb28b4072009-03-22 23:49:27 +00005245 Invalid = true;
5246 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005247
Douglas Gregor104ee002010-03-08 01:47:36 +00005248 // GCC allows catching pointers and references to incomplete types
5249 // as an extension; so do we, but we warn by default.
5250
Sebastian Redl54c04d42008-12-22 19:15:10 +00005251 QualType BaseType = ExDeclType;
5252 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005253 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00005254 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005255 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005256 BaseType = Ptr->getPointeeType();
5257 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00005258 DK = diag::ext_catch_incomplete_ptr;
5259 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00005260 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005261 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005262 BaseType = Ref->getPointeeType();
5263 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00005264 DK = diag::ext_catch_incomplete_ref;
5265 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005266 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005267 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00005268 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5269 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00005270 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005271
Mike Stump11289f42009-09-09 15:08:12 +00005272 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005273 RequireNonAbstractType(Loc, ExDeclType,
5274 diag::err_abstract_type_in_decl,
5275 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005276 Invalid = true;
5277
Mike Stump11289f42009-09-09 15:08:12 +00005278 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Douglas Gregorc4df4072010-04-19 22:54:31 +00005279 Name, ExDeclType, TInfo, VarDecl::None,
5280 VarDecl::None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00005281 ExDecl->setExceptionVariable(true);
5282
Douglas Gregor6de584c2010-03-05 23:38:39 +00005283 if (!Invalid) {
5284 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
5285 // C++ [except.handle]p16:
5286 // The object declared in an exception-declaration or, if the
5287 // exception-declaration does not specify a name, a temporary (12.2) is
5288 // copy-initialized (8.5) from the exception object. [...]
5289 // The object is destroyed when the handler exits, after the destruction
5290 // of any automatic objects initialized within the handler.
5291 //
5292 // We just pretend to initialize the object with itself, then make sure
5293 // it can be destroyed later.
5294 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
5295 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
5296 Loc, ExDeclType, 0);
5297 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
5298 SourceLocation());
5299 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
5300 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
5301 MultiExprArg(*this, (void**)&ExDeclRef, 1));
5302 if (Result.isInvalid())
5303 Invalid = true;
5304 else
5305 FinalizeVarWithDestructor(ExDecl, RecordTy);
5306 }
5307 }
5308
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005309 if (Invalid)
5310 ExDecl->setInvalidDecl();
5311
5312 return ExDecl;
5313}
5314
5315/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
5316/// handler.
5317Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCallbcd03502009-12-07 02:54:59 +00005318 TypeSourceInfo *TInfo = 0;
5319 QualType ExDeclType = GetTypeForDeclarator(D, S, &TInfo);
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005320
5321 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00005322 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00005323 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00005324 LookupOrdinaryName,
5325 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005326 // The scope should be freshly made just for us. There is just no way
5327 // it contains any previous declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +00005328 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl54c04d42008-12-22 19:15:10 +00005329 if (PrevDecl->isTemplateParameter()) {
5330 // Maybe we will complain about the shadowed template parameter.
5331 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005332 }
5333 }
5334
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005335 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005336 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
5337 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005338 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005339 }
5340
John McCallbcd03502009-12-07 02:54:59 +00005341 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005342 D.getIdentifier(),
5343 D.getIdentifierLoc(),
5344 D.getDeclSpec().getSourceRange());
5345
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00005346 if (Invalid)
5347 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00005348
Sebastian Redl54c04d42008-12-22 19:15:10 +00005349 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005350 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005351 PushOnScopeChains(ExDecl, S);
5352 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005353 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005354
Douglas Gregor758a8692009-06-17 21:51:59 +00005355 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner83f095c2009-03-28 19:18:32 +00005356 return DeclPtrTy::make(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00005357}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005358
Mike Stump11289f42009-09-09 15:08:12 +00005359Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00005360 ExprArg assertexpr,
5361 ExprArg assertmessageexpr) {
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005362 Expr *AssertExpr = (Expr *)assertexpr.get();
Mike Stump11289f42009-09-09 15:08:12 +00005363 StringLiteral *AssertMessage =
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005364 cast<StringLiteral>((Expr *)assertmessageexpr.get());
5365
Anders Carlsson54b26982009-03-14 00:33:21 +00005366 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
5367 llvm::APSInt Value(32);
5368 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
5369 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
5370 AssertExpr->getSourceRange();
Chris Lattner83f095c2009-03-28 19:18:32 +00005371 return DeclPtrTy();
Anders Carlsson54b26982009-03-14 00:33:21 +00005372 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005373
Anders Carlsson54b26982009-03-14 00:33:21 +00005374 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00005375 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00005376 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00005377 }
5378 }
Mike Stump11289f42009-09-09 15:08:12 +00005379
Anders Carlsson78e2bc02009-03-15 17:35:16 +00005380 assertexpr.release();
5381 assertmessageexpr.release();
Mike Stump11289f42009-09-09 15:08:12 +00005382 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005383 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00005384
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005385 CurContext->addDecl(Decl);
Chris Lattner83f095c2009-03-28 19:18:32 +00005386 return DeclPtrTy::make(Decl);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00005387}
Sebastian Redlf769df52009-03-24 22:27:57 +00005388
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005389/// \brief Perform semantic analysis of the given friend type declaration.
5390///
5391/// \returns A friend declaration that.
5392FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
5393 TypeSourceInfo *TSInfo) {
5394 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
5395
5396 QualType T = TSInfo->getType();
5397 SourceRange TypeRange = TSInfo->getTypeLoc().getSourceRange();
5398
Douglas Gregor3b4abb62010-04-07 17:57:12 +00005399 if (!getLangOptions().CPlusPlus0x) {
5400 // C++03 [class.friend]p2:
5401 // An elaborated-type-specifier shall be used in a friend declaration
5402 // for a class.*
5403 //
5404 // * The class-key of the elaborated-type-specifier is required.
5405 if (!ActiveTemplateInstantiations.empty()) {
5406 // Do not complain about the form of friend template types during
5407 // template instantiation; we will already have complained when the
5408 // template was declared.
5409 } else if (!T->isElaboratedTypeSpecifier()) {
5410 // If we evaluated the type to a record type, suggest putting
5411 // a tag in front.
5412 if (const RecordType *RT = T->getAs<RecordType>()) {
5413 RecordDecl *RD = RT->getDecl();
5414
5415 std::string InsertionText = std::string(" ") + RD->getKindName();
5416
5417 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
5418 << (unsigned) RD->getTagKind()
5419 << T
5420 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
5421 InsertionText);
5422 } else {
5423 Diag(FriendLoc, diag::ext_nonclass_type_friend)
5424 << T
5425 << SourceRange(FriendLoc, TypeRange.getEnd());
5426 }
5427 } else if (T->getAs<EnumType>()) {
5428 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005429 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005430 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005431 }
5432 }
5433
Douglas Gregor3b4abb62010-04-07 17:57:12 +00005434 // C++0x [class.friend]p3:
5435 // If the type specifier in a friend declaration designates a (possibly
5436 // cv-qualified) class type, that class is declared as a friend; otherwise,
5437 // the friend declaration is ignored.
5438
5439 // FIXME: C++0x has some syntactic restrictions on friend type declarations
5440 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005441
5442 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
5443}
5444
John McCall11083da2009-09-16 22:47:08 +00005445/// Handle a friend type declaration. This works in tandem with
5446/// ActOnTag.
5447///
5448/// Notes on friend class templates:
5449///
5450/// We generally treat friend class declarations as if they were
5451/// declaring a class. So, for example, the elaborated type specifier
5452/// in a friend declaration is required to obey the restrictions of a
5453/// class-head (i.e. no typedefs in the scope chain), template
5454/// parameters are required to match up with simple template-ids, &c.
5455/// However, unlike when declaring a template specialization, it's
5456/// okay to refer to a template specialization without an empty
5457/// template parameter declaration, e.g.
5458/// friend class A<T>::B<unsigned>;
5459/// We permit this as a special case; if there are any template
5460/// parameters present at all, require proper matching, i.e.
5461/// template <> template <class T> friend class A<int>::B;
Chris Lattner1fb66f42009-10-25 17:47:27 +00005462Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00005463 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005464 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00005465
5466 assert(DS.isFriendSpecified());
5467 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5468
John McCall11083da2009-09-16 22:47:08 +00005469 // Try to convert the decl specifier to a type. This works for
5470 // friend templates because ActOnTag never produces a ClassTemplateDecl
5471 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00005472 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall15ad0962010-03-25 18:04:51 +00005473 TypeSourceInfo *TSI;
5474 QualType T = GetTypeForDeclarator(TheDeclarator, S, &TSI);
Chris Lattner1fb66f42009-10-25 17:47:27 +00005475 if (TheDeclarator.isInvalidType())
5476 return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005477
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005478 if (!TSI)
5479 TSI = Context.getTrivialTypeSourceInfo(T, DS.getSourceRange().getBegin());
5480
John McCall11083da2009-09-16 22:47:08 +00005481 // This is definitely an error in C++98. It's probably meant to
5482 // be forbidden in C++0x, too, but the specification is just
5483 // poorly written.
5484 //
5485 // The problem is with declarations like the following:
5486 // template <T> friend A<T>::foo;
5487 // where deciding whether a class C is a friend or not now hinges
5488 // on whether there exists an instantiation of A that causes
5489 // 'foo' to equal C. There are restrictions on class-heads
5490 // (which we declare (by fiat) elaborated friend declarations to
5491 // be) that makes this tractable.
5492 //
5493 // FIXME: handle "template <> friend class A<T>;", which
5494 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00005495 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00005496 Diag(Loc, diag::err_tagless_friend_type_template)
5497 << DS.getSourceRange();
5498 return DeclPtrTy();
5499 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005500
John McCallaa74a0c2009-08-28 07:59:38 +00005501 // C++98 [class.friend]p1: A friend of a class is a function
5502 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00005503 // This is fixed in DR77, which just barely didn't make the C++03
5504 // deadline. It's also a very silly restriction that seriously
5505 // affects inner classes and which nobody else seems to implement;
5506 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00005507 //
5508 // But note that we could warn about it: it's always useless to
5509 // friend one of your own members (it's not, however, worthless to
5510 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00005511
John McCall11083da2009-09-16 22:47:08 +00005512 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005513 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00005514 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005515 NumTempParamLists,
John McCall11083da2009-09-16 22:47:08 +00005516 (TemplateParameterList**) TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00005517 TSI,
John McCall11083da2009-09-16 22:47:08 +00005518 DS.getFriendSpecLoc());
5519 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00005520 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
5521
5522 if (!D)
5523 return DeclPtrTy();
5524
John McCall11083da2009-09-16 22:47:08 +00005525 D->setAccess(AS_public);
5526 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005527
John McCall11083da2009-09-16 22:47:08 +00005528 return DeclPtrTy::make(D);
John McCallaa74a0c2009-08-28 07:59:38 +00005529}
5530
John McCall2f212b32009-09-11 21:02:39 +00005531Sema::DeclPtrTy
5532Sema::ActOnFriendFunctionDecl(Scope *S,
5533 Declarator &D,
5534 bool IsDefinition,
5535 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00005536 const DeclSpec &DS = D.getDeclSpec();
5537
5538 assert(DS.isFriendSpecified());
5539 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
5540
5541 SourceLocation Loc = D.getIdentifierLoc();
John McCallbcd03502009-12-07 02:54:59 +00005542 TypeSourceInfo *TInfo = 0;
5543 QualType T = GetTypeForDeclarator(D, S, &TInfo);
John McCall07e91c02009-08-06 02:15:43 +00005544
5545 // C++ [class.friend]p1
5546 // A friend of a class is a function or class....
5547 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00005548 // It *doesn't* see through dependent types, which is correct
5549 // according to [temp.arg.type]p3:
5550 // If a declaration acquires a function type through a
5551 // type dependent on a template-parameter and this causes
5552 // a declaration that does not use the syntactic form of a
5553 // function declarator to have a function type, the program
5554 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00005555 if (!T->isFunctionType()) {
5556 Diag(Loc, diag::err_unexpected_friend);
5557
5558 // It might be worthwhile to try to recover by creating an
5559 // appropriate declaration.
5560 return DeclPtrTy();
5561 }
5562
5563 // C++ [namespace.memdef]p3
5564 // - If a friend declaration in a non-local class first declares a
5565 // class or function, the friend class or function is a member
5566 // of the innermost enclosing namespace.
5567 // - The name of the friend is not found by simple name lookup
5568 // until a matching declaration is provided in that namespace
5569 // scope (either before or after the class declaration granting
5570 // friendship).
5571 // - If a friend function is called, its name may be found by the
5572 // name lookup that considers functions from namespaces and
5573 // classes associated with the types of the function arguments.
5574 // - When looking for a prior declaration of a class or a function
5575 // declared as a friend, scopes outside the innermost enclosing
5576 // namespace scope are not considered.
5577
John McCallaa74a0c2009-08-28 07:59:38 +00005578 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
5579 DeclarationName Name = GetNameForDeclarator(D);
John McCall07e91c02009-08-06 02:15:43 +00005580 assert(Name);
5581
John McCall07e91c02009-08-06 02:15:43 +00005582 // The context we found the declaration in, or in which we should
5583 // create the declaration.
5584 DeclContext *DC;
5585
5586 // FIXME: handle local classes
5587
5588 // Recover from invalid scope qualifiers as if they just weren't there.
John McCall1f82f242009-11-18 22:49:29 +00005589 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName,
5590 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00005591 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
5592 DC = computeDeclContext(ScopeQual);
5593
5594 // FIXME: handle dependent contexts
5595 if (!DC) return DeclPtrTy();
John McCall0b66eb32010-05-01 00:40:08 +00005596 if (RequireCompleteDeclContext(ScopeQual, DC)) return DeclPtrTy();
John McCall07e91c02009-08-06 02:15:43 +00005597
John McCall1f82f242009-11-18 22:49:29 +00005598 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005599
5600 // If searching in that context implicitly found a declaration in
5601 // a different context, treat it like it wasn't found at all.
5602 // TODO: better diagnostics for this case. Suggesting the right
5603 // qualified scope would be nice...
John McCall1f82f242009-11-18 22:49:29 +00005604 // FIXME: getRepresentativeDecl() is not right here at all
5605 if (Previous.empty() ||
5606 !Previous.getRepresentativeDecl()->getDeclContext()->Equals(DC)) {
John McCallaa74a0c2009-08-28 07:59:38 +00005607 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00005608 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
5609 return DeclPtrTy();
5610 }
5611
5612 // C++ [class.friend]p1: A friend of a class is a function or
5613 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005614 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00005615 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5616
John McCall07e91c02009-08-06 02:15:43 +00005617 // Otherwise walk out to the nearest namespace scope looking for matches.
5618 } else {
5619 // TODO: handle local class contexts.
5620
5621 DC = CurContext;
5622 while (true) {
5623 // Skip class contexts. If someone can cite chapter and verse
5624 // for this behavior, that would be nice --- it's what GCC and
5625 // EDG do, and it seems like a reasonable intent, but the spec
5626 // really only says that checks for unqualified existing
5627 // declarations should stop at the nearest enclosing namespace,
5628 // not that they should only consider the nearest enclosing
5629 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005630 while (DC->isRecord())
5631 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00005632
John McCall1f82f242009-11-18 22:49:29 +00005633 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00005634
5635 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00005636 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00005637 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005638
John McCall07e91c02009-08-06 02:15:43 +00005639 if (DC->isFileContext()) break;
5640 DC = DC->getParent();
5641 }
5642
5643 // C++ [class.friend]p1: A friend of a class is a function or
5644 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00005645 // C++0x changes this for both friend types and functions.
5646 // Most C++ 98 compilers do seem to give an error here, so
5647 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00005648 if (!Previous.empty() && DC->Equals(CurContext)
5649 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00005650 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
5651 }
5652
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005653 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00005654 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00005655 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
5656 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
5657 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00005658 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00005659 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
5660 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall07e91c02009-08-06 02:15:43 +00005661 return DeclPtrTy();
5662 }
John McCall07e91c02009-08-06 02:15:43 +00005663 }
5664
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005665 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00005666 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00005667 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00005668 IsDefinition,
5669 Redeclaration);
John McCallaa74a0c2009-08-28 07:59:38 +00005670 if (!ND) return DeclPtrTy();
John McCall759e32b2009-08-31 22:39:49 +00005671
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005672 assert(ND->getDeclContext() == DC);
5673 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00005674
John McCall759e32b2009-08-31 22:39:49 +00005675 // Add the function declaration to the appropriate lookup tables,
5676 // adjusting the redeclarations list as necessary. We don't
5677 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00005678 //
John McCall759e32b2009-08-31 22:39:49 +00005679 // Also update the scope-based lookup if the target context's
5680 // lookup context is in lexical scope.
5681 if (!CurContext->isDependentContext()) {
5682 DC = DC->getLookupContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005683 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005684 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005685 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00005686 }
John McCallaa74a0c2009-08-28 07:59:38 +00005687
5688 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005689 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00005690 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00005691 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00005692 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00005693
Douglas Gregora29a3ff2009-09-28 00:08:27 +00005694 return DeclPtrTy::make(ND);
Anders Carlsson38811702009-05-11 22:55:49 +00005695}
5696
Chris Lattner83f095c2009-03-28 19:18:32 +00005697void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorc8c277a2009-08-24 11:57:43 +00005698 AdjustDeclIfTemplate(dcl);
Mike Stump11289f42009-09-09 15:08:12 +00005699
Chris Lattner83f095c2009-03-28 19:18:32 +00005700 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redlf769df52009-03-24 22:27:57 +00005701 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
5702 if (!Fn) {
5703 Diag(DelLoc, diag::err_deleted_non_function);
5704 return;
5705 }
5706 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
5707 Diag(DelLoc, diag::err_deleted_decl_not_first);
5708 Diag(Prev->getLocation(), diag::note_previous_declaration);
5709 // If the declaration wasn't the first, we delete the function anyway for
5710 // recovery.
5711 }
5712 Fn->setDeleted();
5713}
Sebastian Redl4c018662009-04-27 21:33:24 +00005714
5715static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
5716 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
5717 ++CI) {
5718 Stmt *SubStmt = *CI;
5719 if (!SubStmt)
5720 continue;
5721 if (isa<ReturnStmt>(SubStmt))
5722 Self.Diag(SubStmt->getSourceRange().getBegin(),
5723 diag::err_return_in_constructor_handler);
5724 if (!isa<Expr>(SubStmt))
5725 SearchForReturnInStmt(Self, SubStmt);
5726 }
5727}
5728
5729void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
5730 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
5731 CXXCatchStmt *Handler = TryBlock->getHandler(I);
5732 SearchForReturnInStmt(*this, Handler);
5733 }
5734}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005735
Mike Stump11289f42009-09-09 15:08:12 +00005736bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005737 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00005738 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
5739 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005740
Chandler Carruth284bb2e2010-02-15 11:53:20 +00005741 if (Context.hasSameType(NewTy, OldTy) ||
5742 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005743 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005744
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005745 // Check if the return types are covariant
5746 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00005747
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005748 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005749 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
5750 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005751 NewClassTy = NewPT->getPointeeType();
5752 OldClassTy = OldPT->getPointeeType();
5753 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005754 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
5755 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
5756 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
5757 NewClassTy = NewRT->getPointeeType();
5758 OldClassTy = OldRT->getPointeeType();
5759 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005760 }
5761 }
Mike Stump11289f42009-09-09 15:08:12 +00005762
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005763 // The return types aren't either both pointers or references to a class type.
5764 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00005765 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005766 diag::err_different_return_type_for_overriding_virtual_function)
5767 << New->getDeclName() << NewTy << OldTy;
5768 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00005769
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005770 return true;
5771 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005772
Anders Carlssone60365b2009-12-31 18:34:24 +00005773 // C++ [class.virtual]p6:
5774 // If the return type of D::f differs from the return type of B::f, the
5775 // class type in the return type of D::f shall be complete at the point of
5776 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005777 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
5778 if (!RT->isBeingDefined() &&
5779 RequireCompleteType(New->getLocation(), NewClassTy,
5780 PDiag(diag::err_covariant_return_incomplete)
5781 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00005782 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00005783 }
Anders Carlssone60365b2009-12-31 18:34:24 +00005784
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005785 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005786 // Check if the new class derives from the old class.
5787 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
5788 Diag(New->getLocation(),
5789 diag::err_covariant_return_not_derived)
5790 << New->getDeclName() << NewTy << OldTy;
5791 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5792 return true;
5793 }
Mike Stump11289f42009-09-09 15:08:12 +00005794
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005795 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00005796 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00005797 diag::err_covariant_return_inaccessible_base,
5798 diag::err_covariant_return_ambiguous_derived_to_base_conv,
5799 // FIXME: Should this point to the return type?
5800 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005801 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5802 return true;
5803 }
5804 }
Mike Stump11289f42009-09-09 15:08:12 +00005805
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005806 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00005807 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005808 Diag(New->getLocation(),
5809 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005810 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005811 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5812 return true;
5813 };
Mike Stump11289f42009-09-09 15:08:12 +00005814
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005815
5816 // The new class type must have the same or less qualifiers as the old type.
5817 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
5818 Diag(New->getLocation(),
5819 diag::err_covariant_return_type_class_type_more_qualified)
5820 << New->getDeclName() << NewTy << OldTy;
5821 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5822 return true;
5823 };
Mike Stump11289f42009-09-09 15:08:12 +00005824
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00005825 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00005826}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005827
Alexis Hunt96d5c762009-11-21 08:43:09 +00005828bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
5829 const CXXMethodDecl *Old)
5830{
5831 if (Old->hasAttr<FinalAttr>()) {
5832 Diag(New->getLocation(), diag::err_final_function_overridden)
5833 << New->getDeclName();
5834 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
5835 return true;
5836 }
5837
5838 return false;
5839}
5840
Douglas Gregor21920e372009-12-01 17:24:26 +00005841/// \brief Mark the given method pure.
5842///
5843/// \param Method the method to be marked pure.
5844///
5845/// \param InitRange the source range that covers the "0" initializer.
5846bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
5847 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
5848 Method->setPure();
5849
5850 // A class is abstract if at least one function is pure virtual.
5851 Method->getParent()->setAbstract(true);
5852 return false;
5853 }
5854
5855 if (!Method->isInvalidDecl())
5856 Diag(Method->getLocation(), diag::err_non_virtual_pure)
5857 << Method->getDeclName() << InitRange;
5858 return true;
5859}
5860
John McCall1f4ee7b2009-12-19 09:28:58 +00005861/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
5862/// an initializer for the out-of-line declaration 'Dcl'. The scope
5863/// is a fresh scope pushed for just this purpose.
5864///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005865/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
5866/// static data member of class X, names should be looked up in the scope of
5867/// class X.
5868void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005869 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005870 Decl *D = Dcl.getAs<Decl>();
5871 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005872
John McCall1f4ee7b2009-12-19 09:28:58 +00005873 // We should only get called for declarations with scope specifiers, like:
5874 // int foo::bar;
5875 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005876 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005877}
5878
5879/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall1f4ee7b2009-12-19 09:28:58 +00005880/// initializer for the out-of-line declaration 'Dcl'.
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005881void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005882 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00005883 Decl *D = Dcl.getAs<Decl>();
5884 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005885
John McCall1f4ee7b2009-12-19 09:28:58 +00005886 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00005887 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00005888}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005889
5890/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
5891/// C++ if/switch/while/for statement.
5892/// e.g: "if (int x = f()) {...}"
5893Action::DeclResult
5894Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
5895 // C++ 6.4p2:
5896 // The declarator shall not specify a function or an array.
5897 // The type-specifier-seq shall not contain typedef and shall not declare a
5898 // new class or enumeration.
5899 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5900 "Parser allowed 'typedef' as storage class of condition decl.");
5901
John McCallbcd03502009-12-07 02:54:59 +00005902 TypeSourceInfo *TInfo = 0;
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005903 TagDecl *OwnedTag = 0;
John McCallbcd03502009-12-07 02:54:59 +00005904 QualType Ty = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00005905
5906 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
5907 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
5908 // would be created and CXXConditionDeclExpr wants a VarDecl.
5909 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
5910 << D.getSourceRange();
5911 return DeclResult();
5912 } else if (OwnedTag && OwnedTag->isDefinition()) {
5913 // The type-specifier-seq shall not declare a new class or enumeration.
5914 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
5915 }
5916
5917 DeclPtrTy Dcl = ActOnDeclarator(S, D);
5918 if (!Dcl)
5919 return DeclResult();
5920
5921 VarDecl *VD = cast<VarDecl>(Dcl.getAs<Decl>());
5922 VD->setDeclaredInCondition(true);
5923 return Dcl;
5924}
Anders Carlssonf98849e2009-12-02 17:15:43 +00005925
Anders Carlsson11e51402010-04-17 20:15:18 +00005926static bool needsVTable(CXXMethodDecl *MD, ASTContext &Context) {
Anders Carlssonf98849e2009-12-02 17:15:43 +00005927 // Ignore dependent types.
5928 if (MD->isDependentContext())
Rafael Espindola70e040d2010-03-02 21:28:26 +00005929 return false;
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00005930
Douglas Gregorccecc1b2010-01-06 20:27:16 +00005931 // Ignore declarations that are not definitions.
5932 if (!MD->isThisDeclarationADefinition())
Rafael Espindola70e040d2010-03-02 21:28:26 +00005933 return false;
5934
5935 CXXRecordDecl *RD = MD->getParent();
5936
5937 // Ignore classes without a vtable.
5938 if (!RD->isDynamicClass())
5939 return false;
5940
5941 switch (MD->getParent()->getTemplateSpecializationKind()) {
5942 case TSK_Undeclared:
5943 case TSK_ExplicitSpecialization:
5944 // Classes that aren't instantiations of templates don't need their
5945 // virtual methods marked until we see the definition of the key
5946 // function.
5947 break;
5948
5949 case TSK_ImplicitInstantiation:
5950 // This is a constructor of a class template; mark all of the virtual
5951 // members as referenced to ensure that they get instantiatied.
5952 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
5953 return true;
5954 break;
5955
5956 case TSK_ExplicitInstantiationDeclaration:
Rafael Espindola8d04f062010-03-22 23:12:48 +00005957 return false;
Rafael Espindola70e040d2010-03-02 21:28:26 +00005958
5959 case TSK_ExplicitInstantiationDefinition:
5960 // This is method of a explicit instantiation; mark all of the virtual
5961 // members as referenced to ensure that they get instantiatied.
5962 return true;
Douglas Gregorccecc1b2010-01-06 20:27:16 +00005963 }
Rafael Espindola70e040d2010-03-02 21:28:26 +00005964
5965 // Consider only out-of-line definitions of member functions. When we see
5966 // an inline definition, it's too early to compute the key function.
5967 if (!MD->isOutOfLine())
5968 return false;
5969
5970 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(RD);
5971
5972 // If there is no key function, we will need a copy of the vtable.
5973 if (!KeyFunction)
5974 return true;
5975
5976 // If this is the key function, we need to mark virtual members.
5977 if (KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
5978 return true;
5979
5980 return false;
5981}
5982
5983void Sema::MaybeMarkVirtualMembersReferenced(SourceLocation Loc,
5984 CXXMethodDecl *MD) {
5985 CXXRecordDecl *RD = MD->getParent();
5986
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00005987 // We will need to mark all of the virtual members as referenced to build the
5988 // vtable.
Anders Carlsson11e51402010-04-17 20:15:18 +00005989 if (!needsVTable(MD, Context))
Rafael Espindolae7113ca2010-03-10 02:19:29 +00005990 return;
5991
5992 TemplateSpecializationKind kind = RD->getTemplateSpecializationKind();
5993 if (kind == TSK_ImplicitInstantiation)
5994 ClassesWithUnmarkedVirtualMembers.push_back(std::make_pair(RD, Loc));
5995 else
Rafael Espindola70e040d2010-03-02 21:28:26 +00005996 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlsson82fccd02009-12-07 08:24:59 +00005997}
5998
5999bool Sema::ProcessPendingClassesWithUnmarkedVirtualMembers() {
6000 if (ClassesWithUnmarkedVirtualMembers.empty())
6001 return false;
6002
Douglas Gregor0a0f04d2010-01-06 04:44:19 +00006003 while (!ClassesWithUnmarkedVirtualMembers.empty()) {
6004 CXXRecordDecl *RD = ClassesWithUnmarkedVirtualMembers.back().first;
6005 SourceLocation Loc = ClassesWithUnmarkedVirtualMembers.back().second;
6006 ClassesWithUnmarkedVirtualMembers.pop_back();
Anders Carlsson82fccd02009-12-07 08:24:59 +00006007 MarkVirtualMembersReferenced(Loc, RD);
Anders Carlssonf98849e2009-12-02 17:15:43 +00006008 }
6009
Anders Carlsson82fccd02009-12-07 08:24:59 +00006010 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006011}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006012
Rafael Espindola5b334082010-03-26 00:36:59 +00006013void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6014 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006015 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6016 e = RD->method_end(); i != e; ++i) {
6017 CXXMethodDecl *MD = *i;
6018
6019 // C++ [basic.def.odr]p2:
6020 // [...] A virtual member function is used if it is not pure. [...]
6021 if (MD->isVirtual() && !MD->isPure())
6022 MarkDeclarationReferenced(Loc, MD);
6023 }
Rafael Espindola5b334082010-03-26 00:36:59 +00006024
6025 // Only classes that have virtual bases need a VTT.
6026 if (RD->getNumVBases() == 0)
6027 return;
6028
6029 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6030 e = RD->bases_end(); i != e; ++i) {
6031 const CXXRecordDecl *Base =
6032 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
6033 if (i->isVirtual())
6034 continue;
6035 if (Base->getNumVBases() == 0)
6036 continue;
6037 MarkVirtualMembersReferenced(Loc, Base);
6038 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006039}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006040
6041/// SetIvarInitializers - This routine builds initialization ASTs for the
6042/// Objective-C implementation whose ivars need be initialized.
6043void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6044 if (!getLangOptions().CPlusPlus)
6045 return;
6046 if (const ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
6047 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6048 CollectIvarsToConstructOrDestruct(OID, ivars);
6049 if (ivars.empty())
6050 return;
6051 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6052 for (unsigned i = 0; i < ivars.size(); i++) {
6053 FieldDecl *Field = ivars[i];
6054 CXXBaseOrMemberInitializer *Member;
6055 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6056 InitializationKind InitKind =
6057 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6058
6059 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
6060 Sema::OwningExprResult MemberInit =
6061 InitSeq.Perform(*this, InitEntity, InitKind,
6062 Sema::MultiExprArg(*this, 0, 0));
6063 MemberInit = MaybeCreateCXXExprWithTemporaries(move(MemberInit));
6064 // Note, MemberInit could actually come back empty if no initialization
6065 // is required (e.g., because it would call a trivial default constructor)
6066 if (!MemberInit.get() || MemberInit.isInvalid())
6067 continue;
6068
6069 Member =
6070 new (Context) CXXBaseOrMemberInitializer(Context,
6071 Field, SourceLocation(),
6072 SourceLocation(),
6073 MemberInit.takeAs<Expr>(),
6074 SourceLocation());
6075 AllToInit.push_back(Member);
6076 }
6077 ObjCImplementation->setIvarInitializers(Context,
6078 AllToInit.data(), AllToInit.size());
6079 }
6080}