blob: 1e4065454ed827228bd3bfb8e6686d1c965db459 [file] [log] [blame]
Chris Lattner199abbc2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallcc14d1f2010-08-24 08:50:51 +000015#include "clang/Sema/CXXFieldCollector.h"
16#include "clang/Sema/Scope.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Argyrios Kyrtzidis2f67f372008-08-09 00:58:37 +000019#include "clang/AST/ASTConsumer.h"
Douglas Gregor556877c2008-04-13 21:30:24 +000020#include "clang/AST/ASTContext.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000021#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
Anders Carlssonb5a27b42009-03-24 01:19:16 +000023#include "clang/AST/DeclVisitor.h"
Douglas Gregorb139cd52010-05-01 20:49:11 +000024#include "clang/AST/RecordLayout.h"
25#include "clang/AST/StmtVisitor.h"
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +000026#include "clang/AST/TypeLoc.h"
Douglas Gregordff6a8e2008-10-22 21:13:31 +000027#include "clang/AST/TypeOrdering.h"
John McCall8b0666c2010-08-20 18:27:03 +000028#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/ParsedTemplate.h"
Anders Carlssond624e162009-08-26 23:45:07 +000030#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +000031#include "clang/Lex/Preprocessor.h"
John McCalla1e130b2010-08-25 07:03:20 +000032#include "llvm/ADT/DenseSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000033#include "llvm/ADT/STLExtras.h"
Douglas Gregor29a92472008-10-22 17:49:05 +000034#include <map>
Douglas Gregor36d1b142009-10-06 17:59:45 +000035#include <set>
Chris Lattner199abbc2008-04-08 05:04:30 +000036
37using namespace clang;
38
Chris Lattner58258242008-04-10 02:22:51 +000039//===----------------------------------------------------------------------===//
40// CheckDefaultArgumentVisitor
41//===----------------------------------------------------------------------===//
42
Chris Lattnerb0d38442008-04-12 23:52:44 +000043namespace {
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
Benjamin Kramer337e3a52009-11-28 19:45:26 +000049 class CheckDefaultArgumentVisitor
Chris Lattner574dee62008-07-26 22:17:49 +000050 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb0d38442008-04-12 23:52:44 +000051 Expr *DefaultArg;
52 Sema *S;
Chris Lattner58258242008-04-10 02:22:51 +000053
Chris Lattnerb0d38442008-04-12 23:52:44 +000054 public:
Mike Stump11289f42009-09-09 15:08:12 +000055 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
Chris Lattnerb0d38442008-04-12 23:52:44 +000056 : DefaultArg(defarg), S(s) {}
Chris Lattner58258242008-04-10 02:22:51 +000057
Chris Lattnerb0d38442008-04-12 23:52:44 +000058 bool VisitExpr(Expr *Node);
59 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor97a9c812008-11-04 14:32:21 +000060 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb0d38442008-04-12 23:52:44 +000061 };
Chris Lattner58258242008-04-10 02:22:51 +000062
Chris Lattnerb0d38442008-04-12 23:52:44 +000063 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
65 bool IsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +000066 for (Stmt::child_iterator I = Node->child_begin(),
Chris Lattner574dee62008-07-26 22:17:49 +000067 E = Node->child_end(); I != E; ++I)
68 IsInvalid |= Visit(*I);
Chris Lattnerb0d38442008-04-12 23:52:44 +000069 return IsInvalid;
Chris Lattner58258242008-04-10 02:22:51 +000070 }
71
Chris Lattnerb0d38442008-04-12 23:52:44 +000072 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb0d38442008-04-12 23:52:44 +000077 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
Mike Stump11289f42009-09-09 15:08:12 +000086 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_param)
Chris Lattnere3d20d92008-11-23 21:45:46 +000088 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff08899ff2008-04-15 22:42:06 +000089 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb0d38442008-04-12 23:52:44 +000090 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
92 // expressions.
Steve Naroff08899ff2008-04-15 22:42:06 +000093 if (VDecl->isBlockVarDecl())
Mike Stump11289f42009-09-09 15:08:12 +000094 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +000095 diag::err_param_default_argument_references_local)
Chris Lattnere3d20d92008-11-23 21:45:46 +000096 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +000097 }
Chris Lattner58258242008-04-10 02:22:51 +000098
Douglas Gregor8e12c382008-11-04 13:41:56 +000099 return false;
100 }
Chris Lattnerb0d38442008-04-12 23:52:44 +0000101
Douglas Gregor97a9c812008-11-04 14:32:21 +0000102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
106 // member function.
107 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000108 diag::err_param_default_argument_references_this)
109 << ThisE->getSourceRange();
Chris Lattnerb0d38442008-04-12 23:52:44 +0000110 }
Chris Lattner58258242008-04-10 02:22:51 +0000111}
112
Anders Carlssonc80a1272009-08-25 02:29:20 +0000113bool
John McCallb268a282010-08-23 23:25:46 +0000114Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
Mike Stump11289f42009-09-09 15:08:12 +0000115 SourceLocation EqualLoc) {
Anders Carlsson114056f2009-08-25 13:46:13 +0000116 if (RequireCompleteType(Param->getLocation(), Param->getType(),
117 diag::err_typecheck_decl_incomplete_type)) {
118 Param->setInvalidDecl();
119 return true;
120 }
121
Anders Carlssonc80a1272009-08-25 02:29:20 +0000122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000128 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
129 Param);
Douglas Gregor85dabae2009-12-16 01:38:02 +0000130 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
131 EqualLoc);
Eli Friedman5f101b92009-12-22 02:46:13 +0000132 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
John McCalldadc5752010-08-24 06:29:42 +0000133 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +0000134 MultiExprArg(*this, &Arg, 1));
Eli Friedman5f101b92009-12-22 02:46:13 +0000135 if (Result.isInvalid())
Anders Carlsson4562f1f2009-08-25 03:18:48 +0000136 return true;
Eli Friedman5f101b92009-12-22 02:46:13 +0000137 Arg = Result.takeAs<Expr>();
Anders Carlssonc80a1272009-08-25 02:29:20 +0000138
Anders Carlsson6e997b22009-12-15 20:51:39 +0000139 Arg = MaybeCreateCXXExprWithTemporaries(Arg);
Mike Stump11289f42009-09-09 15:08:12 +0000140
Anders Carlssonc80a1272009-08-25 02:29:20 +0000141 // Okay: add the default argument to the parameter
142 Param->setDefaultArg(Arg);
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
John McCall48871652010-08-21 09:40:31 +0000151Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
John McCallb268a282010-08-23 23:25:46 +0000152 Expr *DefaultArg) {
153 if (!param || !DefaultArg)
Douglas Gregor71a57182009-06-22 23:20:33 +0000154 return;
Mike Stump11289f42009-09-09 15:08:12 +0000155
John McCall48871652010-08-21 09:40:31 +0000156 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Anders Carlsson84613c42009-06-12 16:51:40 +0000157 UnparsedDefaultArgLocs.erase(Param);
158
Chris Lattner199abbc2008-04-08 05:04:30 +0000159 // Default arguments are only permitted in C++
160 if (!getLangOptions().CPlusPlus) {
Chris Lattner3b054132008-11-19 05:08:23 +0000161 Diag(EqualLoc, diag::err_param_default_argument)
162 << DefaultArg->getSourceRange();
Douglas Gregor4d87df52008-12-16 21:30:33 +0000163 Param->setInvalidDecl();
Chris Lattner199abbc2008-04-08 05:04:30 +0000164 return;
165 }
166
Anders Carlssonf1c26952009-08-25 01:02:06 +0000167 // Check that the default argument is well-formed
John McCallb268a282010-08-23 23:25:46 +0000168 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
169 if (DefaultArgChecker.Visit(DefaultArg)) {
Anders Carlssonf1c26952009-08-25 01:02:06 +0000170 Param->setInvalidDecl();
171 return;
172 }
Mike Stump11289f42009-09-09 15:08:12 +0000173
John McCallb268a282010-08-23 23:25:46 +0000174 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
Chris Lattner199abbc2008-04-08 05:04:30 +0000175}
176
Douglas Gregor58354032008-12-24 00:01:03 +0000177/// ActOnParamUnparsedDefaultArgument - We've seen a default
178/// argument for a function parameter, but we can't parse it yet
179/// because we're inside a class definition. Note that this default
180/// argument will be parsed later.
John McCall48871652010-08-21 09:40:31 +0000181void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
Anders Carlsson84613c42009-06-12 16:51:40 +0000182 SourceLocation EqualLoc,
183 SourceLocation ArgLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000184 if (!param)
185 return;
Mike Stump11289f42009-09-09 15:08:12 +0000186
John McCall48871652010-08-21 09:40:31 +0000187 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Douglas Gregor58354032008-12-24 00:01:03 +0000188 if (Param)
189 Param->setUnparsedDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +0000190
Anders Carlsson84613c42009-06-12 16:51:40 +0000191 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor58354032008-12-24 00:01:03 +0000192}
193
Douglas Gregor4d87df52008-12-16 21:30:33 +0000194/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
195/// the default argument for the parameter param failed.
John McCall48871652010-08-21 09:40:31 +0000196void Sema::ActOnParamDefaultArgumentError(Decl *param) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000197 if (!param)
198 return;
Mike Stump11289f42009-09-09 15:08:12 +0000199
John McCall48871652010-08-21 09:40:31 +0000200 ParmVarDecl *Param = cast<ParmVarDecl>(param);
Mike Stump11289f42009-09-09 15:08:12 +0000201
Anders Carlsson84613c42009-06-12 16:51:40 +0000202 Param->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000203
Anders Carlsson84613c42009-06-12 16:51:40 +0000204 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +0000205}
206
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000207/// CheckExtraCXXDefaultArguments - Check for any extra default
208/// arguments in the declarator, which is not a function declaration
209/// or definition and therefore is not permitted to have default
210/// arguments. This routine should be invoked for every declarator
211/// that is not a function declaration or definition.
212void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
213 // C++ [dcl.fct.default]p3
214 // A default argument expression shall be specified only in the
215 // parameter-declaration-clause of a function declaration or in a
216 // template-parameter (14.1). It shall not be specified for a
217 // parameter pack. If it is specified in a
218 // parameter-declaration-clause, it shall not occur within a
219 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner83f095c2009-03-28 19:18:32 +0000220 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000221 DeclaratorChunk &chunk = D.getTypeObject(i);
222 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner83f095c2009-03-28 19:18:32 +0000223 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
224 ParmVarDecl *Param =
John McCall48871652010-08-21 09:40:31 +0000225 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
Douglas Gregor58354032008-12-24 00:01:03 +0000226 if (Param->hasUnparsedDefaultArg()) {
227 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor4d87df52008-12-16 21:30:33 +0000228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
229 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
230 delete Toks;
231 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor58354032008-12-24 00:01:03 +0000232 } else if (Param->getDefaultArg()) {
233 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
234 << Param->getDefaultArg()->getSourceRange();
235 Param->setDefaultArg(0);
Douglas Gregorcaa8ace2008-05-07 04:49:29 +0000236 }
237 }
238 }
239 }
240}
241
Chris Lattner199abbc2008-04-08 05:04:30 +0000242// MergeCXXFunctionDecl - Merge two declarations of the same C++
243// function, once we already know that they have the same
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000244// type. Subroutine of MergeFunctionDecl. Returns true if there was an
245// error, false otherwise.
246bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
247 bool Invalid = false;
248
Chris Lattner199abbc2008-04-08 05:04:30 +0000249 // C++ [dcl.fct.default]p4:
Chris Lattner199abbc2008-04-08 05:04:30 +0000250 // For non-template functions, default arguments can be added in
251 // later declarations of a function in the same
252 // scope. Declarations in different scopes have completely
253 // distinct sets of default arguments. That is, declarations in
254 // inner scopes do not acquire default arguments from
255 // declarations in outer scopes, and vice versa. In a given
256 // function declaration, all parameters subsequent to a
257 // parameter with a default argument shall have default
258 // arguments supplied in this or previous declarations. A
259 // default argument shall not be redefined by a later
260 // declaration (not even to the same value).
Douglas Gregorc732aba2009-09-11 18:44:32 +0000261 //
262 // C++ [dcl.fct.default]p6:
263 // Except for member functions of class templates, the default arguments
264 // in a member function definition that appears outside of the class
265 // definition are added to the set of default arguments provided by the
266 // member function declaration in the class definition.
Chris Lattner199abbc2008-04-08 05:04:30 +0000267 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
268 ParmVarDecl *OldParam = Old->getParamDecl(p);
269 ParmVarDecl *NewParam = New->getParamDecl(p);
270
Douglas Gregorc732aba2009-09-11 18:44:32 +0000271 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
Douglas Gregor08dc5842010-01-13 00:12:48 +0000272 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
273 // hint here. Alternatively, we could walk the type-source information
274 // for NewParam to find the last source location in the type... but it
275 // isn't worth the effort right now. This is the kind of test case that
276 // is hard to get right:
277
278 // int f(int);
279 // void g(int (*fp)(int) = f);
280 // void g(int (*fp)(int) = &f);
Mike Stump11289f42009-09-09 15:08:12 +0000281 Diag(NewParam->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000282 diag::err_param_default_argument_redefinition)
Douglas Gregor08dc5842010-01-13 00:12:48 +0000283 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000284
285 // Look for the function declaration where the default argument was
286 // actually written, which may be a declaration prior to Old.
287 for (FunctionDecl *Older = Old->getPreviousDeclaration();
288 Older; Older = Older->getPreviousDeclaration()) {
289 if (!Older->getParamDecl(p)->hasDefaultArg())
290 break;
291
292 OldParam = Older->getParamDecl(p);
293 }
294
295 Diag(OldParam->getLocation(), diag::note_previous_definition)
296 << OldParam->getDefaultArgRange();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000297 Invalid = true;
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000298 } else if (OldParam->hasDefaultArg()) {
John McCalle61b02b2010-05-04 01:53:42 +0000299 // Merge the old default argument into the new parameter.
300 // It's important to use getInit() here; getDefaultArg()
301 // strips off any top-level CXXExprWithTemporaries.
John McCallf3cd6652010-03-12 18:31:32 +0000302 NewParam->setHasInheritedDefaultArg();
Douglas Gregor4f15f4d2009-09-17 19:51:30 +0000303 if (OldParam->hasUninstantiatedDefaultArg())
304 NewParam->setUninstantiatedDefaultArg(
305 OldParam->getUninstantiatedDefaultArg());
306 else
John McCalle61b02b2010-05-04 01:53:42 +0000307 NewParam->setDefaultArg(OldParam->getInit());
Douglas Gregorc732aba2009-09-11 18:44:32 +0000308 } else if (NewParam->hasDefaultArg()) {
309 if (New->getDescribedFunctionTemplate()) {
310 // Paragraph 4, quoted above, only applies to non-template functions.
311 Diag(NewParam->getLocation(),
312 diag::err_param_default_argument_template_redecl)
313 << NewParam->getDefaultArgRange();
314 Diag(Old->getLocation(), diag::note_template_prev_declaration)
315 << false;
Douglas Gregor62e10f02009-10-13 17:02:54 +0000316 } else if (New->getTemplateSpecializationKind()
317 != TSK_ImplicitInstantiation &&
318 New->getTemplateSpecializationKind() != TSK_Undeclared) {
319 // C++ [temp.expr.spec]p21:
320 // Default function arguments shall not be specified in a declaration
321 // or a definition for one of the following explicit specializations:
322 // - the explicit specialization of a function template;
Douglas Gregor3362bde2009-10-13 23:52:38 +0000323 // - the explicit specialization of a member function template;
324 // - the explicit specialization of a member function of a class
Douglas Gregor62e10f02009-10-13 17:02:54 +0000325 // template where the class template specialization to which the
326 // member function specialization belongs is implicitly
327 // instantiated.
328 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
329 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
330 << New->getDeclName()
331 << NewParam->getDefaultArgRange();
Douglas Gregorc732aba2009-09-11 18:44:32 +0000332 } else if (New->getDeclContext()->isDependentContext()) {
333 // C++ [dcl.fct.default]p6 (DR217):
334 // Default arguments for a member function of a class template shall
335 // be specified on the initial declaration of the member function
336 // within the class template.
337 //
338 // Reading the tea leaves a bit in DR217 and its reference to DR205
339 // leads me to the conclusion that one cannot add default function
340 // arguments for an out-of-line definition of a member function of a
341 // dependent type.
342 int WhichKind = 2;
343 if (CXXRecordDecl *Record
344 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
345 if (Record->getDescribedClassTemplate())
346 WhichKind = 0;
347 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
348 WhichKind = 1;
349 else
350 WhichKind = 2;
351 }
352
353 Diag(NewParam->getLocation(),
354 diag::err_param_default_argument_member_template_redecl)
355 << WhichKind
356 << NewParam->getDefaultArgRange();
357 }
Chris Lattner199abbc2008-04-08 05:04:30 +0000358 }
359 }
360
Douglas Gregorf40863c2010-02-12 07:32:17 +0000361 if (CheckEquivalentExceptionSpec(Old, New))
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000362 Invalid = true;
Sebastian Redl4f4d7b52009-07-04 11:39:00 +0000363
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000364 return Invalid;
Chris Lattner199abbc2008-04-08 05:04:30 +0000365}
366
367/// CheckCXXDefaultArguments - Verify that the default arguments for a
368/// function declaration are well-formed according to C++
369/// [dcl.fct.default].
370void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
371 unsigned NumParams = FD->getNumParams();
372 unsigned p;
373
374 // Find first parameter with a default argument
375 for (p = 0; p < NumParams; ++p) {
376 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000377 if (Param->hasDefaultArg())
Chris Lattner199abbc2008-04-08 05:04:30 +0000378 break;
379 }
380
381 // C++ [dcl.fct.default]p4:
382 // In a given function declaration, all parameters
383 // subsequent to a parameter with a default argument shall
384 // have default arguments supplied in this or previous
385 // declarations. A default argument shall not be redefined
386 // by a later declaration (not even to the same value).
387 unsigned LastMissingDefaultArg = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000388 for (; p < NumParams; ++p) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000389 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5a532382009-08-25 01:23:32 +0000390 if (!Param->hasDefaultArg()) {
Douglas Gregor4d87df52008-12-16 21:30:33 +0000391 if (Param->isInvalidDecl())
392 /* We already complained about this parameter. */;
393 else if (Param->getIdentifier())
Mike Stump11289f42009-09-09 15:08:12 +0000394 Diag(Param->getLocation(),
Chris Lattner3b054132008-11-19 05:08:23 +0000395 diag::err_param_default_argument_missing_name)
Chris Lattnerb91fd172008-11-19 07:32:16 +0000396 << Param->getIdentifier();
Chris Lattner199abbc2008-04-08 05:04:30 +0000397 else
Mike Stump11289f42009-09-09 15:08:12 +0000398 Diag(Param->getLocation(),
Chris Lattner199abbc2008-04-08 05:04:30 +0000399 diag::err_param_default_argument_missing);
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattner199abbc2008-04-08 05:04:30 +0000401 LastMissingDefaultArg = p;
402 }
403 }
404
405 if (LastMissingDefaultArg > 0) {
406 // Some default arguments were missing. Clear out all of the
407 // default arguments up to (and including) the last missing
408 // default argument, so that we leave the function parameters
409 // in a semantically valid state.
410 for (p = 0; p <= LastMissingDefaultArg; ++p) {
411 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson84613c42009-06-12 16:51:40 +0000412 if (Param->hasDefaultArg()) {
Chris Lattner199abbc2008-04-08 05:04:30 +0000413 Param->setDefaultArg(0);
414 }
415 }
416 }
417}
Douglas Gregor556877c2008-04-13 21:30:24 +0000418
Douglas Gregor61956c42008-10-31 09:07:45 +0000419/// isCurrentClassName - Determine whether the identifier II is the
420/// name of the class type currently being defined. In the case of
421/// nested classes, this will only return true if II is the name of
422/// the innermost class.
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +0000423bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
424 const CXXScopeSpec *SS) {
Douglas Gregor411e5ac2010-01-11 23:29:10 +0000425 assert(getLangOptions().CPlusPlus && "No class names in C!");
426
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000427 CXXRecordDecl *CurDecl;
Douglas Gregor52537682009-03-19 00:18:19 +0000428 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregore5bbb7d2009-08-21 22:16:40 +0000429 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000430 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
431 } else
432 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
433
Douglas Gregor1aa3edb2010-02-05 06:12:42 +0000434 if (CurDecl && CurDecl->getIdentifier())
Douglas Gregor61956c42008-10-31 09:07:45 +0000435 return &II == CurDecl->getIdentifier();
436 else
437 return false;
438}
439
Mike Stump11289f42009-09-09 15:08:12 +0000440/// \brief Check the validity of a C++ base class specifier.
Douglas Gregor463421d2009-03-03 04:44:36 +0000441///
442/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
443/// and returns NULL otherwise.
444CXXBaseSpecifier *
445Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
446 SourceRange SpecifierRange,
447 bool Virtual, AccessSpecifier Access,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000448 TypeSourceInfo *TInfo) {
449 QualType BaseType = TInfo->getType();
450
Douglas Gregor463421d2009-03-03 04:44:36 +0000451 // C++ [class.union]p1:
452 // A union shall not have base classes.
453 if (Class->isUnion()) {
454 Diag(Class->getLocation(), diag::err_base_clause_on_union)
455 << SpecifierRange;
456 return 0;
457 }
458
459 if (BaseType->isDependentType())
Mike Stump11289f42009-09-09 15:08:12 +0000460 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000461 Class->getTagKind() == TTK_Class,
462 Access, TInfo);
463
464 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
Douglas Gregor463421d2009-03-03 04:44:36 +0000465
466 // Base specifiers must be record types.
467 if (!BaseType->isRecordType()) {
468 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
469 return 0;
470 }
471
472 // C++ [class.union]p1:
473 // A union shall not be used as a base class.
474 if (BaseType->isUnionType()) {
475 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
476 return 0;
477 }
478
479 // C++ [class.derived]p2:
480 // The class-name in a base-specifier shall not be an incompletely
481 // defined class.
Mike Stump11289f42009-09-09 15:08:12 +0000482 if (RequireCompleteType(BaseLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +0000483 PDiag(diag::err_incomplete_base_class)
John McCall3696dcb2010-08-17 07:23:57 +0000484 << SpecifierRange)) {
485 Class->setInvalidDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000486 return 0;
John McCall3696dcb2010-08-17 07:23:57 +0000487 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000488
Eli Friedmanc96d4962009-08-15 21:55:26 +0000489 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000490 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor463421d2009-03-03 04:44:36 +0000491 assert(BaseDecl && "Record type has no declaration");
Douglas Gregor0a5a2212010-02-11 01:04:33 +0000492 BaseDecl = BaseDecl->getDefinition();
Douglas Gregor463421d2009-03-03 04:44:36 +0000493 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedmanc96d4962009-08-15 21:55:26 +0000494 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
495 assert(CXXBaseDecl && "Base type is not a C++ type");
Eli Friedman89c038e2009-12-05 23:03:49 +0000496
Alexis Hunt96d5c762009-11-21 08:43:09 +0000497 // C++0x CWG Issue #817 indicates that [[final]] classes shouldn't be bases.
498 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
499 Diag(BaseLoc, diag::err_final_base) << BaseType.getAsString();
Douglas Gregore7488b92009-12-01 16:58:18 +0000500 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
501 << BaseType;
Alexis Hunt96d5c762009-11-21 08:43:09 +0000502 return 0;
503 }
Douglas Gregor463421d2009-03-03 04:44:36 +0000504
John McCall3696dcb2010-08-17 07:23:57 +0000505 if (BaseDecl->isInvalidDecl())
506 Class->setInvalidDecl();
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000507
508 // Create the base specifier.
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000509 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000510 Class->getTagKind() == TTK_Class,
511 Access, TInfo);
Anders Carlssonae3c5cf2009-12-03 17:49:57 +0000512}
513
Douglas Gregor556877c2008-04-13 21:30:24 +0000514/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
515/// one entry in the base class list of a class specifier, for
Mike Stump11289f42009-09-09 15:08:12 +0000516/// example:
517/// class foo : public bar, virtual private baz {
Douglas Gregor556877c2008-04-13 21:30:24 +0000518/// 'public bar' and 'virtual private baz' are each base-specifiers.
John McCallfaf5fb42010-08-26 23:41:50 +0000519BaseResult
John McCall48871652010-08-21 09:40:31 +0000520Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
Douglas Gregor29a92472008-10-22 17:49:05 +0000521 bool Virtual, AccessSpecifier Access,
John McCallba7bf592010-08-24 05:47:05 +0000522 ParsedType basetype, SourceLocation BaseLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000523 if (!classdecl)
524 return true;
525
Douglas Gregorc40290e2009-03-09 23:48:35 +0000526 AdjustDeclIfTemplate(classdecl);
John McCall48871652010-08-21 09:40:31 +0000527 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
Douglas Gregorbeab56e2010-02-27 00:25:28 +0000528 if (!Class)
529 return true;
530
Nick Lewycky19b9f952010-07-26 16:56:01 +0000531 TypeSourceInfo *TInfo = 0;
532 GetTypeFromParser(basetype, &TInfo);
Douglas Gregor463421d2009-03-03 04:44:36 +0000533 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
Nick Lewycky19b9f952010-07-26 16:56:01 +0000534 Virtual, Access, TInfo))
Douglas Gregor463421d2009-03-03 04:44:36 +0000535 return BaseSpec;
Mike Stump11289f42009-09-09 15:08:12 +0000536
Douglas Gregor463421d2009-03-03 04:44:36 +0000537 return true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000538}
Douglas Gregor556877c2008-04-13 21:30:24 +0000539
Douglas Gregor463421d2009-03-03 04:44:36 +0000540/// \brief Performs the actual work of attaching the given base class
541/// specifiers to a C++ class.
542bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
543 unsigned NumBases) {
544 if (NumBases == 0)
545 return false;
Douglas Gregor29a92472008-10-22 17:49:05 +0000546
547 // Used to keep track of which base types we have already seen, so
548 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000549 // that the key is always the unqualified canonical type of the base
550 // class.
Douglas Gregor29a92472008-10-22 17:49:05 +0000551 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
552
553 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000554 unsigned NumGoodBases = 0;
Douglas Gregor463421d2009-03-03 04:44:36 +0000555 bool Invalid = false;
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000556 for (unsigned idx = 0; idx < NumBases; ++idx) {
Mike Stump11289f42009-09-09 15:08:12 +0000557 QualType NewBaseType
Douglas Gregor463421d2009-03-03 04:44:36 +0000558 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000559 NewBaseType = NewBaseType.getLocalUnqualifiedType();
Fariborz Jahanian2792f302010-05-20 23:34:56 +0000560 if (!Class->hasObjectMember()) {
561 if (const RecordType *FDTTy =
562 NewBaseType.getTypePtr()->getAs<RecordType>())
563 if (FDTTy->getDecl()->hasObjectMember())
564 Class->setHasObjectMember(true);
565 }
566
Douglas Gregor29a92472008-10-22 17:49:05 +0000567 if (KnownBaseTypes[NewBaseType]) {
568 // C++ [class.mi]p3:
569 // A class shall not be specified as a direct base class of a
570 // derived class more than once.
Douglas Gregor463421d2009-03-03 04:44:36 +0000571 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +0000572 diag::err_duplicate_base_class)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000573 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor463421d2009-03-03 04:44:36 +0000574 << Bases[idx]->getSourceRange();
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000575
576 // Delete the duplicate base class specifier; we're going to
577 // overwrite its pointer later.
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000578 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000579
580 Invalid = true;
Douglas Gregor29a92472008-10-22 17:49:05 +0000581 } else {
582 // Okay, add this new base class.
Douglas Gregor463421d2009-03-03 04:44:36 +0000583 KnownBaseTypes[NewBaseType] = Bases[idx];
584 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregor29a92472008-10-22 17:49:05 +0000585 }
586 }
587
588 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor4a62bdf2010-02-11 01:30:34 +0000589 Class->setBases(Bases, NumGoodBases);
Douglas Gregor9d6290b2008-10-23 18:13:27 +0000590
591 // Delete the remaining (good) base class specifiers, since their
592 // data has been copied into the CXXRecordDecl.
593 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorb77af8f2009-07-22 20:55:49 +0000594 Context.Deallocate(Bases[idx]);
Douglas Gregor463421d2009-03-03 04:44:36 +0000595
596 return Invalid;
597}
598
599/// ActOnBaseSpecifiers - Attach the given base specifiers to the
600/// class, after checking whether there are any duplicate base
601/// classes.
John McCall48871652010-08-21 09:40:31 +0000602void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
Douglas Gregor463421d2009-03-03 04:44:36 +0000603 unsigned NumBases) {
604 if (!ClassDecl || !Bases || !NumBases)
605 return;
606
607 AdjustDeclIfTemplate(ClassDecl);
John McCall48871652010-08-21 09:40:31 +0000608 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
Douglas Gregor463421d2009-03-03 04:44:36 +0000609 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregor556877c2008-04-13 21:30:24 +0000610}
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000611
John McCalle78aac42010-03-10 03:28:59 +0000612static CXXRecordDecl *GetClassForType(QualType T) {
613 if (const RecordType *RT = T->getAs<RecordType>())
614 return cast<CXXRecordDecl>(RT->getDecl());
615 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
616 return ICT->getDecl();
617 else
618 return 0;
619}
620
Douglas Gregor36d1b142009-10-06 17:59:45 +0000621/// \brief Determine whether the type \p Derived is a C++ class that is
622/// derived from the type \p Base.
623bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
624 if (!getLangOptions().CPlusPlus)
625 return false;
John McCalle78aac42010-03-10 03:28:59 +0000626
627 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
628 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000629 return false;
630
John McCalle78aac42010-03-10 03:28:59 +0000631 CXXRecordDecl *BaseRD = GetClassForType(Base);
632 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000633 return false;
634
John McCall67da35c2010-02-04 22:26:26 +0000635 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
636 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000637}
638
639/// \brief Determine whether the type \p Derived is a C++ class that is
640/// derived from the type \p Base.
641bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
642 if (!getLangOptions().CPlusPlus)
643 return false;
644
John McCalle78aac42010-03-10 03:28:59 +0000645 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
646 if (!DerivedRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000647 return false;
648
John McCalle78aac42010-03-10 03:28:59 +0000649 CXXRecordDecl *BaseRD = GetClassForType(Base);
650 if (!BaseRD)
Douglas Gregor36d1b142009-10-06 17:59:45 +0000651 return false;
652
Douglas Gregor36d1b142009-10-06 17:59:45 +0000653 return DerivedRD->isDerivedFrom(BaseRD, Paths);
654}
655
Anders Carlssona70cff62010-04-24 19:06:50 +0000656void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
John McCallcf142162010-08-07 06:22:56 +0000657 CXXCastPath &BasePathArray) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000658 assert(BasePathArray.empty() && "Base path array must be empty!");
659 assert(Paths.isRecordingPaths() && "Must record paths!");
660
661 const CXXBasePath &Path = Paths.front();
662
663 // We first go backward and check if we have a virtual base.
664 // FIXME: It would be better if CXXBasePath had the base specifier for
665 // the nearest virtual base.
666 unsigned Start = 0;
667 for (unsigned I = Path.size(); I != 0; --I) {
668 if (Path[I - 1].Base->isVirtual()) {
669 Start = I - 1;
670 break;
671 }
672 }
673
674 // Now add all bases.
675 for (unsigned I = Start, E = Path.size(); I != E; ++I)
John McCallcf142162010-08-07 06:22:56 +0000676 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
Anders Carlssona70cff62010-04-24 19:06:50 +0000677}
678
Douglas Gregor88d292c2010-05-13 16:44:06 +0000679/// \brief Determine whether the given base path includes a virtual
680/// base class.
John McCallcf142162010-08-07 06:22:56 +0000681bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
682 for (CXXCastPath::const_iterator B = BasePath.begin(),
683 BEnd = BasePath.end();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000684 B != BEnd; ++B)
685 if ((*B)->isVirtual())
686 return true;
687
688 return false;
689}
690
Douglas Gregor36d1b142009-10-06 17:59:45 +0000691/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
692/// conversion (where Derived and Base are class types) is
693/// well-formed, meaning that the conversion is unambiguous (and
694/// that all of the base classes are accessible). Returns true
695/// and emits a diagnostic if the code is ill-formed, returns false
696/// otherwise. Loc is the location where this routine should point to
697/// if there is an error, and Range is the source range to highlight
698/// if there is an error.
699bool
700Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
John McCall1064d7e2010-03-16 05:22:47 +0000701 unsigned InaccessibleBaseID,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000702 unsigned AmbigiousBaseConvID,
703 SourceLocation Loc, SourceRange Range,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000704 DeclarationName Name,
John McCallcf142162010-08-07 06:22:56 +0000705 CXXCastPath *BasePath) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000706 // First, determine whether the path from Derived to Base is
707 // ambiguous. This is slightly more expensive than checking whether
708 // the Derived to Base conversion exists, because here we need to
709 // explore multiple paths to determine if there is an ambiguity.
710 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
711 /*DetectVirtual=*/false);
712 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
713 assert(DerivationOkay &&
714 "Can only be used with a derived-to-base conversion");
715 (void)DerivationOkay;
716
717 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
Anders Carlssona70cff62010-04-24 19:06:50 +0000718 if (InaccessibleBaseID) {
719 // Check that the base class can be accessed.
720 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
721 InaccessibleBaseID)) {
722 case AR_inaccessible:
723 return true;
724 case AR_accessible:
725 case AR_dependent:
726 case AR_delayed:
727 break;
Anders Carlsson7afe4242010-04-24 17:11:09 +0000728 }
John McCall5b0829a2010-02-10 09:31:12 +0000729 }
Anders Carlssona70cff62010-04-24 19:06:50 +0000730
731 // Build a base path if necessary.
732 if (BasePath)
733 BuildBasePathArray(Paths, *BasePath);
734 return false;
Douglas Gregor36d1b142009-10-06 17:59:45 +0000735 }
736
737 // We know that the derived-to-base conversion is ambiguous, and
738 // we're going to produce a diagnostic. Perform the derived-to-base
739 // search just one more time to compute all of the possible paths so
740 // that we can print them out. This is more expensive than any of
741 // the previous derived-to-base checks we've done, but at this point
742 // performance isn't as much of an issue.
743 Paths.clear();
744 Paths.setRecordingPaths(true);
745 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
746 assert(StillOkay && "Can only be used with a derived-to-base conversion");
747 (void)StillOkay;
748
749 // Build up a textual representation of the ambiguous paths, e.g.,
750 // D -> B -> A, that will be used to illustrate the ambiguous
751 // conversions in the diagnostic. We only print one of the paths
752 // to each base class subobject.
753 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
754
755 Diag(Loc, AmbigiousBaseConvID)
756 << Derived << Base << PathDisplayStr << Range << Name;
757 return true;
758}
759
760bool
761Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
Sebastian Redl7c353682009-11-14 21:15:49 +0000762 SourceLocation Loc, SourceRange Range,
John McCallcf142162010-08-07 06:22:56 +0000763 CXXCastPath *BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +0000764 bool IgnoreAccess) {
Douglas Gregor36d1b142009-10-06 17:59:45 +0000765 return CheckDerivedToBaseConversion(Derived, Base,
John McCall1064d7e2010-03-16 05:22:47 +0000766 IgnoreAccess ? 0
767 : diag::err_upcast_to_inaccessible_base,
Douglas Gregor36d1b142009-10-06 17:59:45 +0000768 diag::err_ambiguous_derived_to_base_conv,
Anders Carlsson7afe4242010-04-24 17:11:09 +0000769 Loc, Range, DeclarationName(),
770 BasePath);
Douglas Gregor36d1b142009-10-06 17:59:45 +0000771}
772
773
774/// @brief Builds a string representing ambiguous paths from a
775/// specific derived class to different subobjects of the same base
776/// class.
777///
778/// This function builds a string that can be used in error messages
779/// to show the different paths that one can take through the
780/// inheritance hierarchy to go from the derived class to different
781/// subobjects of a base class. The result looks something like this:
782/// @code
783/// struct D -> struct B -> struct A
784/// struct D -> struct C -> struct A
785/// @endcode
786std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
787 std::string PathDisplayStr;
788 std::set<unsigned> DisplayedPaths;
789 for (CXXBasePaths::paths_iterator Path = Paths.begin();
790 Path != Paths.end(); ++Path) {
791 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
792 // We haven't displayed a path to this particular base
793 // class subobject yet.
794 PathDisplayStr += "\n ";
795 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
796 for (CXXBasePath::const_iterator Element = Path->begin();
797 Element != Path->end(); ++Element)
798 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
799 }
800 }
801
802 return PathDisplayStr;
803}
804
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000805//===----------------------------------------------------------------------===//
806// C++ class member Handling
807//===----------------------------------------------------------------------===//
808
Abramo Bagnarad7340582010-06-05 05:09:32 +0000809/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
John McCall48871652010-08-21 09:40:31 +0000810Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
811 SourceLocation ASLoc,
812 SourceLocation ColonLoc) {
Abramo Bagnarad7340582010-06-05 05:09:32 +0000813 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
John McCall48871652010-08-21 09:40:31 +0000814 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
Abramo Bagnarad7340582010-06-05 05:09:32 +0000815 ASLoc, ColonLoc);
816 CurContext->addHiddenDecl(ASDecl);
John McCall48871652010-08-21 09:40:31 +0000817 return ASDecl;
Abramo Bagnarad7340582010-06-05 05:09:32 +0000818}
819
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000820/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
821/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
822/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnereb4373d2009-04-12 22:37:57 +0000823/// any.
John McCall48871652010-08-21 09:40:31 +0000824Decl *
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000825Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor3447e762009-08-20 22:52:58 +0000826 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redld6f78502009-11-24 23:38:44 +0000827 ExprTy *BW, ExprTy *InitExpr, bool IsDefinition,
828 bool Deleted) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000829 const DeclSpec &DS = D.getDeclSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +0000830 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
831 DeclarationName Name = NameInfo.getName();
832 SourceLocation Loc = NameInfo.getLoc();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000833 Expr *BitWidth = static_cast<Expr*>(BW);
834 Expr *Init = static_cast<Expr*>(InitExpr);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000835
John McCallb1cd7da2010-06-04 08:34:12 +0000836 assert(isa<CXXRecordDecl>(CurContext));
John McCall07e91c02009-08-06 02:15:43 +0000837 assert(!DS.isFriendSpecified());
838
John McCallb1cd7da2010-06-04 08:34:12 +0000839 bool isFunc = false;
840 if (D.isFunctionDeclarator())
841 isFunc = true;
842 else if (D.getNumTypeObjects() == 0 &&
843 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
John McCallba7bf592010-08-24 05:47:05 +0000844 QualType TDType = GetTypeFromParser(DS.getRepAsType());
John McCallb1cd7da2010-06-04 08:34:12 +0000845 isFunc = TDType->isFunctionType();
846 }
847
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000848 // C++ 9.2p6: A member shall not be declared to have automatic storage
849 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000850 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
851 // data members and cannot be applied to names declared const or static,
852 // and cannot be applied to reference members.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000853 switch (DS.getStorageClassSpec()) {
854 case DeclSpec::SCS_unspecified:
855 case DeclSpec::SCS_typedef:
856 case DeclSpec::SCS_static:
857 // FALL THROUGH.
858 break;
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000859 case DeclSpec::SCS_mutable:
860 if (isFunc) {
861 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner3b054132008-11-19 05:08:23 +0000862 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000863 else
Chris Lattner3b054132008-11-19 05:08:23 +0000864 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
Mike Stump11289f42009-09-09 15:08:12 +0000865
Sebastian Redl8071edb2008-11-17 23:24:37 +0000866 // FIXME: It would be nicer if the keyword was ignored only for this
867 // declarator. Otherwise we could get follow-up errors.
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000868 D.getMutableDeclSpec().ClearStorageClassSpecs();
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000869 }
870 break;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000871 default:
872 if (DS.getStorageClassSpecLoc().isValid())
873 Diag(DS.getStorageClassSpecLoc(),
874 diag::err_storageclass_invalid_for_member);
875 else
876 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
877 D.getMutableDeclSpec().ClearStorageClassSpecs();
878 }
879
Sebastian Redlccdfaba2008-11-14 23:42:31 +0000880 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
881 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidis1207d312008-10-08 22:20:31 +0000882 !isFunc);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000883
884 Decl *Member;
Chris Lattner73bf7b42009-03-05 22:45:59 +0000885 if (isInstField) {
Douglas Gregor3447e762009-08-20 22:52:58 +0000886 // FIXME: Check for template parameters!
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000887 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
888 AS);
Chris Lattner97e277e2009-03-05 23:03:49 +0000889 assert(Member && "HandleField never returns null");
Chris Lattner73bf7b42009-03-05 22:45:59 +0000890 } else {
John McCall48871652010-08-21 09:40:31 +0000891 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
Chris Lattner97e277e2009-03-05 23:03:49 +0000892 if (!Member) {
John McCall48871652010-08-21 09:40:31 +0000893 return 0;
Chris Lattner97e277e2009-03-05 23:03:49 +0000894 }
Chris Lattnerd26760a2009-03-05 23:01:03 +0000895
896 // Non-instance-fields can't have a bitfield.
897 if (BitWidth) {
898 if (Member->isInvalidDecl()) {
899 // don't emit another diagnostic.
Douglas Gregor212cab32009-03-11 20:22:50 +0000900 } else if (isa<VarDecl>(Member)) {
Chris Lattnerd26760a2009-03-05 23:01:03 +0000901 // C++ 9.6p3: A bit-field shall not be a static member.
902 // "static member 'A' cannot be a bit-field"
903 Diag(Loc, diag::err_static_not_bitfield)
904 << Name << BitWidth->getSourceRange();
905 } else if (isa<TypedefDecl>(Member)) {
906 // "typedef member 'x' cannot be a bit-field"
907 Diag(Loc, diag::err_typedef_not_bitfield)
908 << Name << BitWidth->getSourceRange();
909 } else {
910 // A function typedef ("typedef int f(); f a;").
911 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
912 Diag(Loc, diag::err_not_integral_type_bitfield)
Mike Stump11289f42009-09-09 15:08:12 +0000913 << Name << cast<ValueDecl>(Member)->getType()
Douglas Gregor1efa4372009-03-11 18:59:21 +0000914 << BitWidth->getSourceRange();
Chris Lattnerd26760a2009-03-05 23:01:03 +0000915 }
Mike Stump11289f42009-09-09 15:08:12 +0000916
Chris Lattnerd26760a2009-03-05 23:01:03 +0000917 BitWidth = 0;
918 Member->setInvalidDecl();
919 }
Douglas Gregor4261e4c2009-03-11 20:50:30 +0000920
921 Member->setAccess(AS);
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregor3447e762009-08-20 22:52:58 +0000923 // If we have declared a member function template, set the access of the
924 // templated declaration as well.
925 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
926 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner73bf7b42009-03-05 22:45:59 +0000927 }
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000928
Douglas Gregor92751d42008-11-17 22:58:34 +0000929 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000930
Douglas Gregor0c880302009-03-11 23:00:04 +0000931 if (Init)
John McCallb268a282010-08-23 23:25:46 +0000932 AddInitializerToDecl(Member, Init, false);
Sebastian Redl42e92c42009-04-12 17:16:29 +0000933 if (Deleted) // FIXME: Source location is not very good.
John McCall48871652010-08-21 09:40:31 +0000934 SetDeclDeleted(Member, D.getSourceRange().getBegin());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000935
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000936 if (isInstField) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000937 FieldCollector->Add(cast<FieldDecl>(Member));
John McCall48871652010-08-21 09:40:31 +0000938 return 0;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000939 }
John McCall48871652010-08-21 09:40:31 +0000940 return Member;
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000941}
942
Douglas Gregor15e77a22009-12-31 09:10:24 +0000943/// \brief Find the direct and/or virtual base specifiers that
944/// correspond to the given base type, for use in base initialization
945/// within a constructor.
946static bool FindBaseInitializer(Sema &SemaRef,
947 CXXRecordDecl *ClassDecl,
948 QualType BaseType,
949 const CXXBaseSpecifier *&DirectBaseSpec,
950 const CXXBaseSpecifier *&VirtualBaseSpec) {
951 // First, check for a direct base class.
952 DirectBaseSpec = 0;
953 for (CXXRecordDecl::base_class_const_iterator Base
954 = ClassDecl->bases_begin();
955 Base != ClassDecl->bases_end(); ++Base) {
956 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
957 // We found a direct base of this type. That's what we're
958 // initializing.
959 DirectBaseSpec = &*Base;
960 break;
961 }
962 }
963
964 // Check for a virtual base class.
965 // FIXME: We might be able to short-circuit this if we know in advance that
966 // there are no virtual bases.
967 VirtualBaseSpec = 0;
968 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
969 // We haven't found a base yet; search the class hierarchy for a
970 // virtual base class.
971 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
972 /*DetectVirtual=*/false);
973 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
974 BaseType, Paths)) {
975 for (CXXBasePaths::paths_iterator Path = Paths.begin();
976 Path != Paths.end(); ++Path) {
977 if (Path->back().Base->isVirtual()) {
978 VirtualBaseSpec = Path->back().Base;
979 break;
980 }
981 }
982 }
983 }
984
985 return DirectBaseSpec || VirtualBaseSpec;
986}
987
Douglas Gregore8381c02008-11-05 04:29:56 +0000988/// ActOnMemInitializer - Handle a C++ member initializer.
John McCallfaf5fb42010-08-26 23:41:50 +0000989MemInitResult
John McCall48871652010-08-21 09:40:31 +0000990Sema::ActOnMemInitializer(Decl *ConstructorD,
Douglas Gregore8381c02008-11-05 04:29:56 +0000991 Scope *S,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +0000992 CXXScopeSpec &SS,
Douglas Gregore8381c02008-11-05 04:29:56 +0000993 IdentifierInfo *MemberOrBase,
John McCallba7bf592010-08-24 05:47:05 +0000994 ParsedType TemplateTypeTy,
Douglas Gregore8381c02008-11-05 04:29:56 +0000995 SourceLocation IdLoc,
996 SourceLocation LParenLoc,
997 ExprTy **Args, unsigned NumArgs,
Douglas Gregore8381c02008-11-05 04:29:56 +0000998 SourceLocation RParenLoc) {
Douglas Gregor71a57182009-06-22 23:20:33 +0000999 if (!ConstructorD)
1000 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001001
Douglas Gregorc8c277a2009-08-24 11:57:43 +00001002 AdjustDeclIfTemplate(ConstructorD);
Mike Stump11289f42009-09-09 15:08:12 +00001003
1004 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00001005 = dyn_cast<CXXConstructorDecl>(ConstructorD);
Douglas Gregore8381c02008-11-05 04:29:56 +00001006 if (!Constructor) {
1007 // The user wrote a constructor initializer on a function that is
1008 // not a C++ constructor. Ignore the error for now, because we may
1009 // have more member initializers coming; we'll diagnose it just
1010 // once in ActOnMemInitializers.
1011 return true;
1012 }
1013
1014 CXXRecordDecl *ClassDecl = Constructor->getParent();
1015
1016 // C++ [class.base.init]p2:
1017 // Names in a mem-initializer-id are looked up in the scope of the
1018 // constructor’s class and, if not found in that scope, are looked
1019 // up in the scope containing the constructor’s
1020 // definition. [Note: if the constructor’s class contains a member
1021 // with the same name as a direct or virtual base class of the
1022 // class, a mem-initializer-id naming the member or base class and
1023 // composed of a single identifier refers to the class member. A
1024 // mem-initializer-id for the hidden base class may be specified
1025 // using a qualified name. ]
Fariborz Jahanianc1fc3ec2009-07-01 19:21:19 +00001026 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001027 // Look for a member, first.
1028 FieldDecl *Member = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001029 DeclContext::lookup_result Result
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001030 = ClassDecl->lookup(MemberOrBase);
1031 if (Result.first != Result.second)
1032 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregore8381c02008-11-05 04:29:56 +00001033
Fariborz Jahanian302bb662009-06-30 23:26:25 +00001034 // FIXME: Handle members of an anonymous union.
Douglas Gregore8381c02008-11-05 04:29:56 +00001035
Eli Friedman8e1433b2009-07-29 19:44:27 +00001036 if (Member)
1037 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001038 LParenLoc, RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001039 }
Douglas Gregore8381c02008-11-05 04:29:56 +00001040 // It didn't name a member, so see if it names a class.
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001041 QualType BaseType;
John McCallbcd03502009-12-07 02:54:59 +00001042 TypeSourceInfo *TInfo = 0;
John McCallb5a0d312009-12-21 10:41:20 +00001043
1044 if (TemplateTypeTy) {
John McCallbcd03502009-12-07 02:54:59 +00001045 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
John McCallb5a0d312009-12-21 10:41:20 +00001046 } else {
1047 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1048 LookupParsedName(R, S, &SS);
1049
1050 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1051 if (!TyD) {
1052 if (R.isAmbiguous()) return true;
1053
John McCallda6841b2010-04-09 19:01:14 +00001054 // We don't want access-control diagnostics here.
1055 R.suppressDiagnostics();
1056
Douglas Gregora3b624a2010-01-19 06:46:48 +00001057 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1058 bool NotUnknownSpecialization = false;
1059 DeclContext *DC = computeDeclContext(SS, false);
1060 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1061 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1062
1063 if (!NotUnknownSpecialization) {
1064 // When the scope specifier can refer to a member of an unknown
1065 // specialization, we take it as a type name.
Douglas Gregorbbdf20a2010-04-24 15:35:55 +00001066 BaseType = CheckTypenameType(ETK_None,
1067 (NestedNameSpecifier *)SS.getScopeRep(),
Abramo Bagnarad7548482010-05-19 21:37:53 +00001068 *MemberOrBase, SourceLocation(),
1069 SS.getRange(), IdLoc);
Douglas Gregor281c4862010-03-07 23:26:22 +00001070 if (BaseType.isNull())
1071 return true;
1072
Douglas Gregora3b624a2010-01-19 06:46:48 +00001073 R.clear();
Douglas Gregorc048c522010-06-29 19:27:42 +00001074 R.setLookupName(MemberOrBase);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001075 }
1076 }
1077
Douglas Gregor15e77a22009-12-31 09:10:24 +00001078 // If no results were found, try to correct typos.
Douglas Gregora3b624a2010-01-19 06:46:48 +00001079 if (R.empty() && BaseType.isNull() &&
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001080 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1081 R.isSingleResult()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001082 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00001083 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001084 // We have found a non-static data member with a similar
1085 // name to what was typed; complain and initialize that
1086 // member.
1087 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1088 << MemberOrBase << true << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001089 << FixItHint::CreateReplacement(R.getNameLoc(),
1090 R.getLookupName().getAsString());
Douglas Gregor6da83622010-01-07 00:17:44 +00001091 Diag(Member->getLocation(), diag::note_previous_decl)
1092 << Member->getDeclName();
Douglas Gregor15e77a22009-12-31 09:10:24 +00001093
1094 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1095 LParenLoc, RParenLoc);
1096 }
1097 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1098 const CXXBaseSpecifier *DirectBaseSpec;
1099 const CXXBaseSpecifier *VirtualBaseSpec;
1100 if (FindBaseInitializer(*this, ClassDecl,
1101 Context.getTypeDeclType(Type),
1102 DirectBaseSpec, VirtualBaseSpec)) {
1103 // We have found a direct or virtual base class with a
1104 // similar name to what was typed; complain and initialize
1105 // that base class.
1106 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1107 << MemberOrBase << false << R.getLookupName()
Douglas Gregora771f462010-03-31 17:46:05 +00001108 << FixItHint::CreateReplacement(R.getNameLoc(),
1109 R.getLookupName().getAsString());
Douglas Gregor43a08572010-01-07 00:26:25 +00001110
1111 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1112 : VirtualBaseSpec;
1113 Diag(BaseSpec->getSourceRange().getBegin(),
1114 diag::note_base_class_specified_here)
1115 << BaseSpec->getType()
1116 << BaseSpec->getSourceRange();
1117
Douglas Gregor15e77a22009-12-31 09:10:24 +00001118 TyD = Type;
1119 }
1120 }
1121 }
1122
Douglas Gregora3b624a2010-01-19 06:46:48 +00001123 if (!TyD && BaseType.isNull()) {
Douglas Gregor15e77a22009-12-31 09:10:24 +00001124 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1125 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1126 return true;
1127 }
John McCallb5a0d312009-12-21 10:41:20 +00001128 }
1129
Douglas Gregora3b624a2010-01-19 06:46:48 +00001130 if (BaseType.isNull()) {
1131 BaseType = Context.getTypeDeclType(TyD);
1132 if (SS.isSet()) {
1133 NestedNameSpecifier *Qualifier =
1134 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
John McCallb5a0d312009-12-21 10:41:20 +00001135
Douglas Gregora3b624a2010-01-19 06:46:48 +00001136 // FIXME: preserve source range information
Abramo Bagnara6150c882010-05-11 21:36:43 +00001137 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
Douglas Gregora3b624a2010-01-19 06:46:48 +00001138 }
John McCallb5a0d312009-12-21 10:41:20 +00001139 }
1140 }
Mike Stump11289f42009-09-09 15:08:12 +00001141
John McCallbcd03502009-12-07 02:54:59 +00001142 if (!TInfo)
1143 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001144
John McCallbcd03502009-12-07 02:54:59 +00001145 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001146 LParenLoc, RParenLoc, ClassDecl);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001147}
1148
John McCalle22a04a2009-11-04 23:02:40 +00001149/// Checks an initializer expression for use of uninitialized fields, such as
1150/// containing the field that is being initialized. Returns true if there is an
1151/// uninitialized field was used an updates the SourceLocation parameter; false
1152/// otherwise.
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001153static bool InitExprContainsUninitializedFields(const Stmt *S,
1154 const FieldDecl *LhsField,
1155 SourceLocation *L) {
1156 if (isa<CallExpr>(S)) {
1157 // Do not descend into function calls or constructors, as the use
1158 // of an uninitialized field may be valid. One would have to inspect
1159 // the contents of the function/ctor to determine if it is safe or not.
1160 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1161 // may be safe, depending on what the function/ctor does.
1162 return false;
1163 }
1164 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1165 const NamedDecl *RhsField = ME->getMemberDecl();
John McCalle22a04a2009-11-04 23:02:40 +00001166 if (RhsField == LhsField) {
1167 // Initializing a field with itself. Throw a warning.
1168 // But wait; there are exceptions!
1169 // Exception #1: The field may not belong to this record.
1170 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001171 const Expr *base = ME->getBase();
John McCalle22a04a2009-11-04 23:02:40 +00001172 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1173 // Even though the field matches, it does not belong to this record.
1174 return false;
1175 }
1176 // None of the exceptions triggered; return true to indicate an
1177 // uninitialized field was used.
1178 *L = ME->getMemberLoc();
1179 return true;
1180 }
Argyrios Kyrtzidis03f0e2b2010-09-21 10:47:20 +00001181 } else if (isa<SizeOfAlignOfExpr>(S)) {
1182 // sizeof/alignof doesn't reference contents, do not warn.
1183 return false;
1184 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1185 // address-of doesn't reference contents (the pointer may be dereferenced
1186 // in the same expression but it would be rare; and weird).
1187 if (UOE->getOpcode() == UO_AddrOf)
1188 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001189 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001190 for (Stmt::const_child_iterator it = S->child_begin(), e = S->child_end();
1191 it != e; ++it) {
1192 if (!*it) {
1193 // An expression such as 'member(arg ?: "")' may trigger this.
John McCalle22a04a2009-11-04 23:02:40 +00001194 continue;
1195 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001196 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1197 return true;
John McCalle22a04a2009-11-04 23:02:40 +00001198 }
Nick Lewyckya2fb98b2010-06-15 07:32:55 +00001199 return false;
John McCalle22a04a2009-11-04 23:02:40 +00001200}
1201
John McCallfaf5fb42010-08-26 23:41:50 +00001202MemInitResult
Eli Friedman8e1433b2009-07-29 19:44:27 +00001203Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
1204 unsigned NumArgs, SourceLocation IdLoc,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001205 SourceLocation LParenLoc,
Eli Friedman8e1433b2009-07-29 19:44:27 +00001206 SourceLocation RParenLoc) {
John McCalle22a04a2009-11-04 23:02:40 +00001207 // Diagnose value-uses of fields to initialize themselves, e.g.
1208 // foo(foo)
1209 // where foo is not also a parameter to the constructor.
John McCallc90f6d72009-11-04 23:13:52 +00001210 // TODO: implement -Wuninitialized and fold this into that framework.
John McCalle22a04a2009-11-04 23:02:40 +00001211 for (unsigned i = 0; i < NumArgs; ++i) {
1212 SourceLocation L;
1213 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1214 // FIXME: Return true in the case when other fields are used before being
1215 // uninitialized. For example, let this field be the i'th field. When
1216 // initializing the i'th field, throw a warning if any of the >= i'th
1217 // fields are used, as they are not yet initialized.
1218 // Right now we are only handling the case where the i'th field uses
1219 // itself in its initializer.
1220 Diag(L, diag::warn_field_is_uninit);
1221 }
1222 }
1223
Eli Friedman8e1433b2009-07-29 19:44:27 +00001224 bool HasDependentArg = false;
1225 for (unsigned i = 0; i < NumArgs; i++)
1226 HasDependentArg |= Args[i]->isTypeDependent();
1227
Eli Friedman9255adf2010-07-24 21:19:15 +00001228 if (Member->getType()->isDependentType() || HasDependentArg) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001229 // Can't check initialization for a member of dependent type or when
1230 // any of the arguments are type-dependent expressions.
John McCallb268a282010-08-23 23:25:46 +00001231 Expr *Init
1232 = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1233 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001234
1235 // Erase any temporaries within this evaluation context; we're not
1236 // going to track them in the AST, since we'll be rebuilding the
1237 // ASTs during template instantiation.
1238 ExprTemporaries.erase(
1239 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1240 ExprTemporaries.end());
1241
1242 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1243 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001244 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001245 RParenLoc);
1246
Douglas Gregore8381c02008-11-05 04:29:56 +00001247 }
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001248
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001249 if (Member->isInvalidDecl())
1250 return true;
Anders Carlsson1fe64cb2009-11-13 19:21:49 +00001251
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001252 // Initialize the member.
1253 InitializedEntity MemberEntity =
1254 InitializedEntity::InitializeMember(Member, 0);
1255 InitializationKind Kind =
1256 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1257
1258 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1259
John McCalldadc5752010-08-24 06:29:42 +00001260 ExprResult MemberInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001261 InitSeq.Perform(*this, MemberEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001262 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001263 if (MemberInit.isInvalid())
1264 return true;
1265
1266 // C++0x [class.base.init]p7:
1267 // The initialization of each base and member constitutes a
1268 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001269 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001270 if (MemberInit.isInvalid())
1271 return true;
1272
1273 // If we are in a dependent context, template instantiation will
1274 // perform this type-checking again. Just save the arguments that we
1275 // received in a ParenListExpr.
1276 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1277 // of the information that we have about the member
1278 // initializer. However, deconstructing the ASTs is a dicey process,
1279 // and this approach is far more likely to get the corner cases right.
1280 if (CurContext->isDependentContext()) {
1281 // Bump the reference count of all of the arguments.
1282 for (unsigned I = 0; I != NumArgs; ++I)
1283 Args[I]->Retain();
1284
John McCallb268a282010-08-23 23:25:46 +00001285 Expr *Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1286 RParenLoc);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001287 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
1288 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001289 Init,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001290 RParenLoc);
1291 }
1292
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001293 return new (Context) CXXBaseOrMemberInitializer(Context, Member, IdLoc,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001294 LParenLoc,
John McCallb268a282010-08-23 23:25:46 +00001295 MemberInit.get(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001296 RParenLoc);
Eli Friedman8e1433b2009-07-29 19:44:27 +00001297}
1298
John McCallfaf5fb42010-08-26 23:41:50 +00001299MemInitResult
John McCallbcd03502009-12-07 02:54:59 +00001300Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00001301 Expr **Args, unsigned NumArgs,
1302 SourceLocation LParenLoc, SourceLocation RParenLoc,
1303 CXXRecordDecl *ClassDecl) {
Eli Friedman8e1433b2009-07-29 19:44:27 +00001304 bool HasDependentArg = false;
1305 for (unsigned i = 0; i < NumArgs; i++)
1306 HasDependentArg |= Args[i]->isTypeDependent();
1307
Douglas Gregor1c69bf02010-06-16 16:03:14 +00001308 SourceLocation BaseLoc
1309 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1310
1311 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1312 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1313 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1314
1315 // C++ [class.base.init]p2:
1316 // [...] Unless the mem-initializer-id names a nonstatic data
1317 // member of the constructor’s class or a direct or virtual base
1318 // of that class, the mem-initializer is ill-formed. A
1319 // mem-initializer-list can initialize a base class using any
1320 // name that denotes that base class type.
1321 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1322
1323 // Check for direct and virtual base classes.
1324 const CXXBaseSpecifier *DirectBaseSpec = 0;
1325 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1326 if (!Dependent) {
1327 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1328 VirtualBaseSpec);
1329
1330 // C++ [base.class.init]p2:
1331 // Unless the mem-initializer-id names a nonstatic data member of the
1332 // constructor's class or a direct or virtual base of that class, the
1333 // mem-initializer is ill-formed.
1334 if (!DirectBaseSpec && !VirtualBaseSpec) {
1335 // If the class has any dependent bases, then it's possible that
1336 // one of those types will resolve to the same type as
1337 // BaseType. Therefore, just treat this as a dependent base
1338 // class initialization. FIXME: Should we try to check the
1339 // initialization anyway? It seems odd.
1340 if (ClassDecl->hasAnyDependentBases())
1341 Dependent = true;
1342 else
1343 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1344 << BaseType << Context.getTypeDeclType(ClassDecl)
1345 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1346 }
1347 }
1348
1349 if (Dependent) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001350 // Can't check initialization for a base of dependent type or when
1351 // any of the arguments are type-dependent expressions.
John McCalldadc5752010-08-24 06:29:42 +00001352 ExprResult BaseInit
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001353 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1354 RParenLoc));
Eli Friedman8e1433b2009-07-29 19:44:27 +00001355
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001356 // Erase any temporaries within this evaluation context; we're not
1357 // going to track them in the AST, since we'll be rebuilding the
1358 // ASTs during template instantiation.
1359 ExprTemporaries.erase(
1360 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1361 ExprTemporaries.end());
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001363 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001364 /*IsVirtual=*/false,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001365 LParenLoc,
1366 BaseInit.takeAs<Expr>(),
1367 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001368 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001369
1370 // C++ [base.class.init]p2:
1371 // If a mem-initializer-id is ambiguous because it designates both
1372 // a direct non-virtual base class and an inherited virtual base
1373 // class, the mem-initializer is ill-formed.
1374 if (DirectBaseSpec && VirtualBaseSpec)
1375 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00001376 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001377
1378 CXXBaseSpecifier *BaseSpec
1379 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1380 if (!BaseSpec)
1381 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1382
1383 // Initialize the base.
1384 InitializedEntity BaseEntity =
Anders Carlsson43c64af2010-04-21 19:52:01 +00001385 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001386 InitializationKind Kind =
1387 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1388
1389 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1390
John McCalldadc5752010-08-24 06:29:42 +00001391 ExprResult BaseInit =
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001392 InitSeq.Perform(*this, BaseEntity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00001393 MultiExprArg(*this, Args, NumArgs), 0);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001394 if (BaseInit.isInvalid())
1395 return true;
1396
1397 // C++0x [class.base.init]p7:
1398 // The initialization of each base and member constitutes a
1399 // full-expression.
John McCallb268a282010-08-23 23:25:46 +00001400 BaseInit = MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001401 if (BaseInit.isInvalid())
1402 return true;
1403
1404 // If we are in a dependent context, template instantiation will
1405 // perform this type-checking again. Just save the arguments that we
1406 // received in a ParenListExpr.
1407 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1408 // of the information that we have about the base
1409 // initializer. However, deconstructing the ASTs is a dicey process,
1410 // and this approach is far more likely to get the corner cases right.
1411 if (CurContext->isDependentContext()) {
1412 // Bump the reference count of all of the arguments.
1413 for (unsigned I = 0; I != NumArgs; ++I)
1414 Args[I]->Retain();
1415
John McCalldadc5752010-08-24 06:29:42 +00001416 ExprResult Init
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001417 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1418 RParenLoc));
1419 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001420 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001421 LParenLoc,
1422 Init.takeAs<Expr>(),
1423 RParenLoc);
1424 }
1425
1426 return new (Context) CXXBaseOrMemberInitializer(Context, BaseTInfo,
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +00001427 BaseSpec->isVirtual(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001428 LParenLoc,
1429 BaseInit.takeAs<Expr>(),
1430 RParenLoc);
Douglas Gregore8381c02008-11-05 04:29:56 +00001431}
1432
Anders Carlsson1b00e242010-04-23 03:10:23 +00001433/// ImplicitInitializerKind - How an implicit base or member initializer should
1434/// initialize its base or member.
1435enum ImplicitInitializerKind {
1436 IIK_Default,
1437 IIK_Copy,
1438 IIK_Move
1439};
1440
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001441static bool
Anders Carlsson3c1db572010-04-23 02:15:47 +00001442BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001443 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson43c64af2010-04-21 19:52:01 +00001444 CXXBaseSpecifier *BaseSpec,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001445 bool IsInheritedVirtualBase,
1446 CXXBaseOrMemberInitializer *&CXXBaseInit) {
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001447 InitializedEntity InitEntity
Anders Carlsson43c64af2010-04-21 19:52:01 +00001448 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1449 IsInheritedVirtualBase);
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001450
John McCalldadc5752010-08-24 06:29:42 +00001451 ExprResult BaseInit;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001452
1453 switch (ImplicitInitKind) {
1454 case IIK_Default: {
1455 InitializationKind InitKind
1456 = InitializationKind::CreateDefault(Constructor->getLocation());
1457 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1458 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001459 MultiExprArg(SemaRef, 0, 0));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001460 break;
1461 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001462
Anders Carlsson1b00e242010-04-23 03:10:23 +00001463 case IIK_Copy: {
1464 ParmVarDecl *Param = Constructor->getParamDecl(0);
1465 QualType ParamType = Param->getType().getNonReferenceType();
1466
1467 Expr *CopyCtorArg =
1468 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregored088b72010-05-03 15:43:53 +00001469 Constructor->getLocation(), ParamType, 0);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001470
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001471 // Cast to the base class to avoid ambiguities.
Anders Carlsson79111502010-05-01 16:39:01 +00001472 QualType ArgTy =
1473 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1474 ParamType.getQualifiers());
John McCallcf142162010-08-07 06:22:56 +00001475
1476 CXXCastPath BasePath;
1477 BasePath.push_back(BaseSpec);
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001478 SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
John McCalle3027922010-08-25 11:45:40 +00001479 CK_UncheckedDerivedToBase,
John McCall2536c6d2010-08-25 10:28:54 +00001480 VK_LValue, &BasePath);
Anders Carlssonaf13c7b2010-04-24 22:02:54 +00001481
Anders Carlsson1b00e242010-04-23 03:10:23 +00001482 InitializationKind InitKind
1483 = InitializationKind::CreateDirect(Constructor->getLocation(),
1484 SourceLocation(), SourceLocation());
1485 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1486 &CopyCtorArg, 1);
1487 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001488 MultiExprArg(&CopyCtorArg, 1));
Anders Carlsson1b00e242010-04-23 03:10:23 +00001489 break;
1490 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001491
Anders Carlsson1b00e242010-04-23 03:10:23 +00001492 case IIK_Move:
1493 assert(false && "Unhandled initializer kind!");
1494 }
John McCallb268a282010-08-23 23:25:46 +00001495
1496 if (BaseInit.isInvalid())
1497 return true;
Anders Carlsson1b00e242010-04-23 03:10:23 +00001498
John McCallb268a282010-08-23 23:25:46 +00001499 BaseInit = SemaRef.MaybeCreateCXXExprWithTemporaries(BaseInit.get());
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001500 if (BaseInit.isInvalid())
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001501 return true;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001502
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001503 CXXBaseInit =
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001504 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
1505 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1506 SourceLocation()),
1507 BaseSpec->isVirtual(),
1508 SourceLocation(),
1509 BaseInit.takeAs<Expr>(),
1510 SourceLocation());
1511
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001512 return false;
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001513}
1514
Anders Carlsson3c1db572010-04-23 02:15:47 +00001515static bool
1516BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001517 ImplicitInitializerKind ImplicitInitKind,
Anders Carlsson3c1db572010-04-23 02:15:47 +00001518 FieldDecl *Field,
1519 CXXBaseOrMemberInitializer *&CXXMemberInit) {
Douglas Gregor3f4f03a2010-05-20 22:12:02 +00001520 if (Field->isInvalidDecl())
1521 return true;
1522
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001523 SourceLocation Loc = Constructor->getLocation();
1524
Anders Carlsson423f5d82010-04-23 16:04:08 +00001525 if (ImplicitInitKind == IIK_Copy) {
1526 ParmVarDecl *Param = Constructor->getParamDecl(0);
1527 QualType ParamType = Param->getType().getNonReferenceType();
1528
1529 Expr *MemberExprBase =
1530 DeclRefExpr::Create(SemaRef.Context, 0, SourceRange(), Param,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001531 Loc, ParamType, 0);
1532
1533 // Build a reference to this field within the parameter.
1534 CXXScopeSpec SS;
1535 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
1536 Sema::LookupMemberName);
1537 MemberLookup.addDecl(Field, AS_public);
1538 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00001539 ExprResult CopyCtorArg
John McCallb268a282010-08-23 23:25:46 +00001540 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001541 ParamType, Loc,
1542 /*IsArrow=*/false,
1543 SS,
1544 /*FirstQualifierInScope=*/0,
1545 MemberLookup,
1546 /*TemplateArgs=*/0);
1547 if (CopyCtorArg.isInvalid())
Anders Carlsson423f5d82010-04-23 16:04:08 +00001548 return true;
1549
Douglas Gregor94f9a482010-05-05 05:51:00 +00001550 // When the field we are copying is an array, create index variables for
1551 // each dimension of the array. We use these index variables to subscript
1552 // the source array, and other clients (e.g., CodeGen) will perform the
1553 // necessary iteration with these index variables.
1554 llvm::SmallVector<VarDecl *, 4> IndexVariables;
1555 QualType BaseType = Field->getType();
1556 QualType SizeType = SemaRef.Context.getSizeType();
1557 while (const ConstantArrayType *Array
1558 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
1559 // Create the iteration variable for this array index.
1560 IdentifierInfo *IterationVarName = 0;
1561 {
1562 llvm::SmallString<8> Str;
1563 llvm::raw_svector_ostream OS(Str);
1564 OS << "__i" << IndexVariables.size();
1565 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
1566 }
1567 VarDecl *IterationVar
1568 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc,
1569 IterationVarName, SizeType,
1570 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00001571 SC_None, SC_None);
Douglas Gregor94f9a482010-05-05 05:51:00 +00001572 IndexVariables.push_back(IterationVar);
1573
1574 // Create a reference to the iteration variable.
John McCalldadc5752010-08-24 06:29:42 +00001575 ExprResult IterationVarRef
Douglas Gregor94f9a482010-05-05 05:51:00 +00001576 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, Loc);
1577 assert(!IterationVarRef.isInvalid() &&
1578 "Reference to invented variable cannot fail!");
1579
1580 // Subscript the array with this iteration variable.
John McCallb268a282010-08-23 23:25:46 +00001581 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001582 Loc,
John McCallb268a282010-08-23 23:25:46 +00001583 IterationVarRef.take(),
Douglas Gregor94f9a482010-05-05 05:51:00 +00001584 Loc);
1585 if (CopyCtorArg.isInvalid())
1586 return true;
1587
1588 BaseType = Array->getElementType();
1589 }
1590
1591 // Construct the entity that we will be initializing. For an array, this
1592 // will be first element in the array, which may require several levels
1593 // of array-subscript entities.
1594 llvm::SmallVector<InitializedEntity, 4> Entities;
1595 Entities.reserve(1 + IndexVariables.size());
1596 Entities.push_back(InitializedEntity::InitializeMember(Field));
1597 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1598 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
1599 0,
1600 Entities.back()));
1601
1602 // Direct-initialize to use the copy constructor.
1603 InitializationKind InitKind =
1604 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
1605
1606 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
1607 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
1608 &CopyCtorArgE, 1);
1609
John McCalldadc5752010-08-24 06:29:42 +00001610 ExprResult MemberInit
Douglas Gregor94f9a482010-05-05 05:51:00 +00001611 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
John McCallfaf5fb42010-08-26 23:41:50 +00001612 MultiExprArg(&CopyCtorArgE, 1));
John McCallb268a282010-08-23 23:25:46 +00001613 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Douglas Gregor94f9a482010-05-05 05:51:00 +00001614 if (MemberInit.isInvalid())
1615 return true;
1616
1617 CXXMemberInit
1618 = CXXBaseOrMemberInitializer::Create(SemaRef.Context, Field, Loc, Loc,
1619 MemberInit.takeAs<Expr>(), Loc,
1620 IndexVariables.data(),
1621 IndexVariables.size());
Anders Carlsson1b00e242010-04-23 03:10:23 +00001622 return false;
1623 }
1624
Anders Carlsson423f5d82010-04-23 16:04:08 +00001625 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
1626
Anders Carlsson3c1db572010-04-23 02:15:47 +00001627 QualType FieldBaseElementType =
1628 SemaRef.Context.getBaseElementType(Field->getType());
1629
Anders Carlsson3c1db572010-04-23 02:15:47 +00001630 if (FieldBaseElementType->isRecordType()) {
1631 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
Anders Carlsson423f5d82010-04-23 16:04:08 +00001632 InitializationKind InitKind =
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001633 InitializationKind::CreateDefault(Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001634
1635 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00001636 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00001637 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00001638 if (MemberInit.isInvalid())
1639 return true;
1640
1641 MemberInit = SemaRef.MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Anders Carlsson3c1db572010-04-23 02:15:47 +00001642 if (MemberInit.isInvalid())
1643 return true;
1644
1645 CXXMemberInit =
1646 new (SemaRef.Context) CXXBaseOrMemberInitializer(SemaRef.Context,
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001647 Field, Loc, Loc,
John McCallb268a282010-08-23 23:25:46 +00001648 MemberInit.get(),
Chandler Carruth9c9286b2010-06-29 23:50:44 +00001649 Loc);
Anders Carlsson3c1db572010-04-23 02:15:47 +00001650 return false;
1651 }
Anders Carlssondca6be02010-04-23 03:07:47 +00001652
1653 if (FieldBaseElementType->isReferenceType()) {
1654 SemaRef.Diag(Constructor->getLocation(),
1655 diag::err_uninitialized_member_in_ctor)
1656 << (int)Constructor->isImplicit()
1657 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1658 << 0 << Field->getDeclName();
1659 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1660 return true;
1661 }
1662
1663 if (FieldBaseElementType.isConstQualified()) {
1664 SemaRef.Diag(Constructor->getLocation(),
1665 diag::err_uninitialized_member_in_ctor)
1666 << (int)Constructor->isImplicit()
1667 << SemaRef.Context.getTagDeclType(Constructor->getParent())
1668 << 1 << Field->getDeclName();
1669 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
1670 return true;
1671 }
Anders Carlsson3c1db572010-04-23 02:15:47 +00001672
1673 // Nothing to initialize.
1674 CXXMemberInit = 0;
1675 return false;
1676}
John McCallbc83b3f2010-05-20 23:23:51 +00001677
1678namespace {
1679struct BaseAndFieldInfo {
1680 Sema &S;
1681 CXXConstructorDecl *Ctor;
1682 bool AnyErrorsInInits;
1683 ImplicitInitializerKind IIK;
1684 llvm::DenseMap<const void *, CXXBaseOrMemberInitializer*> AllBaseFields;
1685 llvm::SmallVector<CXXBaseOrMemberInitializer*, 8> AllToInit;
1686
1687 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
1688 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
1689 // FIXME: Handle implicit move constructors.
1690 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
1691 IIK = IIK_Copy;
1692 else
1693 IIK = IIK_Default;
1694 }
1695};
1696}
1697
Chandler Carruth139e9622010-06-30 02:59:29 +00001698static void RecordFieldInitializer(BaseAndFieldInfo &Info,
1699 FieldDecl *Top, FieldDecl *Field,
1700 CXXBaseOrMemberInitializer *Init) {
1701 // If the member doesn't need to be initialized, Init will still be null.
1702 if (!Init)
1703 return;
1704
1705 Info.AllToInit.push_back(Init);
1706 if (Field != Top) {
1707 Init->setMember(Top);
1708 Init->setAnonUnionMember(Field);
1709 }
1710}
1711
John McCallbc83b3f2010-05-20 23:23:51 +00001712static bool CollectFieldInitializer(BaseAndFieldInfo &Info,
1713 FieldDecl *Top, FieldDecl *Field) {
1714
Chandler Carruth139e9622010-06-30 02:59:29 +00001715 // Overwhelmingly common case: we have a direct initializer for this field.
John McCallbc83b3f2010-05-20 23:23:51 +00001716 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(Field)) {
Chandler Carruth139e9622010-06-30 02:59:29 +00001717 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001718 return false;
1719 }
1720
1721 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
1722 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
1723 assert(FieldClassType && "anonymous struct/union without record type");
John McCallbc83b3f2010-05-20 23:23:51 +00001724 CXXRecordDecl *FieldClassDecl
1725 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Chandler Carruth139e9622010-06-30 02:59:29 +00001726
1727 // Even though union members never have non-trivial default
1728 // constructions in C++03, we still build member initializers for aggregate
1729 // record types which can be union members, and C++0x allows non-trivial
1730 // default constructors for union members, so we ensure that only one
1731 // member is initialized for these.
1732 if (FieldClassDecl->isUnion()) {
1733 // First check for an explicit initializer for one field.
1734 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1735 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1736 if (CXXBaseOrMemberInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
1737 RecordFieldInitializer(Info, Top, *FA, Init);
1738
1739 // Once we've initialized a field of an anonymous union, the union
1740 // field in the class is also initialized, so exit immediately.
1741 return false;
Argyrios Kyrtzidisa3ae3eb2010-08-16 17:27:13 +00001742 } else if ((*FA)->isAnonymousStructOrUnion()) {
1743 if (CollectFieldInitializer(Info, Top, *FA))
1744 return true;
Chandler Carruth139e9622010-06-30 02:59:29 +00001745 }
1746 }
1747
1748 // Fallthrough and construct a default initializer for the union as
1749 // a whole, which can call its default constructor if such a thing exists
1750 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1751 // behavior going forward with C++0x, when anonymous unions there are
1752 // finalized, we should revisit this.
1753 } else {
1754 // For structs, we simply descend through to initialize all members where
1755 // necessary.
1756 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
1757 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
1758 if (CollectFieldInitializer(Info, Top, *FA))
1759 return true;
1760 }
1761 }
John McCallbc83b3f2010-05-20 23:23:51 +00001762 }
1763
1764 // Don't try to build an implicit initializer if there were semantic
1765 // errors in any of the initializers (and therefore we might be
1766 // missing some that the user actually wrote).
1767 if (Info.AnyErrorsInInits)
1768 return false;
1769
1770 CXXBaseOrMemberInitializer *Init = 0;
1771 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
1772 return true;
John McCallbc83b3f2010-05-20 23:23:51 +00001773
Chandler Carruth139e9622010-06-30 02:59:29 +00001774 RecordFieldInitializer(Info, Top, Field, Init);
John McCallbc83b3f2010-05-20 23:23:51 +00001775 return false;
1776}
Anders Carlsson3c1db572010-04-23 02:15:47 +00001777
Eli Friedman9cf6b592009-11-09 19:20:36 +00001778bool
Anders Carlsson561f7932009-10-29 15:46:07 +00001779Sema::SetBaseOrMemberInitializers(CXXConstructorDecl *Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001780 CXXBaseOrMemberInitializer **Initializers,
1781 unsigned NumInitializers,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00001782 bool AnyErrors) {
John McCallbb7b6582010-04-10 07:37:23 +00001783 if (Constructor->getDeclContext()->isDependentContext()) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001784 // Just store the initializers as written, they will be checked during
1785 // instantiation.
1786 if (NumInitializers > 0) {
1787 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1788 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1789 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
1790 memcpy(baseOrMemberInitializers, Initializers,
1791 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
1792 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
1793 }
1794
1795 return false;
1796 }
1797
John McCallbc83b3f2010-05-20 23:23:51 +00001798 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
Anders Carlsson1b00e242010-04-23 03:10:23 +00001799
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001800 // We need to build the initializer AST according to order of construction
1801 // and not what user specified in the Initializers list.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001802 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
Douglas Gregorc14922f2010-03-26 22:43:07 +00001803 if (!ClassDecl)
1804 return true;
1805
Eli Friedman9cf6b592009-11-09 19:20:36 +00001806 bool HadError = false;
Mike Stump11289f42009-09-09 15:08:12 +00001807
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001808 for (unsigned i = 0; i < NumInitializers; i++) {
1809 CXXBaseOrMemberInitializer *Member = Initializers[i];
Anders Carlssondb0a9652010-04-02 06:26:44 +00001810
1811 if (Member->isBaseInitializer())
John McCallbc83b3f2010-05-20 23:23:51 +00001812 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001813 else
John McCallbc83b3f2010-05-20 23:23:51 +00001814 Info.AllBaseFields[Member->getMember()] = Member;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001815 }
1816
Anders Carlsson43c64af2010-04-21 19:52:01 +00001817 // Keep track of the direct virtual bases.
1818 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
1819 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
1820 E = ClassDecl->bases_end(); I != E; ++I) {
1821 if (I->isVirtual())
1822 DirectVBases.insert(I);
1823 }
1824
Anders Carlssondb0a9652010-04-02 06:26:44 +00001825 // Push virtual bases before others.
1826 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
1827 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
1828
1829 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001830 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
1831 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001832 } else if (!AnyErrors) {
Anders Carlsson43c64af2010-04-21 19:52:01 +00001833 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001834 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001835 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001836 VBase, IsInheritedVirtualBase,
1837 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001838 HadError = true;
1839 continue;
1840 }
Anders Carlssoncedc0a42010-04-20 23:11:20 +00001841
John McCallbc83b3f2010-05-20 23:23:51 +00001842 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001843 }
1844 }
Mike Stump11289f42009-09-09 15:08:12 +00001845
John McCallbc83b3f2010-05-20 23:23:51 +00001846 // Non-virtual bases.
Anders Carlssondb0a9652010-04-02 06:26:44 +00001847 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1848 E = ClassDecl->bases_end(); Base != E; ++Base) {
1849 // Virtuals are in the virtual base list and already constructed.
1850 if (Base->isVirtual())
1851 continue;
Mike Stump11289f42009-09-09 15:08:12 +00001852
Anders Carlssondb0a9652010-04-02 06:26:44 +00001853 if (CXXBaseOrMemberInitializer *Value
John McCallbc83b3f2010-05-20 23:23:51 +00001854 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
1855 Info.AllToInit.push_back(Value);
Anders Carlssondb0a9652010-04-02 06:26:44 +00001856 } else if (!AnyErrors) {
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001857 CXXBaseOrMemberInitializer *CXXBaseInit;
John McCallbc83b3f2010-05-20 23:23:51 +00001858 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
Anders Carlsson1b00e242010-04-23 03:10:23 +00001859 Base, /*IsInheritedVirtualBase=*/false,
Anders Carlsson6bd91c32010-04-23 02:00:02 +00001860 CXXBaseInit)) {
Anders Carlssondb0a9652010-04-02 06:26:44 +00001861 HadError = true;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001862 continue;
Anders Carlssondb0a9652010-04-02 06:26:44 +00001863 }
Fariborz Jahanian59a1cd42009-09-03 21:32:41 +00001864
John McCallbc83b3f2010-05-20 23:23:51 +00001865 Info.AllToInit.push_back(CXXBaseInit);
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001866 }
1867 }
Mike Stump11289f42009-09-09 15:08:12 +00001868
John McCallbc83b3f2010-05-20 23:23:51 +00001869 // Fields.
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001870 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001871 E = ClassDecl->field_end(); Field != E; ++Field) {
1872 if ((*Field)->getType()->isIncompleteArrayType()) {
1873 assert(ClassDecl->hasFlexibleArrayMember() &&
1874 "Incomplete array type is not valid");
1875 continue;
1876 }
John McCallbc83b3f2010-05-20 23:23:51 +00001877 if (CollectFieldInitializer(Info, *Field, *Field))
Anders Carlsson3c1db572010-04-23 02:15:47 +00001878 HadError = true;
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00001879 }
Mike Stump11289f42009-09-09 15:08:12 +00001880
John McCallbc83b3f2010-05-20 23:23:51 +00001881 NumInitializers = Info.AllToInit.size();
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001882 if (NumInitializers > 0) {
1883 Constructor->setNumBaseOrMemberInitializers(NumInitializers);
1884 CXXBaseOrMemberInitializer **baseOrMemberInitializers =
1885 new (Context) CXXBaseOrMemberInitializer*[NumInitializers];
John McCallbc83b3f2010-05-20 23:23:51 +00001886 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
John McCalla6309952010-03-16 21:39:52 +00001887 NumInitializers * sizeof(CXXBaseOrMemberInitializer*));
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001888 Constructor->setBaseOrMemberInitializers(baseOrMemberInitializers);
Rafael Espindola13327bb2010-03-13 18:12:56 +00001889
John McCalla6309952010-03-16 21:39:52 +00001890 // Constructors implicitly reference the base and member
1891 // destructors.
1892 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
1893 Constructor->getParent());
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001894 }
Eli Friedman9cf6b592009-11-09 19:20:36 +00001895
1896 return HadError;
Fariborz Jahanian3501bce2009-09-03 19:36:46 +00001897}
1898
Eli Friedman952c15d2009-07-21 19:28:10 +00001899static void *GetKeyForTopLevelField(FieldDecl *Field) {
1900 // For anonymous unions, use the class declaration as the key.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001901 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman952c15d2009-07-21 19:28:10 +00001902 if (RT->getDecl()->isAnonymousStructOrUnion())
1903 return static_cast<void *>(RT->getDecl());
1904 }
1905 return static_cast<void *>(Field);
1906}
1907
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001908static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
1909 return Context.getCanonicalType(BaseType).getTypePtr();
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001910}
1911
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001912static void *GetKeyForMember(ASTContext &Context,
1913 CXXBaseOrMemberInitializer *Member,
Anders Carlssonbcec05c2009-09-01 06:22:14 +00001914 bool MemberMaybeAnon = false) {
Anders Carlssona942dcd2010-03-30 15:39:27 +00001915 if (!Member->isMemberInitializer())
Anders Carlsson7b3f2782010-04-02 05:42:15 +00001916 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
Anders Carlssona942dcd2010-03-30 15:39:27 +00001917
Eli Friedman952c15d2009-07-21 19:28:10 +00001918 // For fields injected into the class via declaration of an anonymous union,
1919 // use its anonymous union class declaration as the unique key.
Anders Carlssona942dcd2010-03-30 15:39:27 +00001920 FieldDecl *Field = Member->getMember();
Mike Stump11289f42009-09-09 15:08:12 +00001921
Anders Carlssona942dcd2010-03-30 15:39:27 +00001922 // After SetBaseOrMemberInitializers call, Field is the anonymous union
1923 // data member of the class. Data member used in the initializer list is
1924 // in AnonUnionMember field.
1925 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
1926 Field = Member->getAnonUnionMember();
Anders Carlsson83ac3122010-03-30 16:19:37 +00001927
John McCall23eebd92010-04-10 09:28:51 +00001928 // If the field is a member of an anonymous struct or union, our key
1929 // is the anonymous record decl that's a direct child of the class.
Anders Carlsson83ac3122010-03-30 16:19:37 +00001930 RecordDecl *RD = Field->getParent();
John McCall23eebd92010-04-10 09:28:51 +00001931 if (RD->isAnonymousStructOrUnion()) {
1932 while (true) {
1933 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
1934 if (Parent->isAnonymousStructOrUnion())
1935 RD = Parent;
1936 else
1937 break;
1938 }
1939
Anders Carlsson83ac3122010-03-30 16:19:37 +00001940 return static_cast<void *>(RD);
John McCall23eebd92010-04-10 09:28:51 +00001941 }
Mike Stump11289f42009-09-09 15:08:12 +00001942
Anders Carlssona942dcd2010-03-30 15:39:27 +00001943 return static_cast<void *>(Field);
Eli Friedman952c15d2009-07-21 19:28:10 +00001944}
1945
Anders Carlssone857b292010-04-02 03:37:03 +00001946static void
1947DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001948 const CXXConstructorDecl *Constructor,
John McCallbb7b6582010-04-10 07:37:23 +00001949 CXXBaseOrMemberInitializer **Inits,
1950 unsigned NumInits) {
1951 if (Constructor->getDeclContext()->isDependentContext())
Anders Carlsson35d6e3e2009-08-27 05:57:30 +00001952 return;
Mike Stump11289f42009-09-09 15:08:12 +00001953
John McCallbb7b6582010-04-10 07:37:23 +00001954 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order)
1955 == Diagnostic::Ignored)
Anders Carlssone0eebb32009-08-27 05:45:01 +00001956 return;
Anders Carlssone857b292010-04-02 03:37:03 +00001957
John McCallbb7b6582010-04-10 07:37:23 +00001958 // Build the list of bases and members in the order that they'll
1959 // actually be initialized. The explicit initializers should be in
1960 // this same order but may be missing things.
1961 llvm::SmallVector<const void*, 32> IdealInitKeys;
Mike Stump11289f42009-09-09 15:08:12 +00001962
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001963 const CXXRecordDecl *ClassDecl = Constructor->getParent();
1964
John McCallbb7b6582010-04-10 07:37:23 +00001965 // 1. Virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001966 for (CXXRecordDecl::base_class_const_iterator VBase =
Anders Carlssone0eebb32009-08-27 05:45:01 +00001967 ClassDecl->vbases_begin(),
1968 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
John McCallbb7b6582010-04-10 07:37:23 +00001969 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
Mike Stump11289f42009-09-09 15:08:12 +00001970
John McCallbb7b6582010-04-10 07:37:23 +00001971 // 2. Non-virtual bases.
Anders Carlsson96b8fc62010-04-02 03:38:04 +00001972 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
Anders Carlssone0eebb32009-08-27 05:45:01 +00001973 E = ClassDecl->bases_end(); Base != E; ++Base) {
Anders Carlssone0eebb32009-08-27 05:45:01 +00001974 if (Base->isVirtual())
1975 continue;
John McCallbb7b6582010-04-10 07:37:23 +00001976 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
Anders Carlssone0eebb32009-08-27 05:45:01 +00001977 }
Mike Stump11289f42009-09-09 15:08:12 +00001978
John McCallbb7b6582010-04-10 07:37:23 +00001979 // 3. Direct fields.
Anders Carlssone0eebb32009-08-27 05:45:01 +00001980 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1981 E = ClassDecl->field_end(); Field != E; ++Field)
John McCallbb7b6582010-04-10 07:37:23 +00001982 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
Mike Stump11289f42009-09-09 15:08:12 +00001983
John McCallbb7b6582010-04-10 07:37:23 +00001984 unsigned NumIdealInits = IdealInitKeys.size();
1985 unsigned IdealIndex = 0;
Eli Friedman952c15d2009-07-21 19:28:10 +00001986
John McCallbb7b6582010-04-10 07:37:23 +00001987 CXXBaseOrMemberInitializer *PrevInit = 0;
1988 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
1989 CXXBaseOrMemberInitializer *Init = Inits[InitIndex];
1990 void *InitKey = GetKeyForMember(SemaRef.Context, Init, true);
1991
1992 // Scan forward to try to find this initializer in the idealized
1993 // initializers list.
1994 for (; IdealIndex != NumIdealInits; ++IdealIndex)
1995 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00001996 break;
John McCallbb7b6582010-04-10 07:37:23 +00001997
1998 // If we didn't find this initializer, it must be because we
1999 // scanned past it on a previous iteration. That can only
2000 // happen if we're out of order; emit a warning.
Douglas Gregoraabdfcb2010-05-20 23:49:34 +00002001 if (IdealIndex == NumIdealInits && PrevInit) {
John McCallbb7b6582010-04-10 07:37:23 +00002002 Sema::SemaDiagnosticBuilder D =
2003 SemaRef.Diag(PrevInit->getSourceLocation(),
2004 diag::warn_initializer_out_of_order);
2005
2006 if (PrevInit->isMemberInitializer())
2007 D << 0 << PrevInit->getMember()->getDeclName();
2008 else
2009 D << 1 << PrevInit->getBaseClassInfo()->getType();
2010
2011 if (Init->isMemberInitializer())
2012 D << 0 << Init->getMember()->getDeclName();
2013 else
2014 D << 1 << Init->getBaseClassInfo()->getType();
2015
2016 // Move back to the initializer's location in the ideal list.
2017 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2018 if (InitKey == IdealInitKeys[IdealIndex])
Anders Carlssone0eebb32009-08-27 05:45:01 +00002019 break;
John McCallbb7b6582010-04-10 07:37:23 +00002020
2021 assert(IdealIndex != NumIdealInits &&
2022 "initializer not found in initializer list");
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002023 }
John McCallbb7b6582010-04-10 07:37:23 +00002024
2025 PrevInit = Init;
Fariborz Jahanian341583c2009-07-09 19:59:47 +00002026 }
Anders Carlsson75fdaa42009-03-25 02:58:17 +00002027}
2028
John McCall23eebd92010-04-10 09:28:51 +00002029namespace {
2030bool CheckRedundantInit(Sema &S,
2031 CXXBaseOrMemberInitializer *Init,
2032 CXXBaseOrMemberInitializer *&PrevInit) {
2033 if (!PrevInit) {
2034 PrevInit = Init;
2035 return false;
2036 }
2037
2038 if (FieldDecl *Field = Init->getMember())
2039 S.Diag(Init->getSourceLocation(),
2040 diag::err_multiple_mem_initialization)
2041 << Field->getDeclName()
2042 << Init->getSourceRange();
2043 else {
2044 Type *BaseClass = Init->getBaseClass();
2045 assert(BaseClass && "neither field nor base");
2046 S.Diag(Init->getSourceLocation(),
2047 diag::err_multiple_base_initialization)
2048 << QualType(BaseClass, 0)
2049 << Init->getSourceRange();
2050 }
2051 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2052 << 0 << PrevInit->getSourceRange();
2053
2054 return true;
2055}
2056
2057typedef std::pair<NamedDecl *, CXXBaseOrMemberInitializer *> UnionEntry;
2058typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2059
2060bool CheckRedundantUnionInit(Sema &S,
2061 CXXBaseOrMemberInitializer *Init,
2062 RedundantUnionMap &Unions) {
2063 FieldDecl *Field = Init->getMember();
2064 RecordDecl *Parent = Field->getParent();
2065 if (!Parent->isAnonymousStructOrUnion())
2066 return false;
2067
2068 NamedDecl *Child = Field;
2069 do {
2070 if (Parent->isUnion()) {
2071 UnionEntry &En = Unions[Parent];
2072 if (En.first && En.first != Child) {
2073 S.Diag(Init->getSourceLocation(),
2074 diag::err_multiple_mem_union_initialization)
2075 << Field->getDeclName()
2076 << Init->getSourceRange();
2077 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2078 << 0 << En.second->getSourceRange();
2079 return true;
2080 } else if (!En.first) {
2081 En.first = Child;
2082 En.second = Init;
2083 }
2084 }
2085
2086 Child = Parent;
2087 Parent = cast<RecordDecl>(Parent->getDeclContext());
2088 } while (Parent->isAnonymousStructOrUnion());
2089
2090 return false;
2091}
2092}
2093
Anders Carlssone857b292010-04-02 03:37:03 +00002094/// ActOnMemInitializers - Handle the member initializers for a constructor.
John McCall48871652010-08-21 09:40:31 +00002095void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
Anders Carlssone857b292010-04-02 03:37:03 +00002096 SourceLocation ColonLoc,
2097 MemInitTy **meminits, unsigned NumMemInits,
2098 bool AnyErrors) {
2099 if (!ConstructorDecl)
2100 return;
2101
2102 AdjustDeclIfTemplate(ConstructorDecl);
2103
2104 CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002105 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
Anders Carlssone857b292010-04-02 03:37:03 +00002106
2107 if (!Constructor) {
2108 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2109 return;
2110 }
2111
2112 CXXBaseOrMemberInitializer **MemInits =
2113 reinterpret_cast<CXXBaseOrMemberInitializer **>(meminits);
John McCall23eebd92010-04-10 09:28:51 +00002114
2115 // Mapping for the duplicate initializers check.
2116 // For member initializers, this is keyed with a FieldDecl*.
2117 // For base initializers, this is keyed with a Type*.
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002118 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *> Members;
John McCall23eebd92010-04-10 09:28:51 +00002119
2120 // Mapping for the inconsistent anonymous-union initializers check.
2121 RedundantUnionMap MemberUnions;
2122
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002123 bool HadError = false;
2124 for (unsigned i = 0; i < NumMemInits; i++) {
John McCall23eebd92010-04-10 09:28:51 +00002125 CXXBaseOrMemberInitializer *Init = MemInits[i];
Anders Carlssone857b292010-04-02 03:37:03 +00002126
Abramo Bagnara341d7832010-05-26 18:09:23 +00002127 // Set the source order index.
2128 Init->setSourceOrder(i);
2129
John McCall23eebd92010-04-10 09:28:51 +00002130 if (Init->isMemberInitializer()) {
2131 FieldDecl *Field = Init->getMember();
2132 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2133 CheckRedundantUnionInit(*this, Init, MemberUnions))
2134 HadError = true;
2135 } else {
2136 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2137 if (CheckRedundantInit(*this, Init, Members[Key]))
2138 HadError = true;
Anders Carlssone857b292010-04-02 03:37:03 +00002139 }
Anders Carlssone857b292010-04-02 03:37:03 +00002140 }
2141
Anders Carlsson7b3f2782010-04-02 05:42:15 +00002142 if (HadError)
2143 return;
2144
Anders Carlssone857b292010-04-02 03:37:03 +00002145 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002146
2147 SetBaseOrMemberInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
Anders Carlssone857b292010-04-02 03:37:03 +00002148}
2149
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002150void
John McCalla6309952010-03-16 21:39:52 +00002151Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2152 CXXRecordDecl *ClassDecl) {
2153 // Ignore dependent contexts.
2154 if (ClassDecl->isDependentContext())
Anders Carlssondee9a302009-11-17 04:44:12 +00002155 return;
John McCall1064d7e2010-03-16 05:22:47 +00002156
2157 // FIXME: all the access-control diagnostics are positioned on the
2158 // field/base declaration. That's probably good; that said, the
2159 // user might reasonably want to know why the destructor is being
2160 // emitted, and we currently don't say.
Anders Carlssondee9a302009-11-17 04:44:12 +00002161
Anders Carlssondee9a302009-11-17 04:44:12 +00002162 // Non-static data members.
2163 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2164 E = ClassDecl->field_end(); I != E; ++I) {
2165 FieldDecl *Field = *I;
Fariborz Jahanian16f94c62010-05-17 18:15:18 +00002166 if (Field->isInvalidDecl())
2167 continue;
Anders Carlssondee9a302009-11-17 04:44:12 +00002168 QualType FieldType = Context.getBaseElementType(Field->getType());
2169
2170 const RecordType* RT = FieldType->getAs<RecordType>();
2171 if (!RT)
2172 continue;
2173
2174 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2175 if (FieldClassDecl->hasTrivialDestructor())
2176 continue;
2177
Douglas Gregore71edda2010-07-01 22:47:18 +00002178 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002179 CheckDestructorAccess(Field->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002180 PDiag(diag::err_access_dtor_field)
John McCall1064d7e2010-03-16 05:22:47 +00002181 << Field->getDeclName()
2182 << FieldType);
2183
John McCalla6309952010-03-16 21:39:52 +00002184 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002185 }
2186
John McCall1064d7e2010-03-16 05:22:47 +00002187 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2188
Anders Carlssondee9a302009-11-17 04:44:12 +00002189 // Bases.
2190 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2191 E = ClassDecl->bases_end(); Base != E; ++Base) {
John McCall1064d7e2010-03-16 05:22:47 +00002192 // Bases are always records in a well-formed non-dependent class.
2193 const RecordType *RT = Base->getType()->getAs<RecordType>();
2194
2195 // Remember direct virtual bases.
Anders Carlssondee9a302009-11-17 04:44:12 +00002196 if (Base->isVirtual())
John McCall1064d7e2010-03-16 05:22:47 +00002197 DirectVirtualBases.insert(RT);
Anders Carlssondee9a302009-11-17 04:44:12 +00002198
2199 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002200 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssondee9a302009-11-17 04:44:12 +00002201 if (BaseClassDecl->hasTrivialDestructor())
2202 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002203
Douglas Gregore71edda2010-07-01 22:47:18 +00002204 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002205
2206 // FIXME: caret should be on the start of the class name
2207 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002208 PDiag(diag::err_access_dtor_base)
John McCall1064d7e2010-03-16 05:22:47 +00002209 << Base->getType()
2210 << Base->getSourceRange());
Anders Carlssondee9a302009-11-17 04:44:12 +00002211
John McCalla6309952010-03-16 21:39:52 +00002212 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Anders Carlssondee9a302009-11-17 04:44:12 +00002213 }
2214
2215 // Virtual bases.
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002216 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2217 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
John McCall1064d7e2010-03-16 05:22:47 +00002218
2219 // Bases are always records in a well-formed non-dependent class.
2220 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2221
2222 // Ignore direct virtual bases.
2223 if (DirectVirtualBases.count(RT))
2224 continue;
2225
Anders Carlssondee9a302009-11-17 04:44:12 +00002226 // Ignore trivial destructors.
John McCall1064d7e2010-03-16 05:22:47 +00002227 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002228 if (BaseClassDecl->hasTrivialDestructor())
2229 continue;
John McCall1064d7e2010-03-16 05:22:47 +00002230
Douglas Gregore71edda2010-07-01 22:47:18 +00002231 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
John McCall1064d7e2010-03-16 05:22:47 +00002232 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
Douglas Gregor89336232010-03-29 23:34:08 +00002233 PDiag(diag::err_access_dtor_vbase)
John McCall1064d7e2010-03-16 05:22:47 +00002234 << VBase->getType());
2235
John McCalla6309952010-03-16 21:39:52 +00002236 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002237 }
2238}
2239
John McCall48871652010-08-21 09:40:31 +00002240void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
Fariborz Jahanian16094c22009-07-15 22:34:08 +00002241 if (!CDtorDecl)
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002242 return;
Mike Stump11289f42009-09-09 15:08:12 +00002243
Mike Stump11289f42009-09-09 15:08:12 +00002244 if (CXXConstructorDecl *Constructor
John McCall48871652010-08-21 09:40:31 +00002245 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
Anders Carlsson4c8cb012010-04-02 03:43:34 +00002246 SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
Fariborz Jahanian49c81792009-07-14 18:24:21 +00002247}
2248
Mike Stump11289f42009-09-09 15:08:12 +00002249bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002250 unsigned DiagID, AbstractDiagSelID SelID) {
Anders Carlssoneabf7702009-08-27 00:13:57 +00002251 if (SelID == -1)
John McCall02db245d2010-08-18 09:41:07 +00002252 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
Anders Carlssoneabf7702009-08-27 00:13:57 +00002253 else
John McCall02db245d2010-08-18 09:41:07 +00002254 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
Mike Stump11289f42009-09-09 15:08:12 +00002255}
2256
Anders Carlssoneabf7702009-08-27 00:13:57 +00002257bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
John McCall02db245d2010-08-18 09:41:07 +00002258 const PartialDiagnostic &PD) {
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002259 if (!getLangOptions().CPlusPlus)
2260 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002261
Anders Carlssoneb0c5322009-03-23 19:10:31 +00002262 if (const ArrayType *AT = Context.getAsArrayType(T))
John McCall02db245d2010-08-18 09:41:07 +00002263 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Mike Stump11289f42009-09-09 15:08:12 +00002264
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002265 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002266 // Find the innermost pointer type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002267 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002268 PT = T;
Mike Stump11289f42009-09-09 15:08:12 +00002269
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002270 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
John McCall02db245d2010-08-18 09:41:07 +00002271 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
Anders Carlsson8f0d2182009-03-24 01:46:45 +00002272 }
Mike Stump11289f42009-09-09 15:08:12 +00002273
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002274 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002275 if (!RT)
2276 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002277
John McCall67da35c2010-02-04 22:26:26 +00002278 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002279
John McCall02db245d2010-08-18 09:41:07 +00002280 // We can't answer whether something is abstract until it has a
2281 // definition. If it's currently being defined, we'll walk back
2282 // over all the declarations when we have a full definition.
2283 const CXXRecordDecl *Def = RD->getDefinition();
2284 if (!Def || Def->isBeingDefined())
John McCall67da35c2010-02-04 22:26:26 +00002285 return false;
2286
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002287 if (!RD->isAbstract())
2288 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002289
Anders Carlssoneabf7702009-08-27 00:13:57 +00002290 Diag(Loc, PD) << RD->getDeclName();
John McCall02db245d2010-08-18 09:41:07 +00002291 DiagnoseAbstractType(RD);
Mike Stump11289f42009-09-09 15:08:12 +00002292
John McCall02db245d2010-08-18 09:41:07 +00002293 return true;
2294}
2295
2296void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2297 // Check if we've already emitted the list of pure virtual functions
2298 // for this class.
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002299 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
John McCall02db245d2010-08-18 09:41:07 +00002300 return;
Mike Stump11289f42009-09-09 15:08:12 +00002301
Douglas Gregor4165bd62010-03-23 23:47:56 +00002302 CXXFinalOverriderMap FinalOverriders;
2303 RD->getFinalOverriders(FinalOverriders);
Mike Stump11289f42009-09-09 15:08:12 +00002304
Anders Carlssona2f74f32010-06-03 01:00:02 +00002305 // Keep a set of seen pure methods so we won't diagnose the same method
2306 // more than once.
2307 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2308
Douglas Gregor4165bd62010-03-23 23:47:56 +00002309 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2310 MEnd = FinalOverriders.end();
2311 M != MEnd;
2312 ++M) {
2313 for (OverridingMethods::iterator SO = M->second.begin(),
2314 SOEnd = M->second.end();
2315 SO != SOEnd; ++SO) {
2316 // C++ [class.abstract]p4:
2317 // A class is abstract if it contains or inherits at least one
2318 // pure virtual function for which the final overrider is pure
2319 // virtual.
Mike Stump11289f42009-09-09 15:08:12 +00002320
Douglas Gregor4165bd62010-03-23 23:47:56 +00002321 //
2322 if (SO->second.size() != 1)
2323 continue;
2324
2325 if (!SO->second.front().Method->isPure())
2326 continue;
2327
Anders Carlssona2f74f32010-06-03 01:00:02 +00002328 if (!SeenPureMethods.insert(SO->second.front().Method))
2329 continue;
2330
Douglas Gregor4165bd62010-03-23 23:47:56 +00002331 Diag(SO->second.front().Method->getLocation(),
2332 diag::note_pure_virtual_function)
2333 << SO->second.front().Method->getDeclName();
2334 }
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002335 }
2336
2337 if (!PureVirtualClassDiagSet)
2338 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2339 PureVirtualClassDiagSet->insert(RD);
Anders Carlsson576cc6f2009-03-22 20:18:17 +00002340}
2341
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002342namespace {
John McCall02db245d2010-08-18 09:41:07 +00002343struct AbstractUsageInfo {
2344 Sema &S;
2345 CXXRecordDecl *Record;
2346 CanQualType AbstractType;
2347 bool Invalid;
Mike Stump11289f42009-09-09 15:08:12 +00002348
John McCall02db245d2010-08-18 09:41:07 +00002349 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2350 : S(S), Record(Record),
2351 AbstractType(S.Context.getCanonicalType(
2352 S.Context.getTypeDeclType(Record))),
2353 Invalid(false) {}
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002354
John McCall02db245d2010-08-18 09:41:07 +00002355 void DiagnoseAbstractType() {
2356 if (Invalid) return;
2357 S.DiagnoseAbstractType(Record);
2358 Invalid = true;
2359 }
Anders Carlssonb57738b2009-03-24 17:23:42 +00002360
John McCall02db245d2010-08-18 09:41:07 +00002361 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2362};
2363
2364struct CheckAbstractUsage {
2365 AbstractUsageInfo &Info;
2366 const NamedDecl *Ctx;
2367
2368 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2369 : Info(Info), Ctx(Ctx) {}
2370
2371 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2372 switch (TL.getTypeLocClass()) {
2373#define ABSTRACT_TYPELOC(CLASS, PARENT)
2374#define TYPELOC(CLASS, PARENT) \
2375 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2376#include "clang/AST/TypeLocNodes.def"
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002377 }
John McCall02db245d2010-08-18 09:41:07 +00002378 }
Mike Stump11289f42009-09-09 15:08:12 +00002379
John McCall02db245d2010-08-18 09:41:07 +00002380 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2381 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2382 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2383 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2384 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002385 }
John McCall02db245d2010-08-18 09:41:07 +00002386 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002387
John McCall02db245d2010-08-18 09:41:07 +00002388 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2389 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2390 }
Mike Stump11289f42009-09-09 15:08:12 +00002391
John McCall02db245d2010-08-18 09:41:07 +00002392 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2393 // Visit the type parameters from a permissive context.
2394 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2395 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2396 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2397 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2398 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2399 // TODO: other template argument types?
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002400 }
John McCall02db245d2010-08-18 09:41:07 +00002401 }
Mike Stump11289f42009-09-09 15:08:12 +00002402
John McCall02db245d2010-08-18 09:41:07 +00002403 // Visit pointee types from a permissive context.
2404#define CheckPolymorphic(Type) \
2405 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2406 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2407 }
2408 CheckPolymorphic(PointerTypeLoc)
2409 CheckPolymorphic(ReferenceTypeLoc)
2410 CheckPolymorphic(MemberPointerTypeLoc)
2411 CheckPolymorphic(BlockPointerTypeLoc)
Mike Stump11289f42009-09-09 15:08:12 +00002412
John McCall02db245d2010-08-18 09:41:07 +00002413 /// Handle all the types we haven't given a more specific
2414 /// implementation for above.
2415 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2416 // Every other kind of type that we haven't called out already
2417 // that has an inner type is either (1) sugar or (2) contains that
2418 // inner type in some way as a subobject.
2419 if (TypeLoc Next = TL.getNextTypeLoc())
2420 return Visit(Next, Sel);
2421
2422 // If there's no inner type and we're in a permissive context,
2423 // don't diagnose.
2424 if (Sel == Sema::AbstractNone) return;
2425
2426 // Check whether the type matches the abstract type.
2427 QualType T = TL.getType();
2428 if (T->isArrayType()) {
2429 Sel = Sema::AbstractArrayType;
2430 T = Info.S.Context.getBaseElementType(T);
Anders Carlssonb57738b2009-03-24 17:23:42 +00002431 }
John McCall02db245d2010-08-18 09:41:07 +00002432 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2433 if (CT != Info.AbstractType) return;
2434
2435 // It matched; do some magic.
2436 if (Sel == Sema::AbstractArrayType) {
2437 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2438 << T << TL.getSourceRange();
2439 } else {
2440 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2441 << Sel << T << TL.getSourceRange();
2442 }
2443 Info.DiagnoseAbstractType();
2444 }
2445};
2446
2447void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2448 Sema::AbstractDiagSelID Sel) {
2449 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2450}
2451
2452}
2453
2454/// Check for invalid uses of an abstract type in a method declaration.
2455static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2456 CXXMethodDecl *MD) {
2457 // No need to do the check on definitions, which require that
2458 // the return/param types be complete.
2459 if (MD->isThisDeclarationADefinition())
2460 return;
2461
2462 // For safety's sake, just ignore it if we don't have type source
2463 // information. This should never happen for non-implicit methods,
2464 // but...
2465 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2466 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2467}
2468
2469/// Check for invalid uses of an abstract type within a class definition.
2470static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2471 CXXRecordDecl *RD) {
2472 for (CXXRecordDecl::decl_iterator
2473 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2474 Decl *D = *I;
2475 if (D->isImplicit()) continue;
2476
2477 // Methods and method templates.
2478 if (isa<CXXMethodDecl>(D)) {
2479 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2480 } else if (isa<FunctionTemplateDecl>(D)) {
2481 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2482 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2483
2484 // Fields and static variables.
2485 } else if (isa<FieldDecl>(D)) {
2486 FieldDecl *FD = cast<FieldDecl>(D);
2487 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
2488 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
2489 } else if (isa<VarDecl>(D)) {
2490 VarDecl *VD = cast<VarDecl>(D);
2491 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
2492 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
2493
2494 // Nested classes and class templates.
2495 } else if (isa<CXXRecordDecl>(D)) {
2496 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
2497 } else if (isa<ClassTemplateDecl>(D)) {
2498 CheckAbstractClassUsage(Info,
2499 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
2500 }
2501 }
Anders Carlssonb5a27b42009-03-24 01:19:16 +00002502}
2503
Douglas Gregorc99f1552009-12-03 18:33:45 +00002504/// \brief Perform semantic checks on a class definition that has been
2505/// completing, introducing implicitly-declared members, checking for
2506/// abstract types, etc.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002507void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
Douglas Gregor8fb95122010-09-29 00:15:42 +00002508 if (!Record)
Douglas Gregorc99f1552009-12-03 18:33:45 +00002509 return;
2510
John McCall02db245d2010-08-18 09:41:07 +00002511 if (Record->isAbstract() && !Record->isInvalidDecl()) {
2512 AbstractUsageInfo Info(*this, Record);
2513 CheckAbstractClassUsage(Info, Record);
2514 }
Douglas Gregor454a5b62010-04-15 00:00:53 +00002515
2516 // If this is not an aggregate type and has no user-declared constructor,
2517 // complain about any non-static data members of reference or const scalar
2518 // type, since they will never get initializers.
2519 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
2520 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
2521 bool Complained = false;
2522 for (RecordDecl::field_iterator F = Record->field_begin(),
2523 FEnd = Record->field_end();
2524 F != FEnd; ++F) {
2525 if (F->getType()->isReferenceType() ||
Benjamin Kramer659d7fc2010-04-16 17:43:15 +00002526 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
Douglas Gregor454a5b62010-04-15 00:00:53 +00002527 if (!Complained) {
2528 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
2529 << Record->getTagKind() << Record;
2530 Complained = true;
2531 }
2532
2533 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
2534 << F->getType()->isReferenceType()
2535 << F->getDeclName();
2536 }
2537 }
2538 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00002539
2540 if (Record->isDynamicClass())
2541 DynamicClasses.push_back(Record);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002542}
2543
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002544void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
John McCall48871652010-08-21 09:40:31 +00002545 Decl *TagDecl,
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002546 SourceLocation LBrac,
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002547 SourceLocation RBrac,
2548 AttributeList *AttrList) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002549 if (!TagDecl)
2550 return;
Mike Stump11289f42009-09-09 15:08:12 +00002551
Douglas Gregorc9f9b862009-05-11 19:58:34 +00002552 AdjustDeclIfTemplate(TagDecl);
Douglas Gregorc99f1552009-12-03 18:33:45 +00002553
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002554 ActOnFields(S, RLoc, TagDecl,
John McCall48871652010-08-21 09:40:31 +00002555 // strict aliasing violation!
2556 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
Douglas Gregorc48a10d2010-03-29 14:42:08 +00002557 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
Douglas Gregor463421d2009-03-03 04:44:36 +00002558
Douglas Gregor0be31a22010-07-02 17:43:08 +00002559 CheckCompletedCXXClass(
John McCall48871652010-08-21 09:40:31 +00002560 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002561}
2562
Douglas Gregor95755162010-07-01 05:10:53 +00002563namespace {
2564 /// \brief Helper class that collects exception specifications for
2565 /// implicitly-declared special member functions.
2566 class ImplicitExceptionSpecification {
2567 ASTContext &Context;
2568 bool AllowsAllExceptions;
2569 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
2570 llvm::SmallVector<QualType, 4> Exceptions;
2571
2572 public:
2573 explicit ImplicitExceptionSpecification(ASTContext &Context)
2574 : Context(Context), AllowsAllExceptions(false) { }
2575
2576 /// \brief Whether the special member function should have any
2577 /// exception specification at all.
2578 bool hasExceptionSpecification() const {
2579 return !AllowsAllExceptions;
2580 }
2581
2582 /// \brief Whether the special member function should have a
2583 /// throw(...) exception specification (a Microsoft extension).
2584 bool hasAnyExceptionSpecification() const {
2585 return false;
2586 }
2587
2588 /// \brief The number of exceptions in the exception specification.
2589 unsigned size() const { return Exceptions.size(); }
2590
2591 /// \brief The set of exceptions in the exception specification.
2592 const QualType *data() const { return Exceptions.data(); }
2593
2594 /// \brief Note that
2595 void CalledDecl(CXXMethodDecl *Method) {
2596 // If we already know that we allow all exceptions, do nothing.
Douglas Gregor3311ed42010-07-01 15:29:53 +00002597 if (AllowsAllExceptions || !Method)
Douglas Gregor95755162010-07-01 05:10:53 +00002598 return;
2599
2600 const FunctionProtoType *Proto
2601 = Method->getType()->getAs<FunctionProtoType>();
2602
2603 // If this function can throw any exceptions, make a note of that.
2604 if (!Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec()) {
2605 AllowsAllExceptions = true;
2606 ExceptionsSeen.clear();
2607 Exceptions.clear();
2608 return;
2609 }
2610
2611 // Record the exceptions in this function's exception specification.
2612 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
2613 EEnd = Proto->exception_end();
2614 E != EEnd; ++E)
2615 if (ExceptionsSeen.insert(Context.getCanonicalType(*E)))
2616 Exceptions.push_back(*E);
2617 }
2618 };
2619}
2620
2621
Douglas Gregor05379422008-11-03 17:51:48 +00002622/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2623/// special functions, such as the default constructor, copy
2624/// constructor, or destructor, to the given C++ class (C++
2625/// [special]p1). This routine can only be executed just before the
2626/// definition of the class is complete.
Douglas Gregor0be31a22010-07-02 17:43:08 +00002627void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00002628 if (!ClassDecl->hasUserDeclaredConstructor())
Douglas Gregor9672f922010-07-03 00:47:00 +00002629 ++ASTContext::NumImplicitDefaultConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002630
Douglas Gregor54be3392010-07-01 17:57:27 +00002631 if (!ClassDecl->hasUserDeclaredCopyConstructor())
Douglas Gregora6d69502010-07-02 23:41:54 +00002632 ++ASTContext::NumImplicitCopyConstructors;
Douglas Gregor05379422008-11-03 17:51:48 +00002633
Douglas Gregor330b9cf2010-07-02 21:50:04 +00002634 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
2635 ++ASTContext::NumImplicitCopyAssignmentOperators;
2636
2637 // If we have a dynamic class, then the copy assignment operator may be
2638 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2639 // it shows up in the right place in the vtable and that we diagnose
2640 // problems with the implicit exception specification.
2641 if (ClassDecl->isDynamicClass())
2642 DeclareImplicitCopyAssignment(ClassDecl);
2643 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00002644
Douglas Gregor7454c562010-07-02 20:37:36 +00002645 if (!ClassDecl->hasUserDeclaredDestructor()) {
2646 ++ASTContext::NumImplicitDestructors;
2647
2648 // If we have a dynamic class, then the destructor may be virtual, so we
2649 // have to declare the destructor immediately. This ensures that, e.g., it
2650 // shows up in the right place in the vtable and that we diagnose problems
2651 // with the implicit exception specification.
2652 if (ClassDecl->isDynamicClass())
2653 DeclareImplicitDestructor(ClassDecl);
2654 }
Douglas Gregor05379422008-11-03 17:51:48 +00002655}
2656
John McCall48871652010-08-21 09:40:31 +00002657void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
Douglas Gregore61ef622009-09-10 00:12:48 +00002658 if (!D)
2659 return;
2660
2661 TemplateParameterList *Params = 0;
2662 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
2663 Params = Template->getTemplateParameters();
2664 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2665 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
2666 Params = PartialSpec->getTemplateParameters();
2667 else
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002668 return;
2669
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002670 for (TemplateParameterList::iterator Param = Params->begin(),
2671 ParamEnd = Params->end();
2672 Param != ParamEnd; ++Param) {
2673 NamedDecl *Named = cast<NamedDecl>(*Param);
2674 if (Named->getDeclName()) {
John McCall48871652010-08-21 09:40:31 +00002675 S->AddDecl(Named);
Douglas Gregore44a2ad2009-05-27 23:11:45 +00002676 IdResolver.AddDecl(Named);
2677 }
2678 }
2679}
2680
John McCall48871652010-08-21 09:40:31 +00002681void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002682 if (!RecordD) return;
2683 AdjustDeclIfTemplate(RecordD);
John McCall48871652010-08-21 09:40:31 +00002684 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
John McCall6df5fef2009-12-19 10:49:29 +00002685 PushDeclContext(S, Record);
2686}
2687
John McCall48871652010-08-21 09:40:31 +00002688void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
John McCall6df5fef2009-12-19 10:49:29 +00002689 if (!RecordD) return;
2690 PopDeclContext();
2691}
2692
Douglas Gregor4d87df52008-12-16 21:30:33 +00002693/// ActOnStartDelayedCXXMethodDeclaration - We have completed
2694/// parsing a top-level (non-nested) C++ class, and we are now
2695/// parsing those parts of the given Method declaration that could
2696/// not be parsed earlier (C++ [class.mem]p2), such as default
2697/// arguments. This action should enter the scope of the given
2698/// Method declaration as if we had just parsed the qualified method
2699/// name. However, it should not bring the parameters into scope;
2700/// that will be performed by ActOnDelayedCXXMethodParameter.
John McCall48871652010-08-21 09:40:31 +00002701void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002702}
2703
2704/// ActOnDelayedCXXMethodParameter - We've already started a delayed
2705/// C++ method declaration. We're (re-)introducing the given
2706/// function parameter into scope for use in parsing later parts of
2707/// the method declaration. For example, we could see an
2708/// ActOnParamDefaultArgument event for this parameter.
John McCall48871652010-08-21 09:40:31 +00002709void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002710 if (!ParamD)
2711 return;
Mike Stump11289f42009-09-09 15:08:12 +00002712
John McCall48871652010-08-21 09:40:31 +00002713 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
Douglas Gregor58354032008-12-24 00:01:03 +00002714
2715 // If this parameter has an unparsed default argument, clear it out
2716 // to make way for the parsed default argument.
2717 if (Param->hasUnparsedDefaultArg())
2718 Param->setDefaultArg(0);
2719
John McCall48871652010-08-21 09:40:31 +00002720 S->AddDecl(Param);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002721 if (Param->getDeclName())
2722 IdResolver.AddDecl(Param);
2723}
2724
2725/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2726/// processing the delayed method declaration for Method. The method
2727/// declaration is now considered finished. There may be a separate
2728/// ActOnStartOfFunctionDef action later (not necessarily
2729/// immediately!) for this method, if it was also defined inside the
2730/// class body.
John McCall48871652010-08-21 09:40:31 +00002731void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
Douglas Gregor71a57182009-06-22 23:20:33 +00002732 if (!MethodD)
2733 return;
Mike Stump11289f42009-09-09 15:08:12 +00002734
Douglas Gregorc8c277a2009-08-24 11:57:43 +00002735 AdjustDeclIfTemplate(MethodD);
Mike Stump11289f42009-09-09 15:08:12 +00002736
John McCall48871652010-08-21 09:40:31 +00002737 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002738
2739 // Now that we have our default arguments, check the constructor
2740 // again. It could produce additional diagnostics or affect whether
2741 // the class has implicitly-declared destructors, among other
2742 // things.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002743 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
2744 CheckConstructor(Constructor);
Douglas Gregor4d87df52008-12-16 21:30:33 +00002745
2746 // Check the default arguments, which we may have added.
2747 if (!Method->isInvalidDecl())
2748 CheckCXXDefaultArguments(Method);
2749}
2750
Douglas Gregor831c93f2008-11-05 20:51:48 +00002751/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor4d87df52008-12-16 21:30:33 +00002752/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor831c93f2008-11-05 20:51:48 +00002753/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002754/// emit diagnostics and set the invalid bit to true. In any case, the type
2755/// will be updated to reflect a well-formed type for the constructor and
2756/// returned.
2757QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002758 StorageClass &SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002759 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002760
2761 // C++ [class.ctor]p3:
2762 // A constructor shall not be virtual (10.3) or static (9.4). A
2763 // constructor can be invoked for a const, volatile or const
2764 // volatile object. A constructor shall not be declared const,
2765 // volatile, or const volatile (9.3.2).
2766 if (isVirtual) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002767 if (!D.isInvalidType())
2768 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2769 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
2770 << SourceRange(D.getIdentifierLoc());
2771 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002772 }
John McCall8e7d6562010-08-26 03:08:43 +00002773 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002774 if (!D.isInvalidType())
2775 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
2776 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2777 << SourceRange(D.getIdentifierLoc());
2778 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002779 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002780 }
Mike Stump11289f42009-09-09 15:08:12 +00002781
Chris Lattner38378bf2009-04-25 08:28:21 +00002782 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2783 if (FTI.TypeQuals != 0) {
John McCall8ccfcb52009-09-24 19:53:00 +00002784 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002785 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2786 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002787 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002788 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2789 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002790 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002791 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
2792 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002793 }
Mike Stump11289f42009-09-09 15:08:12 +00002794
Douglas Gregor831c93f2008-11-05 20:51:48 +00002795 // Rebuild the function type "R" without any type qualifiers (in
2796 // case any of the errors above fired) and with "void" as the
Douglas Gregor95755162010-07-01 05:10:53 +00002797 // return type, since constructors don't have return types.
John McCall9dd450b2009-09-21 23:43:11 +00002798 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
Chris Lattner38378bf2009-04-25 08:28:21 +00002799 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
2800 Proto->getNumArgs(),
Douglas Gregor36c569f2010-02-21 22:15:06 +00002801 Proto->isVariadic(), 0,
2802 Proto->hasExceptionSpec(),
2803 Proto->hasAnyExceptionSpec(),
2804 Proto->getNumExceptions(),
2805 Proto->exception_begin(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00002806 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002807}
2808
Douglas Gregor4d87df52008-12-16 21:30:33 +00002809/// CheckConstructor - Checks a fully-formed constructor for
2810/// well-formedness, issuing any diagnostics required. Returns true if
2811/// the constructor declarator is invalid.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002812void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Mike Stump11289f42009-09-09 15:08:12 +00002813 CXXRecordDecl *ClassDecl
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002814 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
2815 if (!ClassDecl)
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002816 return Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002817
2818 // C++ [class.copy]p3:
2819 // A declaration of a constructor for a class X is ill-formed if
2820 // its first parameter is of type (optionally cv-qualified) X and
2821 // either there are no other parameters or else all other
2822 // parameters have default arguments.
Douglas Gregorf4d17c42009-03-27 04:38:56 +00002823 if (!Constructor->isInvalidDecl() &&
Mike Stump11289f42009-09-09 15:08:12 +00002824 ((Constructor->getNumParams() == 1) ||
2825 (Constructor->getNumParams() > 1 &&
Douglas Gregorffe14e32009-11-14 01:20:54 +00002826 Constructor->getParamDecl(1)->hasDefaultArg())) &&
2827 Constructor->getTemplateSpecializationKind()
2828 != TSK_ImplicitInstantiation) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00002829 QualType ParamType = Constructor->getParamDecl(0)->getType();
2830 QualType ClassTy = Context.getTagDeclType(ClassDecl);
2831 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor170512f2009-04-01 23:51:29 +00002832 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
Douglas Gregorfd42e952010-05-27 21:28:21 +00002833 const char *ConstRef
2834 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
2835 : " const &";
Douglas Gregor170512f2009-04-01 23:51:29 +00002836 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregorfd42e952010-05-27 21:28:21 +00002837 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002838
2839 // FIXME: Rather that making the constructor invalid, we should endeavor
2840 // to fix the type.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002841 Constructor->setInvalidDecl();
Douglas Gregor4d87df52008-12-16 21:30:33 +00002842 }
2843 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00002844}
2845
John McCalldeb646e2010-08-04 01:04:25 +00002846/// CheckDestructor - Checks a fully-formed destructor definition for
2847/// well-formedness, issuing any diagnostics required. Returns true
2848/// on error.
Anders Carlssonf98849e2009-12-02 17:15:43 +00002849bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
Anders Carlsson2a50e952009-11-15 22:49:34 +00002850 CXXRecordDecl *RD = Destructor->getParent();
2851
2852 if (Destructor->isVirtual()) {
2853 SourceLocation Loc;
2854
2855 if (!Destructor->isImplicit())
2856 Loc = Destructor->getLocation();
2857 else
2858 Loc = RD->getLocation();
2859
2860 // If we have a virtual destructor, look up the deallocation function
2861 FunctionDecl *OperatorDelete = 0;
2862 DeclarationName Name =
2863 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Anders Carlssonf98849e2009-12-02 17:15:43 +00002864 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
Anders Carlsson26a807d2009-11-30 21:24:50 +00002865 return true;
John McCall1e5d75d2010-07-03 18:33:00 +00002866
2867 MarkDeclarationReferenced(Loc, OperatorDelete);
Anders Carlsson26a807d2009-11-30 21:24:50 +00002868
2869 Destructor->setOperatorDelete(OperatorDelete);
Anders Carlsson2a50e952009-11-15 22:49:34 +00002870 }
Anders Carlsson26a807d2009-11-30 21:24:50 +00002871
2872 return false;
Anders Carlsson2a50e952009-11-15 22:49:34 +00002873}
2874
Mike Stump11289f42009-09-09 15:08:12 +00002875static inline bool
Anders Carlsson5e965472009-04-30 23:18:11 +00002876FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
2877 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2878 FTI.ArgInfo[0].Param &&
John McCall48871652010-08-21 09:40:31 +00002879 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
Anders Carlsson5e965472009-04-30 23:18:11 +00002880}
2881
Douglas Gregor831c93f2008-11-05 20:51:48 +00002882/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
2883/// the well-formednes of the destructor declarator @p D with type @p
2884/// R. If there are any errors in the declarator, this routine will
Chris Lattner38378bf2009-04-25 08:28:21 +00002885/// emit diagnostics and set the declarator to invalid. Even if this happens,
2886/// will be updated to reflect a well-formed type for the destructor and
2887/// returned.
Douglas Gregor95755162010-07-01 05:10:53 +00002888QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
John McCall8e7d6562010-08-26 03:08:43 +00002889 StorageClass& SC) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002890 // C++ [class.dtor]p1:
2891 // [...] A typedef-name that names a class is a class-name
2892 // (7.1.3); however, a typedef-name that names a class shall not
2893 // be used as the identifier in the declarator for a destructor
2894 // declaration.
Douglas Gregor7861a802009-11-03 01:35:08 +00002895 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
Douglas Gregor95755162010-07-01 05:10:53 +00002896 if (isa<TypedefType>(DeclaratorType))
Chris Lattner38378bf2009-04-25 08:28:21 +00002897 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor9817f4a2009-02-09 15:09:02 +00002898 << DeclaratorType;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002899
2900 // C++ [class.dtor]p2:
2901 // A destructor is used to destroy objects of its class type. A
2902 // destructor takes no parameters, and no return type can be
2903 // specified for it (not even void). The address of a destructor
2904 // shall not be taken. A destructor shall not be static. A
2905 // destructor can be invoked for a const, volatile or const
2906 // volatile object. A destructor shall not be declared const,
2907 // volatile or const volatile (9.3.2).
John McCall8e7d6562010-08-26 03:08:43 +00002908 if (SC == SC_Static) {
Chris Lattner38378bf2009-04-25 08:28:21 +00002909 if (!D.isInvalidType())
2910 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
2911 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
Douglas Gregor95755162010-07-01 05:10:53 +00002912 << SourceRange(D.getIdentifierLoc())
2913 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
2914
John McCall8e7d6562010-08-26 03:08:43 +00002915 SC = SC_None;
Douglas Gregor831c93f2008-11-05 20:51:48 +00002916 }
Chris Lattner38378bf2009-04-25 08:28:21 +00002917 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002918 // Destructors don't have return types, but the parser will
2919 // happily parse something like:
2920 //
2921 // class X {
2922 // float ~X();
2923 // };
2924 //
2925 // The return type will be eliminated later.
Chris Lattner3b054132008-11-19 05:08:23 +00002926 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
2927 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
2928 << SourceRange(D.getIdentifierLoc());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002929 }
Mike Stump11289f42009-09-09 15:08:12 +00002930
Chris Lattner38378bf2009-04-25 08:28:21 +00002931 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2932 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00002933 if (FTI.TypeQuals & Qualifiers::Const)
Chris Lattner3b054132008-11-19 05:08:23 +00002934 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2935 << "const" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002936 if (FTI.TypeQuals & Qualifiers::Volatile)
Chris Lattner3b054132008-11-19 05:08:23 +00002937 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2938 << "volatile" << SourceRange(D.getIdentifierLoc());
John McCall8ccfcb52009-09-24 19:53:00 +00002939 if (FTI.TypeQuals & Qualifiers::Restrict)
Chris Lattner3b054132008-11-19 05:08:23 +00002940 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
2941 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner38378bf2009-04-25 08:28:21 +00002942 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002943 }
2944
2945 // Make sure we don't have any parameters.
Anders Carlsson5e965472009-04-30 23:18:11 +00002946 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002947 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
2948
2949 // Delete the parameters.
Chris Lattner38378bf2009-04-25 08:28:21 +00002950 FTI.freeArgs();
2951 D.setInvalidType();
Douglas Gregor831c93f2008-11-05 20:51:48 +00002952 }
2953
Mike Stump11289f42009-09-09 15:08:12 +00002954 // Make sure the destructor isn't variadic.
Chris Lattner38378bf2009-04-25 08:28:21 +00002955 if (FTI.isVariadic) {
Douglas Gregor831c93f2008-11-05 20:51:48 +00002956 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner38378bf2009-04-25 08:28:21 +00002957 D.setInvalidType();
2958 }
Douglas Gregor831c93f2008-11-05 20:51:48 +00002959
2960 // Rebuild the function type "R" without any type qualifiers or
2961 // parameters (in case any of the errors above fired) and with
2962 // "void" as the return type, since destructors don't have return
Douglas Gregor95755162010-07-01 05:10:53 +00002963 // types.
2964 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
2965 if (!Proto)
2966 return QualType();
2967
Douglas Gregor36c569f2010-02-21 22:15:06 +00002968 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0,
Douglas Gregor95755162010-07-01 05:10:53 +00002969 Proto->hasExceptionSpec(),
2970 Proto->hasAnyExceptionSpec(),
2971 Proto->getNumExceptions(),
2972 Proto->exception_begin(),
2973 Proto->getExtInfo());
Douglas Gregor831c93f2008-11-05 20:51:48 +00002974}
2975
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002976/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
2977/// well-formednes of the conversion function declarator @p D with
2978/// type @p R. If there are any errors in the declarator, this routine
2979/// will emit diagnostics and return true. Otherwise, it will return
2980/// false. Either way, the type @p R will be updated to reflect a
2981/// well-formed type for the conversion operator.
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002982void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
John McCall8e7d6562010-08-26 03:08:43 +00002983 StorageClass& SC) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002984 // C++ [class.conv.fct]p1:
2985 // Neither parameter types nor return type can be specified. The
Eli Friedman44b83ee2009-08-05 19:21:58 +00002986 // type of a conversion function (8.3.5) is "function taking no
Mike Stump11289f42009-09-09 15:08:12 +00002987 // parameter returning conversion-type-id."
John McCall8e7d6562010-08-26 03:08:43 +00002988 if (SC == SC_Static) {
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002989 if (!D.isInvalidType())
2990 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
2991 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
2992 << SourceRange(D.getIdentifierLoc());
2993 D.setInvalidType();
John McCall8e7d6562010-08-26 03:08:43 +00002994 SC = SC_None;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00002995 }
John McCall212fa2e2010-04-13 00:04:31 +00002996
2997 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
2998
Chris Lattnerb41df4f2009-04-25 08:35:12 +00002999 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003000 // Conversion functions don't have return types, but the parser will
3001 // happily parse something like:
3002 //
3003 // class X {
3004 // float operator bool();
3005 // };
3006 //
3007 // The return type will be changed later anyway.
Chris Lattner3b054132008-11-19 05:08:23 +00003008 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
3009 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
3010 << SourceRange(D.getIdentifierLoc());
John McCall212fa2e2010-04-13 00:04:31 +00003011 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003012 }
3013
John McCall212fa2e2010-04-13 00:04:31 +00003014 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
3015
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003016 // Make sure we don't have any parameters.
John McCall212fa2e2010-04-13 00:04:31 +00003017 if (Proto->getNumArgs() > 0) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003018 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
3019
3020 // Delete the parameters.
Chris Lattner5742c1e2009-01-20 21:06:38 +00003021 D.getTypeObject(0).Fun.freeArgs();
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003022 D.setInvalidType();
John McCall212fa2e2010-04-13 00:04:31 +00003023 } else if (Proto->isVariadic()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003024 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003025 D.setInvalidType();
3026 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003027
John McCall212fa2e2010-04-13 00:04:31 +00003028 // Diagnose "&operator bool()" and other such nonsense. This
3029 // is actually a gcc extension which we don't support.
3030 if (Proto->getResultType() != ConvType) {
3031 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
3032 << Proto->getResultType();
3033 D.setInvalidType();
3034 ConvType = Proto->getResultType();
3035 }
3036
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003037 // C++ [class.conv.fct]p4:
3038 // The conversion-type-id shall not represent a function type nor
3039 // an array type.
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003040 if (ConvType->isArrayType()) {
3041 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
3042 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003043 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003044 } else if (ConvType->isFunctionType()) {
3045 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
3046 ConvType = Context.getPointerType(ConvType);
Chris Lattnerb41df4f2009-04-25 08:35:12 +00003047 D.setInvalidType();
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003048 }
3049
3050 // Rebuild the function type "R" without any parameters (in case any
3051 // of the errors above fired) and with the conversion type as the
Mike Stump11289f42009-09-09 15:08:12 +00003052 // return type.
John McCall212fa2e2010-04-13 00:04:31 +00003053 if (D.isInvalidType()) {
3054 R = Context.getFunctionType(ConvType, 0, 0, false,
3055 Proto->getTypeQuals(),
3056 Proto->hasExceptionSpec(),
3057 Proto->hasAnyExceptionSpec(),
3058 Proto->getNumExceptions(),
3059 Proto->exception_begin(),
3060 Proto->getExtInfo());
3061 }
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003062
Douglas Gregor5fb53972009-01-14 15:45:31 +00003063 // C++0x explicit conversion operators.
3064 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
Mike Stump11289f42009-09-09 15:08:12 +00003065 Diag(D.getDeclSpec().getExplicitSpecLoc(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00003066 diag::warn_explicit_conversion_functions)
3067 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003068}
3069
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003070/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3071/// the declaration of the given C++ conversion function. This routine
3072/// is responsible for recording the conversion function in the C++
3073/// class, if possible.
John McCall48871652010-08-21 09:40:31 +00003074Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003075 assert(Conversion && "Expected to receive a conversion function declaration");
3076
Douglas Gregor4287b372008-12-12 08:25:50 +00003077 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003078
3079 // Make sure we aren't redeclaring the conversion function.
3080 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003081
3082 // C++ [class.conv.fct]p1:
3083 // [...] A conversion function is never used to convert a
3084 // (possibly cv-qualified) object to the (possibly cv-qualified)
3085 // same object type (or a reference to it), to a (possibly
3086 // cv-qualified) base class of that type (or a reference to it),
3087 // or to (possibly cv-qualified) void.
Mike Stump87c57ac2009-05-16 07:39:55 +00003088 // FIXME: Suppress this warning if the conversion function ends up being a
3089 // virtual function that overrides a virtual function in a base class.
Mike Stump11289f42009-09-09 15:08:12 +00003090 QualType ClassType
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003091 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003092 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003093 ConvType = ConvTypeRef->getPointeeType();
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003094 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
3095 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
Douglas Gregore47191c2010-09-13 16:44:26 +00003096 /* Suppress diagnostics for instantiations. */;
Douglas Gregor6309e3d2010-09-12 07:22:28 +00003097 else if (ConvType->isRecordType()) {
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003098 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
3099 if (ConvType == ClassType)
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003100 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003101 << ClassType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003102 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003103 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003104 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003105 } else if (ConvType->isVoidType()) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +00003106 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003107 << ClassType << ConvType;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003108 }
3109
Douglas Gregor457104e2010-09-29 04:25:11 +00003110 if (FunctionTemplateDecl *ConversionTemplate
3111 = Conversion->getDescribedFunctionTemplate())
3112 return ConversionTemplate;
3113
John McCall48871652010-08-21 09:40:31 +00003114 return Conversion;
Douglas Gregordbc5daf2008-11-07 20:08:42 +00003115}
3116
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003117//===----------------------------------------------------------------------===//
3118// Namespace Handling
3119//===----------------------------------------------------------------------===//
3120
John McCallb1be5232010-08-26 09:15:37 +00003121
3122
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003123/// ActOnStartNamespaceDef - This is called at the start of a namespace
3124/// definition.
John McCall48871652010-08-21 09:40:31 +00003125Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
Sebastian Redl67667942010-08-27 23:12:46 +00003126 SourceLocation InlineLoc,
John McCallb1be5232010-08-26 09:15:37 +00003127 SourceLocation IdentLoc,
3128 IdentifierInfo *II,
3129 SourceLocation LBrace,
3130 AttributeList *AttrList) {
Douglas Gregor086cae62010-08-19 20:55:47 +00003131 // anonymous namespace starts at its left brace
3132 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
3133 (II ? IdentLoc : LBrace) , II);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003134 Namespc->setLBracLoc(LBrace);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003135 Namespc->setInline(InlineLoc.isValid());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003136
3137 Scope *DeclRegionScope = NamespcScope->getParent();
3138
Anders Carlssona7bcade2010-02-07 01:09:23 +00003139 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
3140
Eli Friedman570024a2010-08-05 06:57:20 +00003141 if (const VisibilityAttr *attr = Namespc->getAttr<VisibilityAttr>())
John McCallb1be5232010-08-26 09:15:37 +00003142 PushVisibilityAttr(attr);
Eli Friedman570024a2010-08-05 06:57:20 +00003143
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003144 if (II) {
3145 // C++ [namespace.def]p2:
3146 // The identifier in an original-namespace-definition shall not have been
3147 // previously defined in the declarative region in which the
3148 // original-namespace-definition appears. The identifier in an
3149 // original-namespace-definition is the name of the namespace. Subsequently
3150 // in that declarative region, it is treated as an original-namespace-name.
3151
John McCall9f3059a2009-10-09 21:13:30 +00003152 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003153 = LookupSingleName(DeclRegionScope, II, IdentLoc, LookupOrdinaryName,
John McCall5cebab12009-11-18 07:57:50 +00003154 ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00003155
Douglas Gregor91f84212008-12-11 16:49:14 +00003156 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
3157 // This is an extended namespace definition.
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003158 if (Namespc->isInline() != OrigNS->isInline()) {
3159 // inline-ness must match
3160 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3161 << Namespc->isInline();
3162 Diag(OrigNS->getLocation(), diag::note_previous_definition);
3163 Namespc->setInvalidDecl();
3164 // Recover by ignoring the new namespace's inline status.
3165 Namespc->setInline(OrigNS->isInline());
3166 }
3167
Douglas Gregor91f84212008-12-11 16:49:14 +00003168 // Attach this namespace decl to the chain of extended namespace
3169 // definitions.
3170 OrigNS->setNextNamespace(Namespc);
3171 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003172
Mike Stump11289f42009-09-09 15:08:12 +00003173 // Remove the previous declaration from the scope.
John McCall48871652010-08-21 09:40:31 +00003174 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor7a4fad12008-12-11 20:41:00 +00003175 IdResolver.RemoveDecl(OrigNS);
John McCall48871652010-08-21 09:40:31 +00003176 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003177 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003178 } else if (PrevDecl) {
3179 // This is an invalid name redefinition.
3180 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
3181 << Namespc->getDeclName();
3182 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3183 Namespc->setInvalidDecl();
3184 // Continue on to push Namespc as current DeclContext and return it.
Douglas Gregor87f54062009-09-15 22:30:29 +00003185 } else if (II->isStr("std") &&
Sebastian Redl50c68252010-08-31 00:36:30 +00003186 CurContext->getRedeclContext()->isTranslationUnit()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003187 // This is the first "real" definition of the namespace "std", so update
3188 // our cache of the "std" namespace to point at this definition.
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003189 if (NamespaceDecl *StdNS = getStdNamespace()) {
Douglas Gregor87f54062009-09-15 22:30:29 +00003190 // We had already defined a dummy namespace "std". Link this new
3191 // namespace definition to the dummy namespace "std".
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003192 StdNS->setNextNamespace(Namespc);
3193 StdNS->setLocation(IdentLoc);
3194 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
Douglas Gregor87f54062009-09-15 22:30:29 +00003195 }
3196
3197 // Make our StdNamespace cache point at the first real definition of the
3198 // "std" namespace.
3199 StdNamespace = Namespc;
Mike Stump11289f42009-09-09 15:08:12 +00003200 }
Douglas Gregor91f84212008-12-11 16:49:14 +00003201
3202 PushOnScopeChains(Namespc, DeclRegionScope);
3203 } else {
John McCall4fa53422009-10-01 00:25:31 +00003204 // Anonymous namespaces.
John McCall0db42252009-12-16 02:06:49 +00003205 assert(Namespc->isAnonymousNamespace());
John McCall0db42252009-12-16 02:06:49 +00003206
3207 // Link the anonymous namespace into its parent.
3208 NamespaceDecl *PrevDecl;
Sebastian Redl50c68252010-08-31 00:36:30 +00003209 DeclContext *Parent = CurContext->getRedeclContext();
John McCall0db42252009-12-16 02:06:49 +00003210 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
3211 PrevDecl = TU->getAnonymousNamespace();
3212 TU->setAnonymousNamespace(Namespc);
3213 } else {
3214 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
3215 PrevDecl = ND->getAnonymousNamespace();
3216 ND->setAnonymousNamespace(Namespc);
3217 }
3218
3219 // Link the anonymous namespace with its previous declaration.
3220 if (PrevDecl) {
3221 assert(PrevDecl->isAnonymousNamespace());
3222 assert(!PrevDecl->getNextNamespace());
3223 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
3224 PrevDecl->setNextNamespace(Namespc);
Sebastian Redlb5c2baa2010-08-31 00:36:36 +00003225
3226 if (Namespc->isInline() != PrevDecl->isInline()) {
3227 // inline-ness must match
3228 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
3229 << Namespc->isInline();
3230 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3231 Namespc->setInvalidDecl();
3232 // Recover by ignoring the new namespace's inline status.
3233 Namespc->setInline(PrevDecl->isInline());
3234 }
John McCall0db42252009-12-16 02:06:49 +00003235 }
John McCall4fa53422009-10-01 00:25:31 +00003236
Douglas Gregorf9f54ea2010-03-24 00:46:35 +00003237 CurContext->addDecl(Namespc);
3238
John McCall4fa53422009-10-01 00:25:31 +00003239 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3240 // behaves as if it were replaced by
3241 // namespace unique { /* empty body */ }
3242 // using namespace unique;
3243 // namespace unique { namespace-body }
3244 // where all occurrences of 'unique' in a translation unit are
3245 // replaced by the same identifier and this identifier differs
3246 // from all other identifiers in the entire program.
3247
3248 // We just create the namespace with an empty name and then add an
3249 // implicit using declaration, just like the standard suggests.
3250 //
3251 // CodeGen enforces the "universally unique" aspect by giving all
3252 // declarations semantically contained within an anonymous
3253 // namespace internal linkage.
3254
John McCall0db42252009-12-16 02:06:49 +00003255 if (!PrevDecl) {
3256 UsingDirectiveDecl* UD
3257 = UsingDirectiveDecl::Create(Context, CurContext,
3258 /* 'using' */ LBrace,
3259 /* 'namespace' */ SourceLocation(),
3260 /* qualifier */ SourceRange(),
3261 /* NNS */ NULL,
3262 /* identifier */ SourceLocation(),
3263 Namespc,
3264 /* Ancestor */ CurContext);
3265 UD->setImplicit();
3266 CurContext->addDecl(UD);
3267 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003268 }
3269
3270 // Although we could have an invalid decl (i.e. the namespace name is a
3271 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump87c57ac2009-05-16 07:39:55 +00003272 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3273 // for the namespace has the declarations that showed up in that particular
3274 // namespace definition.
Douglas Gregor91f84212008-12-11 16:49:14 +00003275 PushDeclContext(NamespcScope, Namespc);
John McCall48871652010-08-21 09:40:31 +00003276 return Namespc;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003277}
3278
Sebastian Redla6602e92009-11-23 15:34:23 +00003279/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3280/// is a namespace alias, returns the namespace it points to.
3281static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
3282 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
3283 return AD->getNamespace();
3284 return dyn_cast_or_null<NamespaceDecl>(D);
3285}
3286
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003287/// ActOnFinishNamespaceDef - This callback is called after a namespace is
3288/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
John McCall48871652010-08-21 09:40:31 +00003289void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003290 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
3291 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
3292 Namespc->setRBracLoc(RBrace);
3293 PopDeclContext();
Eli Friedman570024a2010-08-05 06:57:20 +00003294 if (Namespc->hasAttr<VisibilityAttr>())
3295 PopPragmaVisibility();
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003296}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003297
John McCall28a0cf72010-08-25 07:42:41 +00003298CXXRecordDecl *Sema::getStdBadAlloc() const {
3299 return cast_or_null<CXXRecordDecl>(
3300 StdBadAlloc.get(Context.getExternalSource()));
3301}
3302
3303NamespaceDecl *Sema::getStdNamespace() const {
3304 return cast_or_null<NamespaceDecl>(
3305 StdNamespace.get(Context.getExternalSource()));
3306}
3307
Douglas Gregorcdf87022010-06-29 17:53:46 +00003308/// \brief Retrieve the special "std" namespace, which may require us to
3309/// implicitly define the namespace.
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003310NamespaceDecl *Sema::getOrCreateStdNamespace() {
Douglas Gregorcdf87022010-06-29 17:53:46 +00003311 if (!StdNamespace) {
3312 // The "std" namespace has not yet been defined, so build one implicitly.
3313 StdNamespace = NamespaceDecl::Create(Context,
3314 Context.getTranslationUnitDecl(),
3315 SourceLocation(),
3316 &PP.getIdentifierTable().get("std"));
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003317 getStdNamespace()->setImplicit(true);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003318 }
3319
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00003320 return getStdNamespace();
Douglas Gregorcdf87022010-06-29 17:53:46 +00003321}
3322
John McCall48871652010-08-21 09:40:31 +00003323Decl *Sema::ActOnUsingDirective(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00003324 SourceLocation UsingLoc,
3325 SourceLocation NamespcLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003326 CXXScopeSpec &SS,
Chris Lattner83f095c2009-03-28 19:18:32 +00003327 SourceLocation IdentLoc,
3328 IdentifierInfo *NamespcName,
3329 AttributeList *AttrList) {
Douglas Gregord7c4d982008-12-30 03:27:21 +00003330 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
3331 assert(NamespcName && "Invalid NamespcName.");
3332 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003333 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregord7c4d982008-12-30 03:27:21 +00003334
Douglas Gregor889ceb72009-02-03 19:21:40 +00003335 UsingDirectiveDecl *UDir = 0;
Douglas Gregorcdf87022010-06-29 17:53:46 +00003336 NestedNameSpecifier *Qualifier = 0;
3337 if (SS.isSet())
3338 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3339
Douglas Gregor34074322009-01-14 22:20:51 +00003340 // Lookup namespace name.
John McCall27b18f82009-11-17 02:14:36 +00003341 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
3342 LookupParsedName(R, S, &SS);
3343 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00003344 return 0;
John McCall27b18f82009-11-17 02:14:36 +00003345
Douglas Gregorcdf87022010-06-29 17:53:46 +00003346 if (R.empty()) {
3347 // Allow "using namespace std;" or "using namespace ::std;" even if
3348 // "std" hasn't been defined yet, for GCC compatibility.
3349 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
3350 NamespcName->isStr("std")) {
3351 Diag(IdentLoc, diag::ext_using_undefined_std);
Argyrios Kyrtzidis4f8e1732010-08-02 07:14:39 +00003352 R.addDecl(getOrCreateStdNamespace());
Douglas Gregorcdf87022010-06-29 17:53:46 +00003353 R.resolveKind();
3354 }
3355 // Otherwise, attempt typo correction.
3356 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
3357 CTC_NoKeywords, 0)) {
3358 if (R.getAsSingle<NamespaceDecl>() ||
3359 R.getAsSingle<NamespaceAliasDecl>()) {
3360 if (DeclContext *DC = computeDeclContext(SS, false))
3361 Diag(IdentLoc, diag::err_using_directive_member_suggest)
3362 << NamespcName << DC << Corrected << SS.getRange()
3363 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3364 else
3365 Diag(IdentLoc, diag::err_using_directive_suggest)
3366 << NamespcName << Corrected
3367 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
3368 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
3369 << Corrected;
3370
3371 NamespcName = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00003372 } else {
3373 R.clear();
3374 R.setLookupName(NamespcName);
Douglas Gregorcdf87022010-06-29 17:53:46 +00003375 }
3376 }
3377 }
3378
John McCall9f3059a2009-10-09 21:13:30 +00003379 if (!R.empty()) {
Sebastian Redla6602e92009-11-23 15:34:23 +00003380 NamedDecl *Named = R.getFoundDecl();
3381 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
3382 && "expected namespace decl");
Douglas Gregor889ceb72009-02-03 19:21:40 +00003383 // C++ [namespace.udir]p1:
3384 // A using-directive specifies that the names in the nominated
3385 // namespace can be used in the scope in which the
3386 // using-directive appears after the using-directive. During
3387 // unqualified name lookup (3.4.1), the names appear as if they
3388 // were declared in the nearest enclosing namespace which
3389 // contains both the using-directive and the nominated
Eli Friedman44b83ee2009-08-05 19:21:58 +00003390 // namespace. [Note: in this context, "contains" means "contains
3391 // directly or indirectly". ]
Douglas Gregor889ceb72009-02-03 19:21:40 +00003392
3393 // Find enclosing context containing both using-directive and
3394 // nominated namespace.
Sebastian Redla6602e92009-11-23 15:34:23 +00003395 NamespaceDecl *NS = getNamespaceDecl(Named);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003396 DeclContext *CommonAncestor = cast<DeclContext>(NS);
3397 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
3398 CommonAncestor = CommonAncestor->getParent();
3399
Sebastian Redla6602e92009-11-23 15:34:23 +00003400 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
Douglas Gregor3bc6e4c2009-05-30 06:31:56 +00003401 SS.getRange(),
3402 (NestedNameSpecifier *)SS.getScopeRep(),
Sebastian Redla6602e92009-11-23 15:34:23 +00003403 IdentLoc, Named, CommonAncestor);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003404 PushUsingDirective(S, UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003405 } else {
Chris Lattner8dca2e92009-01-06 07:24:29 +00003406 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregord7c4d982008-12-30 03:27:21 +00003407 }
3408
Douglas Gregor889ceb72009-02-03 19:21:40 +00003409 // FIXME: We ignore attributes for now.
Douglas Gregord7c4d982008-12-30 03:27:21 +00003410 delete AttrList;
John McCall48871652010-08-21 09:40:31 +00003411 return UDir;
Douglas Gregor889ceb72009-02-03 19:21:40 +00003412}
3413
3414void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
3415 // If scope has associated entity, then using directive is at namespace
3416 // or translation unit scope. We add UsingDirectiveDecls, into
3417 // it's lookup structure.
3418 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003419 Ctx->addDecl(UDir);
Douglas Gregor889ceb72009-02-03 19:21:40 +00003420 else
3421 // Otherwise it is block-sope. using-directives will affect lookup
3422 // only to the end of scope.
John McCall48871652010-08-21 09:40:31 +00003423 S->PushUsingDirective(UDir);
Douglas Gregord7c4d982008-12-30 03:27:21 +00003424}
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00003425
Douglas Gregorfec52632009-06-20 00:51:54 +00003426
John McCall48871652010-08-21 09:40:31 +00003427Decl *Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlsson7b194b72009-08-29 19:54:19 +00003428 AccessSpecifier AS,
John McCalla0097262009-12-11 02:10:03 +00003429 bool HasUsingKeyword,
Anders Carlsson59140b32009-08-28 03:16:11 +00003430 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003431 CXXScopeSpec &SS,
Douglas Gregor220f4272009-11-04 16:30:06 +00003432 UnqualifiedId &Name,
Anders Carlsson59140b32009-08-28 03:16:11 +00003433 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003434 bool IsTypeName,
3435 SourceLocation TypenameLoc) {
Douglas Gregorfec52632009-06-20 00:51:54 +00003436 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Mike Stump11289f42009-09-09 15:08:12 +00003437
Douglas Gregor220f4272009-11-04 16:30:06 +00003438 switch (Name.getKind()) {
3439 case UnqualifiedId::IK_Identifier:
3440 case UnqualifiedId::IK_OperatorFunctionId:
Alexis Hunt34458502009-11-28 04:44:28 +00003441 case UnqualifiedId::IK_LiteralOperatorId:
Douglas Gregor220f4272009-11-04 16:30:06 +00003442 case UnqualifiedId::IK_ConversionFunctionId:
3443 break;
3444
3445 case UnqualifiedId::IK_ConstructorName:
Douglas Gregor9de54ea2010-01-13 17:31:36 +00003446 case UnqualifiedId::IK_ConstructorTemplateId:
John McCall3969e302009-12-08 07:46:18 +00003447 // C++0x inherited constructors.
3448 if (getLangOptions().CPlusPlus0x) break;
3449
Douglas Gregor220f4272009-11-04 16:30:06 +00003450 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
3451 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003452 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003453
3454 case UnqualifiedId::IK_DestructorName:
3455 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
3456 << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00003457 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003458
3459 case UnqualifiedId::IK_TemplateId:
3460 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
3461 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
John McCall48871652010-08-21 09:40:31 +00003462 return 0;
Douglas Gregor220f4272009-11-04 16:30:06 +00003463 }
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003464
3465 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
3466 DeclarationName TargetName = TargetNameInfo.getName();
John McCall3969e302009-12-08 07:46:18 +00003467 if (!TargetName)
John McCall48871652010-08-21 09:40:31 +00003468 return 0;
John McCall3969e302009-12-08 07:46:18 +00003469
John McCalla0097262009-12-11 02:10:03 +00003470 // Warn about using declarations.
3471 // TODO: store that the declaration was written without 'using' and
3472 // talk about access decls instead of using decls in the
3473 // diagnostics.
3474 if (!HasUsingKeyword) {
3475 UsingLoc = Name.getSourceRange().getBegin();
3476
3477 Diag(UsingLoc, diag::warn_access_decl_deprecated)
Douglas Gregora771f462010-03-31 17:46:05 +00003478 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
John McCalla0097262009-12-11 02:10:03 +00003479 }
3480
John McCall3f746822009-11-17 05:59:44 +00003481 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003482 TargetNameInfo, AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003483 /* IsInstantiation */ false,
3484 IsTypeName, TypenameLoc);
John McCallb96ec562009-12-04 22:46:56 +00003485 if (UD)
3486 PushOnScopeChains(UD, S, /*AddToContext*/ false);
Mike Stump11289f42009-09-09 15:08:12 +00003487
John McCall48871652010-08-21 09:40:31 +00003488 return UD;
Anders Carlsson696a3f12009-08-28 05:40:36 +00003489}
3490
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003491/// \brief Determine whether a using declaration considers the given
3492/// declarations as "equivalent", e.g., if they are redeclarations of
3493/// the same entity or are both typedefs of the same type.
3494static bool
3495IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
3496 bool &SuppressRedeclaration) {
3497 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
3498 SuppressRedeclaration = false;
3499 return true;
3500 }
3501
3502 if (TypedefDecl *TD1 = dyn_cast<TypedefDecl>(D1))
3503 if (TypedefDecl *TD2 = dyn_cast<TypedefDecl>(D2)) {
3504 SuppressRedeclaration = true;
3505 return Context.hasSameType(TD1->getUnderlyingType(),
3506 TD2->getUnderlyingType());
3507 }
3508
3509 return false;
3510}
3511
3512
John McCall84d87672009-12-10 09:41:52 +00003513/// Determines whether to create a using shadow decl for a particular
3514/// decl, given the set of decls existing prior to this using lookup.
3515bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
3516 const LookupResult &Previous) {
3517 // Diagnose finding a decl which is not from a base class of the
3518 // current class. We do this now because there are cases where this
3519 // function will silently decide not to build a shadow decl, which
3520 // will pre-empt further diagnostics.
3521 //
3522 // We don't need to do this in C++0x because we do the check once on
3523 // the qualifier.
3524 //
3525 // FIXME: diagnose the following if we care enough:
3526 // struct A { int foo; };
3527 // struct B : A { using A::foo; };
3528 // template <class T> struct C : A {};
3529 // template <class T> struct D : C<T> { using B::foo; } // <---
3530 // This is invalid (during instantiation) in C++03 because B::foo
3531 // resolves to the using decl in B, which is not a base class of D<T>.
3532 // We can't diagnose it immediately because C<T> is an unknown
3533 // specialization. The UsingShadowDecl in D<T> then points directly
3534 // to A::foo, which will look well-formed when we instantiate.
3535 // The right solution is to not collapse the shadow-decl chain.
3536 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
3537 DeclContext *OrigDC = Orig->getDeclContext();
3538
3539 // Handle enums and anonymous structs.
3540 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
3541 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
3542 while (OrigRec->isAnonymousStructOrUnion())
3543 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
3544
3545 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
3546 if (OrigDC == CurContext) {
3547 Diag(Using->getLocation(),
3548 diag::err_using_decl_nested_name_specifier_is_current_class)
3549 << Using->getNestedNameRange();
3550 Diag(Orig->getLocation(), diag::note_using_decl_target);
3551 return true;
3552 }
3553
3554 Diag(Using->getNestedNameRange().getBegin(),
3555 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3556 << Using->getTargetNestedNameDecl()
3557 << cast<CXXRecordDecl>(CurContext)
3558 << Using->getNestedNameRange();
3559 Diag(Orig->getLocation(), diag::note_using_decl_target);
3560 return true;
3561 }
3562 }
3563
3564 if (Previous.empty()) return false;
3565
3566 NamedDecl *Target = Orig;
3567 if (isa<UsingShadowDecl>(Target))
3568 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3569
John McCalla17e83e2009-12-11 02:33:26 +00003570 // If the target happens to be one of the previous declarations, we
3571 // don't have a conflict.
3572 //
3573 // FIXME: but we might be increasing its access, in which case we
3574 // should redeclare it.
3575 NamedDecl *NonTag = 0, *Tag = 0;
3576 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
3577 I != E; ++I) {
3578 NamedDecl *D = (*I)->getUnderlyingDecl();
Douglas Gregor1d9ef842010-07-07 23:08:52 +00003579 bool Result;
3580 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
3581 return Result;
John McCalla17e83e2009-12-11 02:33:26 +00003582
3583 (isa<TagDecl>(D) ? Tag : NonTag) = D;
3584 }
3585
John McCall84d87672009-12-10 09:41:52 +00003586 if (Target->isFunctionOrFunctionTemplate()) {
3587 FunctionDecl *FD;
3588 if (isa<FunctionTemplateDecl>(Target))
3589 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
3590 else
3591 FD = cast<FunctionDecl>(Target);
3592
3593 NamedDecl *OldDecl = 0;
John McCalle9cccd82010-06-16 08:42:20 +00003594 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
John McCall84d87672009-12-10 09:41:52 +00003595 case Ovl_Overload:
3596 return false;
3597
3598 case Ovl_NonFunction:
John McCalle29c5cd2009-12-10 19:51:03 +00003599 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003600 break;
3601
3602 // We found a decl with the exact signature.
3603 case Ovl_Match:
John McCall84d87672009-12-10 09:41:52 +00003604 // If we're in a record, we want to hide the target, so we
3605 // return true (without a diagnostic) to tell the caller not to
3606 // build a shadow decl.
3607 if (CurContext->isRecord())
3608 return true;
3609
3610 // If we're not in a record, this is an error.
John McCalle29c5cd2009-12-10 19:51:03 +00003611 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003612 break;
3613 }
3614
3615 Diag(Target->getLocation(), diag::note_using_decl_target);
3616 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
3617 return true;
3618 }
3619
3620 // Target is not a function.
3621
John McCall84d87672009-12-10 09:41:52 +00003622 if (isa<TagDecl>(Target)) {
3623 // No conflict between a tag and a non-tag.
3624 if (!Tag) return false;
3625
John McCalle29c5cd2009-12-10 19:51:03 +00003626 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003627 Diag(Target->getLocation(), diag::note_using_decl_target);
3628 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
3629 return true;
3630 }
3631
3632 // No conflict between a tag and a non-tag.
3633 if (!NonTag) return false;
3634
John McCalle29c5cd2009-12-10 19:51:03 +00003635 Diag(Using->getLocation(), diag::err_using_decl_conflict);
John McCall84d87672009-12-10 09:41:52 +00003636 Diag(Target->getLocation(), diag::note_using_decl_target);
3637 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
3638 return true;
3639}
3640
John McCall3f746822009-11-17 05:59:44 +00003641/// Builds a shadow declaration corresponding to a 'using' declaration.
John McCall3969e302009-12-08 07:46:18 +00003642UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
John McCall3969e302009-12-08 07:46:18 +00003643 UsingDecl *UD,
3644 NamedDecl *Orig) {
John McCall3f746822009-11-17 05:59:44 +00003645
3646 // If we resolved to another shadow declaration, just coalesce them.
John McCall3969e302009-12-08 07:46:18 +00003647 NamedDecl *Target = Orig;
3648 if (isa<UsingShadowDecl>(Target)) {
3649 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
3650 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
John McCall3f746822009-11-17 05:59:44 +00003651 }
3652
3653 UsingShadowDecl *Shadow
John McCall3969e302009-12-08 07:46:18 +00003654 = UsingShadowDecl::Create(Context, CurContext,
3655 UD->getLocation(), UD, Target);
John McCall3f746822009-11-17 05:59:44 +00003656 UD->addShadowDecl(Shadow);
Douglas Gregor457104e2010-09-29 04:25:11 +00003657
3658 Shadow->setAccess(UD->getAccess());
3659 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
3660 Shadow->setInvalidDecl();
3661
John McCall3f746822009-11-17 05:59:44 +00003662 if (S)
John McCall3969e302009-12-08 07:46:18 +00003663 PushOnScopeChains(Shadow, S);
John McCall3f746822009-11-17 05:59:44 +00003664 else
John McCall3969e302009-12-08 07:46:18 +00003665 CurContext->addDecl(Shadow);
John McCall3f746822009-11-17 05:59:44 +00003666
John McCall3969e302009-12-08 07:46:18 +00003667
John McCall84d87672009-12-10 09:41:52 +00003668 return Shadow;
3669}
John McCall3969e302009-12-08 07:46:18 +00003670
John McCall84d87672009-12-10 09:41:52 +00003671/// Hides a using shadow declaration. This is required by the current
3672/// using-decl implementation when a resolvable using declaration in a
3673/// class is followed by a declaration which would hide or override
3674/// one or more of the using decl's targets; for example:
3675///
3676/// struct Base { void foo(int); };
3677/// struct Derived : Base {
3678/// using Base::foo;
3679/// void foo(int);
3680/// };
3681///
3682/// The governing language is C++03 [namespace.udecl]p12:
3683///
3684/// When a using-declaration brings names from a base class into a
3685/// derived class scope, member functions in the derived class
3686/// override and/or hide member functions with the same name and
3687/// parameter types in a base class (rather than conflicting).
3688///
3689/// There are two ways to implement this:
3690/// (1) optimistically create shadow decls when they're not hidden
3691/// by existing declarations, or
3692/// (2) don't create any shadow decls (or at least don't make them
3693/// visible) until we've fully parsed/instantiated the class.
3694/// The problem with (1) is that we might have to retroactively remove
3695/// a shadow decl, which requires several O(n) operations because the
3696/// decl structures are (very reasonably) not designed for removal.
3697/// (2) avoids this but is very fiddly and phase-dependent.
3698void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
John McCallda4458e2010-03-31 01:36:47 +00003699 if (Shadow->getDeclName().getNameKind() ==
3700 DeclarationName::CXXConversionFunctionName)
3701 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
3702
John McCall84d87672009-12-10 09:41:52 +00003703 // Remove it from the DeclContext...
3704 Shadow->getDeclContext()->removeDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003705
John McCall84d87672009-12-10 09:41:52 +00003706 // ...and the scope, if applicable...
3707 if (S) {
John McCall48871652010-08-21 09:40:31 +00003708 S->RemoveDecl(Shadow);
John McCall84d87672009-12-10 09:41:52 +00003709 IdResolver.RemoveDecl(Shadow);
John McCall3969e302009-12-08 07:46:18 +00003710 }
3711
John McCall84d87672009-12-10 09:41:52 +00003712 // ...and the using decl.
3713 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
3714
3715 // TODO: complain somehow if Shadow was used. It shouldn't
John McCallda4458e2010-03-31 01:36:47 +00003716 // be possible for this to happen, because...?
John McCall3f746822009-11-17 05:59:44 +00003717}
3718
John McCalle61f2ba2009-11-18 02:36:19 +00003719/// Builds a using declaration.
3720///
3721/// \param IsInstantiation - Whether this call arises from an
3722/// instantiation of an unresolved using declaration. We treat
3723/// the lookup differently for these declarations.
John McCall3f746822009-11-17 05:59:44 +00003724NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
3725 SourceLocation UsingLoc,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00003726 CXXScopeSpec &SS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003727 const DeclarationNameInfo &NameInfo,
Anders Carlsson696a3f12009-08-28 05:40:36 +00003728 AttributeList *AttrList,
John McCalle61f2ba2009-11-18 02:36:19 +00003729 bool IsInstantiation,
3730 bool IsTypeName,
3731 SourceLocation TypenameLoc) {
Anders Carlsson696a3f12009-08-28 05:40:36 +00003732 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003733 SourceLocation IdentLoc = NameInfo.getLoc();
Anders Carlsson696a3f12009-08-28 05:40:36 +00003734 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman561154d2009-08-27 05:09:36 +00003735
Anders Carlssonf038fc22009-08-28 05:49:21 +00003736 // FIXME: We ignore attributes for now.
3737 delete AttrList;
Mike Stump11289f42009-09-09 15:08:12 +00003738
Anders Carlsson59140b32009-08-28 03:16:11 +00003739 if (SS.isEmpty()) {
3740 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlsson696a3f12009-08-28 05:40:36 +00003741 return 0;
Anders Carlsson59140b32009-08-28 03:16:11 +00003742 }
Mike Stump11289f42009-09-09 15:08:12 +00003743
John McCall84d87672009-12-10 09:41:52 +00003744 // Do the redeclaration lookup in the current scope.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003745 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
John McCall84d87672009-12-10 09:41:52 +00003746 ForRedeclaration);
3747 Previous.setHideTags(false);
3748 if (S) {
3749 LookupName(Previous, S);
3750
3751 // It is really dumb that we have to do this.
3752 LookupResult::Filter F = Previous.makeFilter();
3753 while (F.hasNext()) {
3754 NamedDecl *D = F.next();
3755 if (!isDeclInScope(D, CurContext, S))
3756 F.erase();
3757 }
3758 F.done();
3759 } else {
3760 assert(IsInstantiation && "no scope in non-instantiation");
3761 assert(CurContext->isRecord() && "scope not record in instantiation");
3762 LookupQualifiedName(Previous, CurContext);
3763 }
3764
Mike Stump11289f42009-09-09 15:08:12 +00003765 NestedNameSpecifier *NNS =
Anders Carlsson59140b32009-08-28 03:16:11 +00003766 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3767
John McCall84d87672009-12-10 09:41:52 +00003768 // Check for invalid redeclarations.
3769 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
3770 return 0;
3771
3772 // Check for bad qualifiers.
John McCallb96ec562009-12-04 22:46:56 +00003773 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
3774 return 0;
3775
John McCall84c16cf2009-11-12 03:15:40 +00003776 DeclContext *LookupContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003777 NamedDecl *D;
John McCall84c16cf2009-11-12 03:15:40 +00003778 if (!LookupContext) {
John McCalle61f2ba2009-11-18 02:36:19 +00003779 if (IsTypeName) {
John McCallb96ec562009-12-04 22:46:56 +00003780 // FIXME: not all declaration name kinds are legal here
3781 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
3782 UsingLoc, TypenameLoc,
3783 SS.getRange(), NNS,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003784 IdentLoc, NameInfo.getName());
John McCallb96ec562009-12-04 22:46:56 +00003785 } else {
3786 D = UnresolvedUsingValueDecl::Create(Context, CurContext,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003787 UsingLoc, SS.getRange(),
3788 NNS, NameInfo);
John McCalle61f2ba2009-11-18 02:36:19 +00003789 }
John McCallb96ec562009-12-04 22:46:56 +00003790 } else {
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003791 D = UsingDecl::Create(Context, CurContext,
3792 SS.getRange(), UsingLoc, NNS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00003793 IsTypeName);
Anders Carlssonf038fc22009-08-28 05:49:21 +00003794 }
John McCallb96ec562009-12-04 22:46:56 +00003795 D->setAccess(AS);
3796 CurContext->addDecl(D);
3797
3798 if (!LookupContext) return D;
3799 UsingDecl *UD = cast<UsingDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00003800
John McCall0b66eb32010-05-01 00:40:08 +00003801 if (RequireCompleteDeclContext(SS, LookupContext)) {
John McCall3969e302009-12-08 07:46:18 +00003802 UD->setInvalidDecl();
3803 return UD;
Anders Carlsson59140b32009-08-28 03:16:11 +00003804 }
3805
John McCall3969e302009-12-08 07:46:18 +00003806 // Look up the target name.
3807
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003808 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle61f2ba2009-11-18 02:36:19 +00003809
John McCall3969e302009-12-08 07:46:18 +00003810 // Unlike most lookups, we don't always want to hide tag
3811 // declarations: tag names are visible through the using declaration
3812 // even if hidden by ordinary names, *except* in a dependent context
3813 // where it's important for the sanity of two-phase lookup.
John McCalle61f2ba2009-11-18 02:36:19 +00003814 if (!IsInstantiation)
3815 R.setHideTags(false);
John McCall3f746822009-11-17 05:59:44 +00003816
John McCall27b18f82009-11-17 02:14:36 +00003817 LookupQualifiedName(R, LookupContext);
Mike Stump11289f42009-09-09 15:08:12 +00003818
John McCall9f3059a2009-10-09 21:13:30 +00003819 if (R.empty()) {
Douglas Gregore40876a2009-10-13 21:16:44 +00003820 Diag(IdentLoc, diag::err_no_member)
Abramo Bagnara8de74e92010-08-12 11:46:03 +00003821 << NameInfo.getName() << LookupContext << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003822 UD->setInvalidDecl();
3823 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003824 }
3825
John McCallb96ec562009-12-04 22:46:56 +00003826 if (R.isAmbiguous()) {
3827 UD->setInvalidDecl();
3828 return UD;
3829 }
Mike Stump11289f42009-09-09 15:08:12 +00003830
John McCalle61f2ba2009-11-18 02:36:19 +00003831 if (IsTypeName) {
3832 // If we asked for a typename and got a non-type decl, error out.
John McCallb96ec562009-12-04 22:46:56 +00003833 if (!R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003834 Diag(IdentLoc, diag::err_using_typename_non_type);
3835 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3836 Diag((*I)->getUnderlyingDecl()->getLocation(),
3837 diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003838 UD->setInvalidDecl();
3839 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003840 }
3841 } else {
3842 // If we asked for a non-typename and we got a type, error out,
3843 // but only if this is an instantiation of an unresolved using
3844 // decl. Otherwise just silently find the type name.
John McCallb96ec562009-12-04 22:46:56 +00003845 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003846 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
3847 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
John McCallb96ec562009-12-04 22:46:56 +00003848 UD->setInvalidDecl();
3849 return UD;
John McCalle61f2ba2009-11-18 02:36:19 +00003850 }
Anders Carlsson59140b32009-08-28 03:16:11 +00003851 }
3852
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003853 // C++0x N2914 [namespace.udecl]p6:
3854 // A using-declaration shall not name a namespace.
John McCallb96ec562009-12-04 22:46:56 +00003855 if (R.getAsSingle<NamespaceDecl>()) {
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003856 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
3857 << SS.getRange();
John McCallb96ec562009-12-04 22:46:56 +00003858 UD->setInvalidDecl();
3859 return UD;
Anders Carlsson5a9c5ac2009-08-28 03:35:18 +00003860 }
Mike Stump11289f42009-09-09 15:08:12 +00003861
John McCall84d87672009-12-10 09:41:52 +00003862 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3863 if (!CheckUsingShadowDecl(UD, *I, Previous))
3864 BuildUsingShadowDecl(S, UD, *I);
3865 }
John McCall3f746822009-11-17 05:59:44 +00003866
3867 return UD;
Douglas Gregorfec52632009-06-20 00:51:54 +00003868}
3869
John McCall84d87672009-12-10 09:41:52 +00003870/// Checks that the given using declaration is not an invalid
3871/// redeclaration. Note that this is checking only for the using decl
3872/// itself, not for any ill-formedness among the UsingShadowDecls.
3873bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
3874 bool isTypeName,
3875 const CXXScopeSpec &SS,
3876 SourceLocation NameLoc,
3877 const LookupResult &Prev) {
3878 // C++03 [namespace.udecl]p8:
3879 // C++0x [namespace.udecl]p10:
3880 // A using-declaration is a declaration and can therefore be used
3881 // repeatedly where (and only where) multiple declarations are
3882 // allowed.
Douglas Gregor4b718ee2010-05-06 23:31:27 +00003883 //
3884 // That's in non-member contexts.
Sebastian Redl50c68252010-08-31 00:36:30 +00003885 if (!CurContext->getRedeclContext()->isRecord())
John McCall84d87672009-12-10 09:41:52 +00003886 return false;
3887
3888 NestedNameSpecifier *Qual
3889 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3890
3891 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
3892 NamedDecl *D = *I;
3893
3894 bool DTypename;
3895 NestedNameSpecifier *DQual;
3896 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
3897 DTypename = UD->isTypeName();
3898 DQual = UD->getTargetNestedNameDecl();
3899 } else if (UnresolvedUsingValueDecl *UD
3900 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
3901 DTypename = false;
3902 DQual = UD->getTargetNestedNameSpecifier();
3903 } else if (UnresolvedUsingTypenameDecl *UD
3904 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3905 DTypename = true;
3906 DQual = UD->getTargetNestedNameSpecifier();
3907 } else continue;
3908
3909 // using decls differ if one says 'typename' and the other doesn't.
3910 // FIXME: non-dependent using decls?
3911 if (isTypeName != DTypename) continue;
3912
3913 // using decls differ if they name different scopes (but note that
3914 // template instantiation can cause this check to trigger when it
3915 // didn't before instantiation).
3916 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
3917 Context.getCanonicalNestedNameSpecifier(DQual))
3918 continue;
3919
3920 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
John McCalle29c5cd2009-12-10 19:51:03 +00003921 Diag(D->getLocation(), diag::note_using_decl) << 1;
John McCall84d87672009-12-10 09:41:52 +00003922 return true;
3923 }
3924
3925 return false;
3926}
3927
John McCall3969e302009-12-08 07:46:18 +00003928
John McCallb96ec562009-12-04 22:46:56 +00003929/// Checks that the given nested-name qualifier used in a using decl
3930/// in the current context is appropriately related to the current
3931/// scope. If an error is found, diagnoses it and returns true.
3932bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
3933 const CXXScopeSpec &SS,
3934 SourceLocation NameLoc) {
John McCall3969e302009-12-08 07:46:18 +00003935 DeclContext *NamedContext = computeDeclContext(SS);
John McCallb96ec562009-12-04 22:46:56 +00003936
John McCall3969e302009-12-08 07:46:18 +00003937 if (!CurContext->isRecord()) {
3938 // C++03 [namespace.udecl]p3:
3939 // C++0x [namespace.udecl]p8:
3940 // A using-declaration for a class member shall be a member-declaration.
3941
3942 // If we weren't able to compute a valid scope, it must be a
3943 // dependent class scope.
3944 if (!NamedContext || NamedContext->isRecord()) {
3945 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
3946 << SS.getRange();
3947 return true;
3948 }
3949
3950 // Otherwise, everything is known to be fine.
3951 return false;
3952 }
3953
3954 // The current scope is a record.
3955
3956 // If the named context is dependent, we can't decide much.
3957 if (!NamedContext) {
3958 // FIXME: in C++0x, we can diagnose if we can prove that the
3959 // nested-name-specifier does not refer to a base class, which is
3960 // still possible in some cases.
3961
3962 // Otherwise we have to conservatively report that things might be
3963 // okay.
3964 return false;
3965 }
3966
3967 if (!NamedContext->isRecord()) {
3968 // Ideally this would point at the last name in the specifier,
3969 // but we don't have that level of source info.
3970 Diag(SS.getRange().getBegin(),
3971 diag::err_using_decl_nested_name_specifier_is_not_class)
3972 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
3973 return true;
3974 }
3975
3976 if (getLangOptions().CPlusPlus0x) {
3977 // C++0x [namespace.udecl]p3:
3978 // In a using-declaration used as a member-declaration, the
3979 // nested-name-specifier shall name a base class of the class
3980 // being defined.
3981
3982 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
3983 cast<CXXRecordDecl>(NamedContext))) {
3984 if (CurContext == NamedContext) {
3985 Diag(NameLoc,
3986 diag::err_using_decl_nested_name_specifier_is_current_class)
3987 << SS.getRange();
3988 return true;
3989 }
3990
3991 Diag(SS.getRange().getBegin(),
3992 diag::err_using_decl_nested_name_specifier_is_not_base_class)
3993 << (NestedNameSpecifier*) SS.getScopeRep()
3994 << cast<CXXRecordDecl>(CurContext)
3995 << SS.getRange();
3996 return true;
3997 }
3998
3999 return false;
4000 }
4001
4002 // C++03 [namespace.udecl]p4:
4003 // A using-declaration used as a member-declaration shall refer
4004 // to a member of a base class of the class being defined [etc.].
4005
4006 // Salient point: SS doesn't have to name a base class as long as
4007 // lookup only finds members from base classes. Therefore we can
4008 // diagnose here only if we can prove that that can't happen,
4009 // i.e. if the class hierarchies provably don't intersect.
4010
4011 // TODO: it would be nice if "definitely valid" results were cached
4012 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4013 // need to be repeated.
4014
4015 struct UserData {
4016 llvm::DenseSet<const CXXRecordDecl*> Bases;
4017
4018 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
4019 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4020 Data->Bases.insert(Base);
4021 return true;
4022 }
4023
4024 bool hasDependentBases(const CXXRecordDecl *Class) {
4025 return !Class->forallBases(collect, this);
4026 }
4027
4028 /// Returns true if the base is dependent or is one of the
4029 /// accumulated base classes.
4030 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
4031 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
4032 return !Data->Bases.count(Base);
4033 }
4034
4035 bool mightShareBases(const CXXRecordDecl *Class) {
4036 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
4037 }
4038 };
4039
4040 UserData Data;
4041
4042 // Returns false if we find a dependent base.
4043 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
4044 return false;
4045
4046 // Returns false if the class has a dependent base or if it or one
4047 // of its bases is present in the base set of the current context.
4048 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
4049 return false;
4050
4051 Diag(SS.getRange().getBegin(),
4052 diag::err_using_decl_nested_name_specifier_is_not_base_class)
4053 << (NestedNameSpecifier*) SS.getScopeRep()
4054 << cast<CXXRecordDecl>(CurContext)
4055 << SS.getRange();
4056
4057 return true;
John McCallb96ec562009-12-04 22:46:56 +00004058}
4059
John McCall48871652010-08-21 09:40:31 +00004060Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004061 SourceLocation NamespaceLoc,
Chris Lattner83f095c2009-03-28 19:18:32 +00004062 SourceLocation AliasLoc,
4063 IdentifierInfo *Alias,
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00004064 CXXScopeSpec &SS,
Anders Carlsson47952ae2009-03-28 22:53:22 +00004065 SourceLocation IdentLoc,
4066 IdentifierInfo *Ident) {
Mike Stump11289f42009-09-09 15:08:12 +00004067
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004068 // Lookup the namespace name.
John McCall27b18f82009-11-17 02:14:36 +00004069 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
4070 LookupParsedName(R, S, &SS);
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004071
Anders Carlssondca83c42009-03-28 06:23:46 +00004072 // Check if we have a previous declaration with the same name.
Douglas Gregor5cf8d672010-05-03 15:37:31 +00004073 NamedDecl *PrevDecl
4074 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
4075 ForRedeclaration);
4076 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
4077 PrevDecl = 0;
4078
4079 if (PrevDecl) {
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004080 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
Mike Stump11289f42009-09-09 15:08:12 +00004081 // We already have an alias with the same name that points to the same
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004082 // namespace, so don't create a new one.
Douglas Gregor4667eff2010-03-26 22:59:39 +00004083 // FIXME: At some point, we'll want to create the (redundant)
4084 // declaration to maintain better source information.
John McCall9f3059a2009-10-09 21:13:30 +00004085 if (!R.isAmbiguous() && !R.empty() &&
Douglas Gregor4667eff2010-03-26 22:59:39 +00004086 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
John McCall48871652010-08-21 09:40:31 +00004087 return 0;
Anders Carlssonbb1e4722009-03-28 23:53:49 +00004088 }
Mike Stump11289f42009-09-09 15:08:12 +00004089
Anders Carlssondca83c42009-03-28 06:23:46 +00004090 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
4091 diag::err_redefinition_different_kind;
4092 Diag(AliasLoc, DiagID) << Alias;
4093 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall48871652010-08-21 09:40:31 +00004094 return 0;
Anders Carlssondca83c42009-03-28 06:23:46 +00004095 }
4096
John McCall27b18f82009-11-17 02:14:36 +00004097 if (R.isAmbiguous())
John McCall48871652010-08-21 09:40:31 +00004098 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004099
John McCall9f3059a2009-10-09 21:13:30 +00004100 if (R.empty()) {
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004101 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4102 CTC_NoKeywords, 0)) {
4103 if (R.getAsSingle<NamespaceDecl>() ||
4104 R.getAsSingle<NamespaceAliasDecl>()) {
4105 if (DeclContext *DC = computeDeclContext(SS, false))
4106 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4107 << Ident << DC << Corrected << SS.getRange()
4108 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4109 else
4110 Diag(IdentLoc, diag::err_using_directive_suggest)
4111 << Ident << Corrected
4112 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4113
4114 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4115 << Corrected;
4116
4117 Ident = Corrected.getAsIdentifierInfo();
Douglas Gregorc048c522010-06-29 19:27:42 +00004118 } else {
4119 R.clear();
4120 R.setLookupName(Ident);
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004121 }
4122 }
4123
4124 if (R.empty()) {
4125 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
John McCall48871652010-08-21 09:40:31 +00004126 return 0;
Douglas Gregor9629e9a2010-06-29 18:55:19 +00004127 }
Anders Carlssonac2c9652009-03-28 06:42:02 +00004128 }
Mike Stump11289f42009-09-09 15:08:12 +00004129
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004130 NamespaceAliasDecl *AliasDecl =
Mike Stump11289f42009-09-09 15:08:12 +00004131 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
4132 Alias, SS.getRange(),
Douglas Gregor18231932009-05-30 06:48:27 +00004133 (NestedNameSpecifier *)SS.getScopeRep(),
John McCall9f3059a2009-10-09 21:13:30 +00004134 IdentLoc, R.getFoundDecl());
Mike Stump11289f42009-09-09 15:08:12 +00004135
John McCalld8d0d432010-02-16 06:53:13 +00004136 PushOnScopeChains(AliasDecl, S);
John McCall48871652010-08-21 09:40:31 +00004137 return AliasDecl;
Anders Carlsson9205d552009-03-28 05:27:17 +00004138}
4139
Douglas Gregora57478e2010-05-01 15:04:51 +00004140namespace {
4141 /// \brief Scoped object used to handle the state changes required in Sema
4142 /// to implicitly define the body of a C++ member function;
4143 class ImplicitlyDefinedFunctionScope {
4144 Sema &S;
4145 DeclContext *PreviousContext;
4146
4147 public:
4148 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
4149 : S(S), PreviousContext(S.CurContext)
4150 {
4151 S.CurContext = Method;
4152 S.PushFunctionScope();
4153 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
4154 }
4155
4156 ~ImplicitlyDefinedFunctionScope() {
4157 S.PopExpressionEvaluationContext();
4158 S.PopFunctionOrBlockScope();
4159 S.CurContext = PreviousContext;
4160 }
4161 };
4162}
4163
Sebastian Redlc15c3262010-09-13 22:02:47 +00004164static CXXConstructorDecl *getDefaultConstructorUnsafe(Sema &Self,
4165 CXXRecordDecl *D) {
4166 ASTContext &Context = Self.Context;
4167 QualType ClassType = Context.getTypeDeclType(D);
4168 DeclarationName ConstructorName
4169 = Context.DeclarationNames.getCXXConstructorName(
4170 Context.getCanonicalType(ClassType.getUnqualifiedType()));
4171
4172 DeclContext::lookup_const_iterator Con, ConEnd;
4173 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
4174 Con != ConEnd; ++Con) {
4175 // FIXME: In C++0x, a constructor template can be a default constructor.
4176 if (isa<FunctionTemplateDecl>(*Con))
4177 continue;
4178
4179 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
4180 if (Constructor->isDefaultConstructor())
4181 return Constructor;
4182 }
4183 return 0;
4184}
4185
Douglas Gregor0be31a22010-07-02 17:43:08 +00004186CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
4187 CXXRecordDecl *ClassDecl) {
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004188 // C++ [class.ctor]p5:
4189 // A default constructor for a class X is a constructor of class X
4190 // that can be called without an argument. If there is no
4191 // user-declared constructor for class X, a default constructor is
4192 // implicitly declared. An implicitly-declared default constructor
4193 // is an inline public member of its class.
Douglas Gregor9672f922010-07-03 00:47:00 +00004194 assert(!ClassDecl->hasUserDeclaredConstructor() &&
4195 "Should not build implicit default constructor!");
4196
Douglas Gregor6d880b12010-07-01 22:31:05 +00004197 // C++ [except.spec]p14:
4198 // An implicitly declared special member function (Clause 12) shall have an
4199 // exception-specification. [...]
4200 ImplicitExceptionSpecification ExceptSpec(Context);
4201
4202 // Direct base-class destructors.
4203 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4204 BEnd = ClassDecl->bases_end();
4205 B != BEnd; ++B) {
4206 if (B->isVirtual()) // Handled below.
4207 continue;
4208
Douglas Gregor9672f922010-07-03 00:47:00 +00004209 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4210 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4211 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4212 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
Sebastian Redlc15c3262010-09-13 22:02:47 +00004213 else if (CXXConstructorDecl *Constructor
4214 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004215 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004216 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004217 }
4218
4219 // Virtual base-class destructors.
4220 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4221 BEnd = ClassDecl->vbases_end();
4222 B != BEnd; ++B) {
Douglas Gregor9672f922010-07-03 00:47:00 +00004223 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
4224 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
4225 if (!BaseClassDecl->hasDeclaredDefaultConstructor())
4226 ExceptSpec.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl));
4227 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004228 = getDefaultConstructorUnsafe(*this, BaseClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004229 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004230 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004231 }
4232
4233 // Field destructors.
4234 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4235 FEnd = ClassDecl->field_end();
4236 F != FEnd; ++F) {
4237 if (const RecordType *RecordTy
Douglas Gregor9672f922010-07-03 00:47:00 +00004238 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
4239 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4240 if (!FieldClassDecl->hasDeclaredDefaultConstructor())
4241 ExceptSpec.CalledDecl(
4242 DeclareImplicitDefaultConstructor(FieldClassDecl));
4243 else if (CXXConstructorDecl *Constructor
Sebastian Redlc15c3262010-09-13 22:02:47 +00004244 = getDefaultConstructorUnsafe(*this, FieldClassDecl))
Douglas Gregor6d880b12010-07-01 22:31:05 +00004245 ExceptSpec.CalledDecl(Constructor);
Douglas Gregor9672f922010-07-03 00:47:00 +00004246 }
Douglas Gregor6d880b12010-07-01 22:31:05 +00004247 }
4248
4249
4250 // Create the actual constructor declaration.
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004251 CanQualType ClassType
4252 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4253 DeclarationName Name
4254 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004255 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004256 CXXConstructorDecl *DefaultCon
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004257 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004258 Context.getFunctionType(Context.VoidTy,
4259 0, 0, false, 0,
Douglas Gregor6d880b12010-07-01 22:31:05 +00004260 ExceptSpec.hasExceptionSpecification(),
4261 ExceptSpec.hasAnyExceptionSpecification(),
4262 ExceptSpec.size(),
4263 ExceptSpec.data(),
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004264 FunctionType::ExtInfo()),
4265 /*TInfo=*/0,
4266 /*isExplicit=*/false,
4267 /*isInline=*/true,
4268 /*isImplicitlyDeclared=*/true);
4269 DefaultCon->setAccess(AS_public);
4270 DefaultCon->setImplicit();
4271 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Douglas Gregor9672f922010-07-03 00:47:00 +00004272
4273 // Note that we have declared this constructor.
Douglas Gregor9672f922010-07-03 00:47:00 +00004274 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
4275
Douglas Gregor0be31a22010-07-02 17:43:08 +00004276 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor9672f922010-07-03 00:47:00 +00004277 PushOnScopeChains(DefaultCon, S, false);
4278 ClassDecl->addDecl(DefaultCon);
4279
Douglas Gregor4e8b5fb2010-07-01 22:02:46 +00004280 return DefaultCon;
4281}
4282
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004283void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
4284 CXXConstructorDecl *Constructor) {
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004285 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004286 !Constructor->isUsed(false)) &&
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00004287 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Mike Stump11289f42009-09-09 15:08:12 +00004288
Anders Carlsson423f5d82010-04-23 16:04:08 +00004289 CXXRecordDecl *ClassDecl = Constructor->getParent();
Eli Friedman9cf6b592009-11-09 19:20:36 +00004290 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Eli Friedmand7686ef2009-11-09 01:05:47 +00004291
Douglas Gregora57478e2010-05-01 15:04:51 +00004292 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00004293 ErrorTrap Trap(*this);
4294 if (SetBaseOrMemberInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
4295 Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004296 Diag(CurrentLocation, diag::note_member_synthesized_at)
Anders Carlsson05bf0092010-04-22 05:40:53 +00004297 << CXXConstructor << Context.getTagDeclType(ClassDecl);
Eli Friedman9cf6b592009-11-09 19:20:36 +00004298 Constructor->setInvalidDecl();
Douglas Gregor73193272010-09-20 16:48:21 +00004299 return;
Eli Friedman9cf6b592009-11-09 19:20:36 +00004300 }
Douglas Gregor73193272010-09-20 16:48:21 +00004301
4302 SourceLocation Loc = Constructor->getLocation();
4303 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4304
4305 Constructor->setUsed();
4306 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian423a81f2009-06-19 19:55:27 +00004307}
4308
Douglas Gregor0be31a22010-07-02 17:43:08 +00004309CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
Douglas Gregorf1203042010-07-01 19:09:28 +00004310 // C++ [class.dtor]p2:
4311 // If a class has no user-declared destructor, a destructor is
4312 // declared implicitly. An implicitly-declared destructor is an
4313 // inline public member of its class.
4314
4315 // C++ [except.spec]p14:
4316 // An implicitly declared special member function (Clause 12) shall have
4317 // an exception-specification.
4318 ImplicitExceptionSpecification ExceptSpec(Context);
4319
4320 // Direct base-class destructors.
4321 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
4322 BEnd = ClassDecl->bases_end();
4323 B != BEnd; ++B) {
4324 if (B->isVirtual()) // Handled below.
4325 continue;
4326
4327 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4328 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004329 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004330 }
4331
4332 // Virtual base-class destructors.
4333 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
4334 BEnd = ClassDecl->vbases_end();
4335 B != BEnd; ++B) {
4336 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
4337 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004338 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004339 }
4340
4341 // Field destructors.
4342 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
4343 FEnd = ClassDecl->field_end();
4344 F != FEnd; ++F) {
4345 if (const RecordType *RecordTy
4346 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
4347 ExceptSpec.CalledDecl(
Douglas Gregore71edda2010-07-01 22:47:18 +00004348 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
Douglas Gregorf1203042010-07-01 19:09:28 +00004349 }
4350
Douglas Gregor7454c562010-07-02 20:37:36 +00004351 // Create the actual destructor declaration.
Douglas Gregorf1203042010-07-01 19:09:28 +00004352 QualType Ty = Context.getFunctionType(Context.VoidTy,
4353 0, 0, false, 0,
4354 ExceptSpec.hasExceptionSpecification(),
4355 ExceptSpec.hasAnyExceptionSpecification(),
4356 ExceptSpec.size(),
4357 ExceptSpec.data(),
4358 FunctionType::ExtInfo());
4359
4360 CanQualType ClassType
4361 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4362 DeclarationName Name
4363 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004364 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf1203042010-07-01 19:09:28 +00004365 CXXDestructorDecl *Destructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004366 = CXXDestructorDecl::Create(Context, ClassDecl, NameInfo, Ty,
Douglas Gregorf1203042010-07-01 19:09:28 +00004367 /*isInline=*/true,
4368 /*isImplicitlyDeclared=*/true);
4369 Destructor->setAccess(AS_public);
4370 Destructor->setImplicit();
4371 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Douglas Gregor7454c562010-07-02 20:37:36 +00004372
4373 // Note that we have declared this destructor.
Douglas Gregor7454c562010-07-02 20:37:36 +00004374 ++ASTContext::NumImplicitDestructorsDeclared;
4375
4376 // Introduce this destructor into its scope.
Douglas Gregor0be31a22010-07-02 17:43:08 +00004377 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor7454c562010-07-02 20:37:36 +00004378 PushOnScopeChains(Destructor, S, false);
4379 ClassDecl->addDecl(Destructor);
Douglas Gregorf1203042010-07-01 19:09:28 +00004380
4381 // This could be uniqued if it ever proves significant.
4382 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
4383
4384 AddOverriddenMethods(ClassDecl, Destructor);
Douglas Gregor7454c562010-07-02 20:37:36 +00004385
Douglas Gregorf1203042010-07-01 19:09:28 +00004386 return Destructor;
4387}
4388
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004389void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
Douglas Gregord94105a2009-09-04 19:04:08 +00004390 CXXDestructorDecl *Destructor) {
Douglas Gregorebada0772010-06-17 23:14:26 +00004391 assert((Destructor->isImplicit() && !Destructor->isUsed(false)) &&
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004392 "DefineImplicitDestructor - call it for implicit default dtor");
Anders Carlsson2a50e952009-11-15 22:49:34 +00004393 CXXRecordDecl *ClassDecl = Destructor->getParent();
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004394 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004395
Douglas Gregor54818f02010-05-12 16:39:35 +00004396 if (Destructor->isInvalidDecl())
4397 return;
4398
Douglas Gregora57478e2010-05-01 15:04:51 +00004399 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004400
Douglas Gregor54818f02010-05-12 16:39:35 +00004401 ErrorTrap Trap(*this);
John McCalla6309952010-03-16 21:39:52 +00004402 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
4403 Destructor->getParent());
Mike Stump11289f42009-09-09 15:08:12 +00004404
Douglas Gregor54818f02010-05-12 16:39:35 +00004405 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
Anders Carlsson26a807d2009-11-30 21:24:50 +00004406 Diag(CurrentLocation, diag::note_member_synthesized_at)
4407 << CXXDestructor << Context.getTagDeclType(ClassDecl);
4408
4409 Destructor->setInvalidDecl();
4410 return;
4411 }
4412
Douglas Gregor73193272010-09-20 16:48:21 +00004413 SourceLocation Loc = Destructor->getLocation();
4414 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
4415
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004416 Destructor->setUsed();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004417 MarkVTableUsed(CurrentLocation, ClassDecl);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00004418}
4419
Douglas Gregorb139cd52010-05-01 20:49:11 +00004420/// \brief Builds a statement that copies the given entity from \p From to
4421/// \c To.
4422///
4423/// This routine is used to copy the members of a class with an
4424/// implicitly-declared copy assignment operator. When the entities being
4425/// copied are arrays, this routine builds for loops to copy them.
4426///
4427/// \param S The Sema object used for type-checking.
4428///
4429/// \param Loc The location where the implicit copy is being generated.
4430///
4431/// \param T The type of the expressions being copied. Both expressions must
4432/// have this type.
4433///
4434/// \param To The expression we are copying to.
4435///
4436/// \param From The expression we are copying from.
4437///
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004438/// \param CopyingBaseSubobject Whether we're copying a base subobject.
4439/// Otherwise, it's a non-static member subobject.
4440///
Douglas Gregorb139cd52010-05-01 20:49:11 +00004441/// \param Depth Internal parameter recording the depth of the recursion.
4442///
4443/// \returns A statement or a loop that copies the expressions.
John McCalldadc5752010-08-24 06:29:42 +00004444static StmtResult
Douglas Gregorb139cd52010-05-01 20:49:11 +00004445BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
John McCallb268a282010-08-23 23:25:46 +00004446 Expr *To, Expr *From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004447 bool CopyingBaseSubobject, unsigned Depth = 0) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00004448 // C++0x [class.copy]p30:
4449 // Each subobject is assigned in the manner appropriate to its type:
4450 //
4451 // - if the subobject is of class type, the copy assignment operator
4452 // for the class is used (as if by explicit qualification; that is,
4453 // ignoring any possible virtual overriding functions in more derived
4454 // classes);
4455 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
4456 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
4457
4458 // Look for operator=.
4459 DeclarationName Name
4460 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4461 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
4462 S.LookupQualifiedName(OpLookup, ClassDecl, false);
4463
4464 // Filter out any result that isn't a copy-assignment operator.
4465 LookupResult::Filter F = OpLookup.makeFilter();
4466 while (F.hasNext()) {
4467 NamedDecl *D = F.next();
4468 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
4469 if (Method->isCopyAssignmentOperator())
4470 continue;
4471
4472 F.erase();
John McCallab8c2732010-03-16 06:11:48 +00004473 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004474 F.done();
4475
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004476 // Suppress the protected check (C++ [class.protected]) for each of the
4477 // assignment operators we found. This strange dance is required when
4478 // we're assigning via a base classes's copy-assignment operator. To
4479 // ensure that we're getting the right base class subobject (without
4480 // ambiguities), we need to cast "this" to that subobject type; to
4481 // ensure that we don't go through the virtual call mechanism, we need
4482 // to qualify the operator= name with the base class (see below). However,
4483 // this means that if the base class has a protected copy assignment
4484 // operator, the protected member access check will fail. So, we
4485 // rewrite "protected" access to "public" access in this case, since we
4486 // know by construction that we're calling from a derived class.
4487 if (CopyingBaseSubobject) {
4488 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
4489 L != LEnd; ++L) {
4490 if (L.getAccess() == AS_protected)
4491 L.setAccess(AS_public);
4492 }
4493 }
4494
Douglas Gregorb139cd52010-05-01 20:49:11 +00004495 // Create the nested-name-specifier that will be used to qualify the
4496 // reference to operator=; this is required to suppress the virtual
4497 // call mechanism.
4498 CXXScopeSpec SS;
4499 SS.setRange(Loc);
4500 SS.setScopeRep(NestedNameSpecifier::Create(S.Context, 0, false,
4501 T.getTypePtr()));
4502
4503 // Create the reference to operator=.
John McCalldadc5752010-08-24 06:29:42 +00004504 ExprResult OpEqualRef
John McCallb268a282010-08-23 23:25:46 +00004505 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004506 /*FirstQualifierInScope=*/0, OpLookup,
4507 /*TemplateArgs=*/0,
4508 /*SuppressQualifierCheck=*/true);
4509 if (OpEqualRef.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004510 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004511
4512 // Build the call to the assignment operator.
John McCallb268a282010-08-23 23:25:46 +00004513
John McCalldadc5752010-08-24 06:29:42 +00004514 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
Douglas Gregorce5aa332010-09-09 16:33:13 +00004515 OpEqualRef.takeAs<Expr>(),
4516 Loc, &From, 1, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004517 if (Call.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004518 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004519
4520 return S.Owned(Call.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004521 }
John McCallab8c2732010-03-16 06:11:48 +00004522
Douglas Gregorb139cd52010-05-01 20:49:11 +00004523 // - if the subobject is of scalar type, the built-in assignment
4524 // operator is used.
4525 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
4526 if (!ArrayTy) {
John McCalle3027922010-08-25 11:45:40 +00004527 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004528 if (Assignment.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004529 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004530
4531 return S.Owned(Assignment.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004532 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004533
4534 // - if the subobject is an array, each element is assigned, in the
4535 // manner appropriate to the element type;
4536
4537 // Construct a loop over the array bounds, e.g.,
4538 //
4539 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4540 //
4541 // that will copy each of the array elements.
4542 QualType SizeType = S.Context.getSizeType();
4543
4544 // Create the iteration variable.
4545 IdentifierInfo *IterationVarName = 0;
4546 {
4547 llvm::SmallString<8> Str;
4548 llvm::raw_svector_ostream OS(Str);
4549 OS << "__i" << Depth;
4550 IterationVarName = &S.Context.Idents.get(OS.str());
4551 }
4552 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc,
4553 IterationVarName, SizeType,
4554 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
John McCall8e7d6562010-08-26 03:08:43 +00004555 SC_None, SC_None);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004556
4557 // Initialize the iteration variable to zero.
4558 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004559 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004560
4561 // Create a reference to the iteration variable; we'll use this several
4562 // times throughout.
4563 Expr *IterationVarRef
4564 = S.BuildDeclRefExpr(IterationVar, SizeType, Loc).takeAs<Expr>();
4565 assert(IterationVarRef && "Reference to invented variable cannot fail!");
4566
4567 // Create the DeclStmt that holds the iteration variable.
4568 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
4569
4570 // Create the comparison against the array bound.
4571 llvm::APInt Upper = ArrayTy->getSize();
4572 Upper.zextOrTrunc(S.Context.getTypeSize(SizeType));
John McCallb268a282010-08-23 23:25:46 +00004573 Expr *Comparison
4574 = new (S.Context) BinaryOperator(IterationVarRef->Retain(),
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00004575 IntegerLiteral::Create(S.Context,
4576 Upper, SizeType, Loc),
4577 BO_NE, S.Context.BoolTy, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004578
4579 // Create the pre-increment of the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004580 Expr *Increment
4581 = new (S.Context) UnaryOperator(IterationVarRef->Retain(),
John McCalle3027922010-08-25 11:45:40 +00004582 UO_PreInc,
John McCallb268a282010-08-23 23:25:46 +00004583 SizeType, Loc);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004584
4585 // Subscript the "from" and "to" expressions with the iteration variable.
John McCallb268a282010-08-23 23:25:46 +00004586 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
4587 IterationVarRef, Loc));
4588 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
4589 IterationVarRef, Loc));
Douglas Gregorb139cd52010-05-01 20:49:11 +00004590
4591 // Build the copy for an individual element of the array.
John McCalldadc5752010-08-24 06:29:42 +00004592 StmtResult Copy = BuildSingleCopyAssign(S, Loc,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004593 ArrayTy->getElementType(),
John McCallb268a282010-08-23 23:25:46 +00004594 To, From,
Douglas Gregor40c92bb2010-05-04 15:20:55 +00004595 CopyingBaseSubobject, Depth+1);
Douglas Gregorb412e172010-07-25 18:17:45 +00004596 if (Copy.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00004597 return StmtError();
Douglas Gregorb139cd52010-05-01 20:49:11 +00004598
4599 // Construct the loop that copies all elements of this array.
John McCallb268a282010-08-23 23:25:46 +00004600 return S.ActOnForStmt(Loc, Loc, InitStmt,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004601 S.MakeFullExpr(Comparison),
John McCall48871652010-08-21 09:40:31 +00004602 0, S.MakeFullExpr(Increment),
John McCallb268a282010-08-23 23:25:46 +00004603 Loc, Copy.take());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00004604}
4605
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004606/// \brief Determine whether the given class has a copy assignment operator
4607/// that accepts a const-qualified argument.
4608static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
4609 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
4610
4611 if (!Class->hasDeclaredCopyAssignment())
4612 S.DeclareImplicitCopyAssignment(Class);
4613
4614 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
4615 DeclarationName OpName
4616 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
4617
4618 DeclContext::lookup_const_iterator Op, OpEnd;
4619 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
4620 // C++ [class.copy]p9:
4621 // A user-declared copy assignment operator is a non-static non-template
4622 // member function of class X with exactly one parameter of type X, X&,
4623 // const X&, volatile X& or const volatile X&.
4624 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
4625 if (!Method)
4626 continue;
4627
4628 if (Method->isStatic())
4629 continue;
4630 if (Method->getPrimaryTemplate())
4631 continue;
4632 const FunctionProtoType *FnType =
4633 Method->getType()->getAs<FunctionProtoType>();
4634 assert(FnType && "Overloaded operator has no prototype.");
4635 // Don't assert on this; an invalid decl might have been left in the AST.
4636 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
4637 continue;
4638 bool AcceptsConst = true;
4639 QualType ArgType = FnType->getArgType(0);
4640 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
4641 ArgType = Ref->getPointeeType();
4642 // Is it a non-const lvalue reference?
4643 if (!ArgType.isConstQualified())
4644 AcceptsConst = false;
4645 }
4646 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
4647 continue;
4648
4649 // We have a single argument of type cv X or cv X&, i.e. we've found the
4650 // copy assignment operator. Return whether it accepts const arguments.
4651 return AcceptsConst;
4652 }
4653 assert(Class->isInvalidDecl() &&
4654 "No copy assignment operator declared in valid code.");
4655 return false;
4656}
4657
Douglas Gregor0be31a22010-07-02 17:43:08 +00004658CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004659 // Note: The following rules are largely analoguous to the copy
4660 // constructor rules. Note that virtual bases are not taken into account
4661 // for determining the argument type of the operator. Note also that
4662 // operators taking an object instead of a reference are allowed.
Douglas Gregor9672f922010-07-03 00:47:00 +00004663
4664
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004665 // C++ [class.copy]p10:
4666 // If the class definition does not explicitly declare a copy
4667 // assignment operator, one is declared implicitly.
4668 // The implicitly-defined copy assignment operator for a class X
4669 // will have the form
4670 //
4671 // X& X::operator=(const X&)
4672 //
4673 // if
4674 bool HasConstCopyAssignment = true;
4675
4676 // -- each direct base class B of X has a copy assignment operator
4677 // whose parameter is of type const B&, const volatile B& or B,
4678 // and
4679 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4680 BaseEnd = ClassDecl->bases_end();
4681 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
4682 assert(!Base->getType()->isDependentType() &&
4683 "Cannot generate implicit members for class with dependent bases.");
4684 const CXXRecordDecl *BaseClassDecl
4685 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004686 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004687 }
4688
4689 // -- for all the nonstatic data members of X that are of a class
4690 // type M (or array thereof), each such class type has a copy
4691 // assignment operator whose parameter is of type const M&,
4692 // const volatile M& or M.
4693 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4694 FieldEnd = ClassDecl->field_end();
4695 HasConstCopyAssignment && Field != FieldEnd;
4696 ++Field) {
4697 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4698 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
4699 const CXXRecordDecl *FieldClassDecl
4700 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004701 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004702 }
4703 }
4704
4705 // Otherwise, the implicitly declared copy assignment operator will
4706 // have the form
4707 //
4708 // X& X::operator=(X&)
4709 QualType ArgType = Context.getTypeDeclType(ClassDecl);
4710 QualType RetType = Context.getLValueReferenceType(ArgType);
4711 if (HasConstCopyAssignment)
4712 ArgType = ArgType.withConst();
4713 ArgType = Context.getLValueReferenceType(ArgType);
4714
Douglas Gregor68e11362010-07-01 17:48:08 +00004715 // C++ [except.spec]p14:
4716 // An implicitly declared special member function (Clause 12) shall have an
4717 // exception-specification. [...]
4718 ImplicitExceptionSpecification ExceptSpec(Context);
4719 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4720 BaseEnd = ClassDecl->bases_end();
4721 Base != BaseEnd; ++Base) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004722 CXXRecordDecl *BaseClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004723 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004724
4725 if (!BaseClassDecl->hasDeclaredCopyAssignment())
4726 DeclareImplicitCopyAssignment(BaseClassDecl);
4727
Douglas Gregor68e11362010-07-01 17:48:08 +00004728 if (CXXMethodDecl *CopyAssign
4729 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4730 ExceptSpec.CalledDecl(CopyAssign);
4731 }
4732 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4733 FieldEnd = ClassDecl->field_end();
4734 Field != FieldEnd;
4735 ++Field) {
4736 QualType FieldType = Context.getBaseElementType((*Field)->getType());
4737 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004738 CXXRecordDecl *FieldClassDecl
Douglas Gregor68e11362010-07-01 17:48:08 +00004739 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004740
4741 if (!FieldClassDecl->hasDeclaredCopyAssignment())
4742 DeclareImplicitCopyAssignment(FieldClassDecl);
4743
Douglas Gregor68e11362010-07-01 17:48:08 +00004744 if (CXXMethodDecl *CopyAssign
4745 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
4746 ExceptSpec.CalledDecl(CopyAssign);
4747 }
4748 }
4749
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004750 // An implicitly-declared copy assignment operator is an inline public
4751 // member of its class.
4752 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004753 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004754 CXXMethodDecl *CopyAssignment
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00004755 = CXXMethodDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004756 Context.getFunctionType(RetType, &ArgType, 1,
4757 false, 0,
Douglas Gregor68e11362010-07-01 17:48:08 +00004758 ExceptSpec.hasExceptionSpecification(),
4759 ExceptSpec.hasAnyExceptionSpecification(),
4760 ExceptSpec.size(),
4761 ExceptSpec.data(),
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004762 FunctionType::ExtInfo()),
4763 /*TInfo=*/0, /*isStatic=*/false,
John McCall8e7d6562010-08-26 03:08:43 +00004764 /*StorageClassAsWritten=*/SC_None,
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004765 /*isInline=*/true);
4766 CopyAssignment->setAccess(AS_public);
4767 CopyAssignment->setImplicit();
4768 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004769
4770 // Add the parameter to the operator.
4771 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
4772 ClassDecl->getLocation(),
4773 /*Id=*/0,
4774 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00004775 SC_None,
4776 SC_None, 0);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004777 CopyAssignment->setParams(&FromParam, 1);
4778
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004779 // Note that we have added this copy-assignment operator.
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004780 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
4781
Douglas Gregor0be31a22010-07-02 17:43:08 +00004782 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregor330b9cf2010-07-02 21:50:04 +00004783 PushOnScopeChains(CopyAssignment, S, false);
4784 ClassDecl->addDecl(CopyAssignment);
Douglas Gregorf56ab7b2010-07-01 16:36:15 +00004785
4786 AddOverriddenMethods(ClassDecl, CopyAssignment);
4787 return CopyAssignment;
4788}
4789
Douglas Gregorb139cd52010-05-01 20:49:11 +00004790void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
4791 CXXMethodDecl *CopyAssignOperator) {
4792 assert((CopyAssignOperator->isImplicit() &&
4793 CopyAssignOperator->isOverloadedOperator() &&
4794 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
Douglas Gregorebada0772010-06-17 23:14:26 +00004795 !CopyAssignOperator->isUsed(false)) &&
Douglas Gregorb139cd52010-05-01 20:49:11 +00004796 "DefineImplicitCopyAssignment called for wrong function");
4797
4798 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
4799
4800 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
4801 CopyAssignOperator->setInvalidDecl();
4802 return;
4803 }
4804
4805 CopyAssignOperator->setUsed();
4806
4807 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
Douglas Gregor54818f02010-05-12 16:39:35 +00004808 ErrorTrap Trap(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004809
4810 // C++0x [class.copy]p30:
4811 // The implicitly-defined or explicitly-defaulted copy assignment operator
4812 // for a non-union class X performs memberwise copy assignment of its
4813 // subobjects. The direct base classes of X are assigned first, in the
4814 // order of their declaration in the base-specifier-list, and then the
4815 // immediate non-static data members of X are assigned, in the order in
4816 // which they were declared in the class definition.
4817
4818 // The statements that form the synthesized function body.
John McCall37ad5512010-08-23 06:44:23 +00004819 ASTOwningVector<Stmt*> Statements(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004820
4821 // The parameter for the "other" object, which we are copying from.
4822 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
4823 Qualifiers OtherQuals = Other->getType().getQualifiers();
4824 QualType OtherRefType = Other->getType();
4825 if (const LValueReferenceType *OtherRef
4826 = OtherRefType->getAs<LValueReferenceType>()) {
4827 OtherRefType = OtherRef->getPointeeType();
4828 OtherQuals = OtherRefType.getQualifiers();
4829 }
4830
4831 // Our location for everything implicitly-generated.
4832 SourceLocation Loc = CopyAssignOperator->getLocation();
4833
4834 // Construct a reference to the "other" object. We'll be using this
4835 // throughout the generated ASTs.
4836 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, Loc).takeAs<Expr>();
4837 assert(OtherRef && "Reference to parameter cannot fail!");
4838
4839 // Construct the "this" pointer. We'll be using this throughout the generated
4840 // ASTs.
4841 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
4842 assert(This && "Reference to this cannot fail!");
4843
4844 // Assign base classes.
4845 bool Invalid = false;
4846 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
4847 E = ClassDecl->bases_end(); Base != E; ++Base) {
4848 // Form the assignment:
4849 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
4850 QualType BaseType = Base->getType().getUnqualifiedType();
4851 CXXRecordDecl *BaseClassDecl = 0;
4852 if (const RecordType *BaseRecordT = BaseType->getAs<RecordType>())
4853 BaseClassDecl = cast<CXXRecordDecl>(BaseRecordT->getDecl());
4854 else {
4855 Invalid = true;
4856 continue;
4857 }
4858
John McCallcf142162010-08-07 06:22:56 +00004859 CXXCastPath BasePath;
4860 BasePath.push_back(Base);
4861
Douglas Gregorb139cd52010-05-01 20:49:11 +00004862 // Construct the "from" expression, which is an implicit cast to the
4863 // appropriately-qualified base type.
4864 Expr *From = OtherRef->Retain();
4865 ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
John McCall2536c6d2010-08-25 10:28:54 +00004866 CK_UncheckedDerivedToBase,
4867 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004868
4869 // Dereference "this".
John McCall2536c6d2010-08-25 10:28:54 +00004870 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004871
4872 // Implicitly cast "this" to the appropriately-qualified base type.
4873 Expr *ToE = To.takeAs<Expr>();
4874 ImpCastExprToType(ToE,
4875 Context.getCVRQualifiedType(BaseType,
4876 CopyAssignOperator->getTypeQualifiers()),
John McCall2536c6d2010-08-25 10:28:54 +00004877 CK_UncheckedDerivedToBase,
4878 VK_LValue, &BasePath);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004879 To = Owned(ToE);
4880
4881 // Build the copy.
John McCalldadc5752010-08-24 06:29:42 +00004882 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
John McCall2536c6d2010-08-25 10:28:54 +00004883 To.get(), From,
4884 /*CopyingBaseSubobject=*/true);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004885 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004886 Diag(CurrentLocation, diag::note_member_synthesized_at)
4887 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
4888 CopyAssignOperator->setInvalidDecl();
4889 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004890 }
4891
4892 // Success! Record the copy.
4893 Statements.push_back(Copy.takeAs<Expr>());
4894 }
4895
4896 // \brief Reference to the __builtin_memcpy function.
4897 Expr *BuiltinMemCpyRef = 0;
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004898 // \brief Reference to the __builtin_objc_memmove_collectable function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004899 Expr *CollectableMemCpyRef = 0;
Douglas Gregorb139cd52010-05-01 20:49:11 +00004900
4901 // Assign non-static members.
4902 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
4903 FieldEnd = ClassDecl->field_end();
4904 Field != FieldEnd; ++Field) {
4905 // Check for members of reference type; we can't copy those.
4906 if (Field->getType()->isReferenceType()) {
4907 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4908 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
4909 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004910 Diag(CurrentLocation, diag::note_member_synthesized_at)
4911 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004912 Invalid = true;
4913 continue;
4914 }
4915
4916 // Check for members of const-qualified, non-class type.
4917 QualType BaseType = Context.getBaseElementType(Field->getType());
4918 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
4919 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
4920 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
4921 Diag(Field->getLocation(), diag::note_declared_at);
Douglas Gregorbf1fb442010-05-05 22:38:15 +00004922 Diag(CurrentLocation, diag::note_member_synthesized_at)
4923 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
Douglas Gregorb139cd52010-05-01 20:49:11 +00004924 Invalid = true;
4925 continue;
4926 }
4927
4928 QualType FieldType = Field->getType().getNonReferenceType();
Fariborz Jahanian1138ba62010-05-26 20:19:07 +00004929 if (FieldType->isIncompleteArrayType()) {
4930 assert(ClassDecl->hasFlexibleArrayMember() &&
4931 "Incomplete array type is not valid");
4932 continue;
4933 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00004934
4935 // Build references to the field in the object we're copying from and to.
4936 CXXScopeSpec SS; // Intentionally empty
4937 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
4938 LookupMemberName);
4939 MemberLookup.addDecl(*Field);
4940 MemberLookup.resolveKind();
John McCalldadc5752010-08-24 06:29:42 +00004941 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
Douglas Gregorb139cd52010-05-01 20:49:11 +00004942 Loc, /*IsArrow=*/false,
4943 SS, 0, MemberLookup, 0);
John McCalldadc5752010-08-24 06:29:42 +00004944 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
Douglas Gregorb139cd52010-05-01 20:49:11 +00004945 Loc, /*IsArrow=*/true,
4946 SS, 0, MemberLookup, 0);
4947 assert(!From.isInvalid() && "Implicit field reference cannot fail");
4948 assert(!To.isInvalid() && "Implicit field reference cannot fail");
4949
4950 // If the field should be copied with __builtin_memcpy rather than via
4951 // explicit assignments, do so. This optimization only applies for arrays
4952 // of scalars and arrays of class type with trivial copy-assignment
4953 // operators.
4954 if (FieldType->isArrayType() &&
4955 (!BaseType->isRecordType() ||
4956 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
4957 ->hasTrivialCopyAssignment())) {
4958 // Compute the size of the memory buffer to be copied.
4959 QualType SizeType = Context.getSizeType();
4960 llvm::APInt Size(Context.getTypeSize(SizeType),
4961 Context.getTypeSizeInChars(BaseType).getQuantity());
4962 for (const ConstantArrayType *Array
4963 = Context.getAsConstantArrayType(FieldType);
4964 Array;
4965 Array = Context.getAsConstantArrayType(Array->getElementType())) {
4966 llvm::APInt ArraySize = Array->getSize();
4967 ArraySize.zextOrTrunc(Size.getBitWidth());
4968 Size *= ArraySize;
4969 }
4970
4971 // Take the address of the field references for "from" and "to".
John McCalle3027922010-08-25 11:45:40 +00004972 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
4973 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004974
4975 bool NeedsCollectableMemCpy =
4976 (BaseType->isRecordType() &&
4977 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
4978
4979 if (NeedsCollectableMemCpy) {
4980 if (!CollectableMemCpyRef) {
Fariborz Jahanian4a303072010-06-16 16:22:04 +00004981 // Create a reference to the __builtin_objc_memmove_collectable function.
4982 LookupResult R(*this,
4983 &Context.Idents.get("__builtin_objc_memmove_collectable"),
Fariborz Jahanian021510e2010-06-15 22:44:06 +00004984 Loc, LookupOrdinaryName);
4985 LookupName(R, TUScope, true);
4986
4987 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
4988 if (!CollectableMemCpy) {
4989 // Something went horribly wrong earlier, and we will have
4990 // complained about it.
4991 Invalid = true;
4992 continue;
4993 }
4994
4995 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
4996 CollectableMemCpy->getType(),
4997 Loc, 0).takeAs<Expr>();
4998 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
4999 }
5000 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005001 // Create a reference to the __builtin_memcpy builtin function.
Fariborz Jahanian021510e2010-06-15 22:44:06 +00005002 else if (!BuiltinMemCpyRef) {
Douglas Gregorb139cd52010-05-01 20:49:11 +00005003 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
5004 LookupOrdinaryName);
5005 LookupName(R, TUScope, true);
5006
5007 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
5008 if (!BuiltinMemCpy) {
5009 // Something went horribly wrong earlier, and we will have complained
5010 // about it.
5011 Invalid = true;
5012 continue;
5013 }
5014
5015 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
5016 BuiltinMemCpy->getType(),
5017 Loc, 0).takeAs<Expr>();
5018 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
5019 }
5020
John McCall37ad5512010-08-23 06:44:23 +00005021 ASTOwningVector<Expr*> CallArgs(*this);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005022 CallArgs.push_back(To.takeAs<Expr>());
5023 CallArgs.push_back(From.takeAs<Expr>());
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00005024 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
John McCalldadc5752010-08-24 06:29:42 +00005025 ExprResult Call = ExprError();
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005026 if (NeedsCollectableMemCpy)
5027 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005028 CollectableMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005029 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005030 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005031 else
5032 Call = ActOnCallExpr(/*Scope=*/0,
John McCallb268a282010-08-23 23:25:46 +00005033 BuiltinMemCpyRef,
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005034 Loc, move_arg(CallArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00005035 Loc);
Fariborz Jahanian00bdca52010-06-16 00:16:38 +00005036
Douglas Gregorb139cd52010-05-01 20:49:11 +00005037 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5038 Statements.push_back(Call.takeAs<Expr>());
5039 continue;
5040 }
5041
5042 // Build the copy of this field.
John McCalldadc5752010-08-24 06:29:42 +00005043 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
John McCallb268a282010-08-23 23:25:46 +00005044 To.get(), From.get(),
Douglas Gregor40c92bb2010-05-04 15:20:55 +00005045 /*CopyingBaseSubobject=*/false);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005046 if (Copy.isInvalid()) {
Douglas Gregorbf1fb442010-05-05 22:38:15 +00005047 Diag(CurrentLocation, diag::note_member_synthesized_at)
5048 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5049 CopyAssignOperator->setInvalidDecl();
5050 return;
Douglas Gregorb139cd52010-05-01 20:49:11 +00005051 }
5052
5053 // Success! Record the copy.
5054 Statements.push_back(Copy.takeAs<Stmt>());
5055 }
5056
5057 if (!Invalid) {
5058 // Add a "return *this;"
John McCalle3027922010-08-25 11:45:40 +00005059 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
Douglas Gregorb139cd52010-05-01 20:49:11 +00005060
John McCalldadc5752010-08-24 06:29:42 +00005061 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
Douglas Gregorb139cd52010-05-01 20:49:11 +00005062 if (Return.isInvalid())
5063 Invalid = true;
5064 else {
5065 Statements.push_back(Return.takeAs<Stmt>());
Douglas Gregor54818f02010-05-12 16:39:35 +00005066
5067 if (Trap.hasErrorOccurred()) {
5068 Diag(CurrentLocation, diag::note_member_synthesized_at)
5069 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
5070 Invalid = true;
5071 }
Douglas Gregorb139cd52010-05-01 20:49:11 +00005072 }
5073 }
5074
5075 if (Invalid) {
5076 CopyAssignOperator->setInvalidDecl();
5077 return;
5078 }
5079
John McCalldadc5752010-08-24 06:29:42 +00005080 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
Douglas Gregorb139cd52010-05-01 20:49:11 +00005081 /*isStmtExpr=*/false);
5082 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
5083 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00005084}
5085
Douglas Gregor0be31a22010-07-02 17:43:08 +00005086CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
5087 CXXRecordDecl *ClassDecl) {
Douglas Gregor54be3392010-07-01 17:57:27 +00005088 // C++ [class.copy]p4:
5089 // If the class definition does not explicitly declare a copy
5090 // constructor, one is declared implicitly.
5091
Douglas Gregor54be3392010-07-01 17:57:27 +00005092 // C++ [class.copy]p5:
5093 // The implicitly-declared copy constructor for a class X will
5094 // have the form
5095 //
5096 // X::X(const X&)
5097 //
5098 // if
5099 bool HasConstCopyConstructor = true;
5100
5101 // -- each direct or virtual base class B of X has a copy
5102 // constructor whose first parameter is of type const B& or
5103 // const volatile B&, and
5104 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5105 BaseEnd = ClassDecl->bases_end();
5106 HasConstCopyConstructor && Base != BaseEnd;
5107 ++Base) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005108 // Virtual bases are handled below.
5109 if (Base->isVirtual())
5110 continue;
5111
Douglas Gregora6d69502010-07-02 23:41:54 +00005112 CXXRecordDecl *BaseClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005113 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005114 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5115 DeclareImplicitCopyConstructor(BaseClassDecl);
5116
Douglas Gregorcfe68222010-07-01 18:27:03 +00005117 HasConstCopyConstructor
5118 = BaseClassDecl->hasConstCopyConstructor(Context);
5119 }
5120
5121 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5122 BaseEnd = ClassDecl->vbases_end();
5123 HasConstCopyConstructor && Base != BaseEnd;
5124 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005125 CXXRecordDecl *BaseClassDecl
Douglas Gregor54be3392010-07-01 17:57:27 +00005126 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005127 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5128 DeclareImplicitCopyConstructor(BaseClassDecl);
5129
Douglas Gregor54be3392010-07-01 17:57:27 +00005130 HasConstCopyConstructor
5131 = BaseClassDecl->hasConstCopyConstructor(Context);
5132 }
5133
5134 // -- for all the nonstatic data members of X that are of a
5135 // class type M (or array thereof), each such class type
5136 // has a copy constructor whose first parameter is of type
5137 // const M& or const volatile M&.
5138 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5139 FieldEnd = ClassDecl->field_end();
5140 HasConstCopyConstructor && Field != FieldEnd;
5141 ++Field) {
Douglas Gregorcfe68222010-07-01 18:27:03 +00005142 QualType FieldType = Context.getBaseElementType((*Field)->getType());
Douglas Gregor54be3392010-07-01 17:57:27 +00005143 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005144 CXXRecordDecl *FieldClassDecl
Douglas Gregorcfe68222010-07-01 18:27:03 +00005145 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005146 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5147 DeclareImplicitCopyConstructor(FieldClassDecl);
5148
Douglas Gregor54be3392010-07-01 17:57:27 +00005149 HasConstCopyConstructor
Douglas Gregorcfe68222010-07-01 18:27:03 +00005150 = FieldClassDecl->hasConstCopyConstructor(Context);
Douglas Gregor54be3392010-07-01 17:57:27 +00005151 }
5152 }
5153
5154 // Otherwise, the implicitly declared copy constructor will have
5155 // the form
5156 //
5157 // X::X(X&)
5158 QualType ClassType = Context.getTypeDeclType(ClassDecl);
5159 QualType ArgType = ClassType;
5160 if (HasConstCopyConstructor)
5161 ArgType = ArgType.withConst();
5162 ArgType = Context.getLValueReferenceType(ArgType);
5163
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005164 // C++ [except.spec]p14:
5165 // An implicitly declared special member function (Clause 12) shall have an
5166 // exception-specification. [...]
5167 ImplicitExceptionSpecification ExceptSpec(Context);
5168 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
5169 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
5170 BaseEnd = ClassDecl->bases_end();
5171 Base != BaseEnd;
5172 ++Base) {
5173 // Virtual bases are handled below.
5174 if (Base->isVirtual())
5175 continue;
5176
Douglas Gregora6d69502010-07-02 23:41:54 +00005177 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005178 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005179 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5180 DeclareImplicitCopyConstructor(BaseClassDecl);
5181
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005182 if (CXXConstructorDecl *CopyConstructor
5183 = BaseClassDecl->getCopyConstructor(Context, Quals))
5184 ExceptSpec.CalledDecl(CopyConstructor);
5185 }
5186 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
5187 BaseEnd = ClassDecl->vbases_end();
5188 Base != BaseEnd;
5189 ++Base) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005190 CXXRecordDecl *BaseClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005191 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005192 if (!BaseClassDecl->hasDeclaredCopyConstructor())
5193 DeclareImplicitCopyConstructor(BaseClassDecl);
5194
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005195 if (CXXConstructorDecl *CopyConstructor
5196 = BaseClassDecl->getCopyConstructor(Context, Quals))
5197 ExceptSpec.CalledDecl(CopyConstructor);
5198 }
5199 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
5200 FieldEnd = ClassDecl->field_end();
5201 Field != FieldEnd;
5202 ++Field) {
5203 QualType FieldType = Context.getBaseElementType((*Field)->getType());
5204 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregora6d69502010-07-02 23:41:54 +00005205 CXXRecordDecl *FieldClassDecl
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005206 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Douglas Gregora6d69502010-07-02 23:41:54 +00005207 if (!FieldClassDecl->hasDeclaredCopyConstructor())
5208 DeclareImplicitCopyConstructor(FieldClassDecl);
5209
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005210 if (CXXConstructorDecl *CopyConstructor
5211 = FieldClassDecl->getCopyConstructor(Context, Quals))
5212 ExceptSpec.CalledDecl(CopyConstructor);
5213 }
5214 }
5215
Douglas Gregor54be3392010-07-01 17:57:27 +00005216 // An implicitly-declared copy constructor is an inline public
5217 // member of its class.
5218 DeclarationName Name
5219 = Context.DeclarationNames.getCXXConstructorName(
5220 Context.getCanonicalType(ClassType));
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005221 DeclarationNameInfo NameInfo(Name, ClassDecl->getLocation());
Douglas Gregor54be3392010-07-01 17:57:27 +00005222 CXXConstructorDecl *CopyConstructor
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00005223 = CXXConstructorDecl::Create(Context, ClassDecl, NameInfo,
Douglas Gregor54be3392010-07-01 17:57:27 +00005224 Context.getFunctionType(Context.VoidTy,
5225 &ArgType, 1,
5226 false, 0,
Douglas Gregor8453ddb2010-07-01 20:59:04 +00005227 ExceptSpec.hasExceptionSpecification(),
5228 ExceptSpec.hasAnyExceptionSpecification(),
5229 ExceptSpec.size(),
5230 ExceptSpec.data(),
Douglas Gregor54be3392010-07-01 17:57:27 +00005231 FunctionType::ExtInfo()),
5232 /*TInfo=*/0,
5233 /*isExplicit=*/false,
5234 /*isInline=*/true,
5235 /*isImplicitlyDeclared=*/true);
5236 CopyConstructor->setAccess(AS_public);
5237 CopyConstructor->setImplicit();
5238 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
5239
Douglas Gregora6d69502010-07-02 23:41:54 +00005240 // Note that we have declared this constructor.
Douglas Gregora6d69502010-07-02 23:41:54 +00005241 ++ASTContext::NumImplicitCopyConstructorsDeclared;
5242
Douglas Gregor54be3392010-07-01 17:57:27 +00005243 // Add the parameter to the constructor.
5244 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
5245 ClassDecl->getLocation(),
5246 /*IdentifierInfo=*/0,
5247 ArgType, /*TInfo=*/0,
John McCall8e7d6562010-08-26 03:08:43 +00005248 SC_None,
5249 SC_None, 0);
Douglas Gregor54be3392010-07-01 17:57:27 +00005250 CopyConstructor->setParams(&FromParam, 1);
Douglas Gregor0be31a22010-07-02 17:43:08 +00005251 if (Scope *S = getScopeForContext(ClassDecl))
Douglas Gregora6d69502010-07-02 23:41:54 +00005252 PushOnScopeChains(CopyConstructor, S, false);
5253 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor54be3392010-07-01 17:57:27 +00005254
5255 return CopyConstructor;
5256}
5257
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005258void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
5259 CXXConstructorDecl *CopyConstructor,
5260 unsigned TypeQuals) {
Mike Stump11289f42009-09-09 15:08:12 +00005261 assert((CopyConstructor->isImplicit() &&
Douglas Gregor507eb872009-12-22 00:34:07 +00005262 CopyConstructor->isCopyConstructor(TypeQuals) &&
Douglas Gregorebada0772010-06-17 23:14:26 +00005263 !CopyConstructor->isUsed(false)) &&
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005264 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
Mike Stump11289f42009-09-09 15:08:12 +00005265
Anders Carlsson7a0ffdb2010-04-23 16:24:12 +00005266 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005267 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005268
Douglas Gregora57478e2010-05-01 15:04:51 +00005269 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
Douglas Gregor54818f02010-05-12 16:39:35 +00005270 ErrorTrap Trap(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005271
Douglas Gregor54818f02010-05-12 16:39:35 +00005272 if (SetBaseOrMemberInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
5273 Trap.hasErrorOccurred()) {
Anders Carlsson79111502010-05-01 16:39:01 +00005274 Diag(CurrentLocation, diag::note_member_synthesized_at)
Douglas Gregor94f9a482010-05-05 05:51:00 +00005275 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
Anders Carlsson79111502010-05-01 16:39:01 +00005276 CopyConstructor->setInvalidDecl();
Douglas Gregor94f9a482010-05-05 05:51:00 +00005277 } else {
5278 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
5279 CopyConstructor->getLocation(),
5280 MultiStmtArg(*this, 0, 0),
5281 /*isStmtExpr=*/false)
5282 .takeAs<Stmt>());
Anders Carlsson53e1ba92010-04-25 00:52:09 +00005283 }
Douglas Gregor94f9a482010-05-05 05:51:00 +00005284
5285 CopyConstructor->setUsed();
Fariborz Jahanian477d2422009-06-22 23:34:40 +00005286}
5287
John McCalldadc5752010-08-24 06:29:42 +00005288ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005289Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
Mike Stump11289f42009-09-09 15:08:12 +00005290 CXXConstructorDecl *Constructor,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005291 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005292 bool RequiresZeroInit,
John McCallbfd822c2010-08-24 07:32:53 +00005293 unsigned ConstructKind) {
Anders Carlsson250aada2009-08-16 05:13:48 +00005294 bool Elidable = false;
Mike Stump11289f42009-09-09 15:08:12 +00005295
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005296 // C++0x [class.copy]p34:
5297 // When certain criteria are met, an implementation is allowed to
5298 // omit the copy/move construction of a class object, even if the
5299 // copy/move constructor and/or destructor for the object have
5300 // side effects. [...]
5301 // - when a temporary class object that has not been bound to a
5302 // reference (12.2) would be copied/moved to a class object
5303 // with the same cv-unqualified type, the copy/move operation
5304 // can be omitted by constructing the temporary object
5305 // directly into the target of the omitted copy/move
John McCall7a626f62010-09-15 10:14:12 +00005306 if (ConstructKind == CXXConstructExpr::CK_Complete &&
5307 Constructor->isCopyConstructor() && ExprArgs.size() >= 1) {
Douglas Gregor45cf7e32010-04-02 18:24:57 +00005308 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
John McCall7a626f62010-09-15 10:14:12 +00005309 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
Anders Carlsson250aada2009-08-16 05:13:48 +00005310 }
Mike Stump11289f42009-09-09 15:08:12 +00005311
5312 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005313 Elidable, move(ExprArgs), RequiresZeroInit,
Anders Carlssonbcc066b2010-05-02 22:54:08 +00005314 ConstructKind);
Anders Carlsson250aada2009-08-16 05:13:48 +00005315}
5316
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005317/// BuildCXXConstructExpr - Creates a complete call to a constructor,
5318/// including handling of its default argument expressions.
John McCalldadc5752010-08-24 06:29:42 +00005319ExprResult
Anders Carlsson1b4ebfa2009-09-05 07:40:38 +00005320Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5321 CXXConstructorDecl *Constructor, bool Elidable,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005322 MultiExprArg ExprArgs,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00005323 bool RequiresZeroInit,
John McCallbfd822c2010-08-24 07:32:53 +00005324 unsigned ConstructKind) {
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005325 unsigned NumExprs = ExprArgs.size();
5326 Expr **Exprs = (Expr **)ExprArgs.release();
Mike Stump11289f42009-09-09 15:08:12 +00005327
Douglas Gregor27381f32009-11-23 12:27:39 +00005328 MarkDeclarationReferenced(ConstructLoc, Constructor);
Douglas Gregor85dabae2009-12-16 01:38:02 +00005329 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
Douglas Gregor4f4b1862009-12-16 18:50:27 +00005330 Constructor, Elidable, Exprs, NumExprs,
John McCallbfd822c2010-08-24 07:32:53 +00005331 RequiresZeroInit,
5332 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind)));
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005333}
5334
Mike Stump11289f42009-09-09 15:08:12 +00005335bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianaa890bf2009-08-05 17:03:54 +00005336 CXXConstructorDecl *Constructor,
Anders Carlsson5995a3e2009-09-07 22:23:31 +00005337 MultiExprArg Exprs) {
John McCalldadc5752010-08-24 06:29:42 +00005338 ExprResult TempResult =
Fariborz Jahanian57277c52009-10-28 18:41:06 +00005339 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
John McCallbfd822c2010-08-24 07:32:53 +00005340 move(Exprs), false, CXXConstructExpr::CK_Complete);
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005341 if (TempResult.isInvalid())
5342 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005343
Anders Carlsson6eb55572009-08-25 05:12:04 +00005344 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregor77b50e12009-06-22 23:06:13 +00005345 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Anders Carlsson6e997b22009-12-15 20:51:39 +00005346 Temp = MaybeCreateCXXExprWithTemporaries(Temp);
Douglas Gregord5058122010-02-11 01:19:42 +00005347 VD->setInit(Temp);
Mike Stump11289f42009-09-09 15:08:12 +00005348
Anders Carlssonc1eb79b2009-08-25 05:18:00 +00005349 return false;
Anders Carlssone6840d82009-04-16 23:50:50 +00005350}
5351
John McCall03c48482010-02-02 09:10:11 +00005352void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
5353 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
Douglas Gregor422f1552010-02-25 18:11:54 +00005354 if (!ClassDecl->isInvalidDecl() && !VD->isInvalidDecl() &&
Douglas Gregor024d80e2010-05-22 17:12:29 +00005355 !ClassDecl->hasTrivialDestructor() && !ClassDecl->isDependentContext()) {
Douglas Gregore71edda2010-07-01 22:47:18 +00005356 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
John McCall6781b052010-02-02 08:45:54 +00005357 MarkDeclarationReferenced(VD->getLocation(), Destructor);
John McCall1064d7e2010-03-16 05:22:47 +00005358 CheckDestructorAccess(VD->getLocation(), Destructor,
Douglas Gregor89336232010-03-29 23:34:08 +00005359 PDiag(diag::err_access_dtor_var)
John McCall1064d7e2010-03-16 05:22:47 +00005360 << VD->getDeclName()
5361 << VD->getType());
John McCall47e40932010-08-01 20:20:59 +00005362
John McCall386dfc72010-09-18 05:25:11 +00005363 // TODO: this should be re-enabled for static locals by !CXAAtExit
5364 if (!VD->isInvalidDecl() && VD->hasGlobalStorage() && !VD->isStaticLocal())
John McCall47e40932010-08-01 20:20:59 +00005365 Diag(VD->getLocation(), diag::warn_global_destructor);
John McCall6781b052010-02-02 08:45:54 +00005366 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00005367}
5368
Mike Stump11289f42009-09-09 15:08:12 +00005369/// AddCXXDirectInitializerToDecl - This action is called immediately after
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005370/// ActOnDeclarator, when a C++ direct initializer is present.
5371/// e.g: "int x(1);"
John McCall48871652010-08-21 09:40:31 +00005372void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
Chris Lattner83f095c2009-03-28 19:18:32 +00005373 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005374 MultiExprArg Exprs,
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005375 SourceLocation RParenLoc) {
Daniel Dunbar2db411f2009-12-24 19:19:26 +00005376 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005377
5378 // If there is no declaration, there was an error parsing it. Just ignore
5379 // the initializer.
Chris Lattner83f095c2009-03-28 19:18:32 +00005380 if (RealDecl == 0)
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005381 return;
Mike Stump11289f42009-09-09 15:08:12 +00005382
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005383 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
5384 if (!VDecl) {
5385 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
5386 RealDecl->setInvalidDecl();
5387 return;
5388 }
5389
Douglas Gregor402250f2009-08-26 21:14:46 +00005390 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005391 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005392 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5393 //
5394 // Clients that want to distinguish between the two forms, can check for
5395 // direct initializer using VarDecl::hasCXXDirectInitializer().
5396 // A major benefit is that clients that don't particularly care about which
5397 // exactly form was it (like the CodeGen) can handle both cases without
5398 // special case code.
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005399
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005400 // C++ 8.5p11:
5401 // The form of initialization (using parentheses or '=') is generally
5402 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005403 // class type.
5404
Douglas Gregor50dc2192010-02-11 22:55:30 +00005405 if (!VDecl->getType()->isDependentType() &&
5406 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
Douglas Gregor4044d992009-03-24 16:43:20 +00005407 diag::err_typecheck_decl_incomplete_type)) {
5408 VDecl->setInvalidDecl();
5409 return;
5410 }
5411
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005412 // The variable can not have an abstract class type.
5413 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
5414 diag::err_abstract_type_in_decl,
5415 AbstractVariableType))
5416 VDecl->setInvalidDecl();
5417
Sebastian Redl5ca79842010-02-01 20:16:42 +00005418 const VarDecl *Def;
5419 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005420 Diag(VDecl->getLocation(), diag::err_redefinition)
5421 << VDecl->getDeclName();
5422 Diag(Def->getLocation(), diag::note_previous_definition);
5423 VDecl->setInvalidDecl();
Argyrios Kyrtzidis153d9672008-10-06 18:37:09 +00005424 return;
5425 }
Douglas Gregor50dc2192010-02-11 22:55:30 +00005426
Douglas Gregorf0f83692010-08-24 05:27:49 +00005427 // C++ [class.static.data]p4
5428 // If a static data member is of const integral or const
5429 // enumeration type, its declaration in the class definition can
5430 // specify a constant-initializer which shall be an integral
5431 // constant expression (5.19). In that case, the member can appear
5432 // in integral constant expressions. The member shall still be
5433 // defined in a namespace scope if it is used in the program and the
5434 // namespace scope definition shall not contain an initializer.
5435 //
5436 // We already performed a redefinition check above, but for static
5437 // data members we also need to check whether there was an in-class
5438 // declaration with an initializer.
5439 const VarDecl* PrevInit = 0;
5440 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
5441 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
5442 Diag(PrevInit->getLocation(), diag::note_previous_definition);
5443 return;
5444 }
5445
Douglas Gregor50dc2192010-02-11 22:55:30 +00005446 // If either the declaration has a dependent type or if any of the
5447 // expressions is type-dependent, we represent the initialization
5448 // via a ParenListExpr for later use during template instantiation.
5449 if (VDecl->getType()->isDependentType() ||
5450 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
5451 // Let clients know that initialization was done with a direct initializer.
5452 VDecl->setCXXDirectInitializer(true);
5453
5454 // Store the initialization expressions as a ParenListExpr.
5455 unsigned NumExprs = Exprs.size();
5456 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
5457 (Expr **)Exprs.release(),
5458 NumExprs, RParenLoc));
5459 return;
5460 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005461
5462 // Capture the variable that is being initialized and the style of
5463 // initialization.
5464 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
5465
5466 // FIXME: Poor source location information.
5467 InitializationKind Kind
5468 = InitializationKind::CreateDirect(VDecl->getLocation(),
5469 LParenLoc, RParenLoc);
5470
5471 InitializationSequence InitSeq(*this, Entity, Kind,
John McCallb268a282010-08-23 23:25:46 +00005472 Exprs.get(), Exprs.size());
John McCalldadc5752010-08-24 06:29:42 +00005473 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005474 if (Result.isInvalid()) {
5475 VDecl->setInvalidDecl();
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005476 return;
5477 }
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005478
John McCallb268a282010-08-23 23:25:46 +00005479 Result = MaybeCreateCXXExprWithTemporaries(Result.get());
Douglas Gregord5058122010-02-11 01:19:42 +00005480 VDecl->setInit(Result.takeAs<Expr>());
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005481 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidis997d00d2008-10-06 23:08:37 +00005482
John McCall8b0f4ff2010-08-02 21:13:48 +00005483 if (!VDecl->isInvalidDecl() &&
5484 !VDecl->getDeclContext()->isDependentContext() &&
Sebastian Redl02f1eeb2010-09-08 04:46:19 +00005485 VDecl->hasGlobalStorage() && !VDecl->isStaticLocal() &&
John McCall8b0f4ff2010-08-02 21:13:48 +00005486 !VDecl->getInit()->isConstantInitializer(Context,
5487 VDecl->getType()->isReferenceType()))
5488 Diag(VDecl->getLocation(), diag::warn_global_constructor)
5489 << VDecl->getInit()->getSourceRange();
5490
John McCall03c48482010-02-02 09:10:11 +00005491 if (const RecordType *Record = VDecl->getType()->getAs<RecordType>())
5492 FinalizeVarWithDestructor(VDecl, Record);
Argyrios Kyrtzidis9a1191c2008-10-06 17:10:33 +00005493}
Douglas Gregor8e1cf602008-10-29 00:13:59 +00005494
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005495/// \brief Given a constructor and the set of arguments provided for the
5496/// constructor, convert the arguments and add any required default arguments
5497/// to form a proper call to this constructor.
5498///
5499/// \returns true if an error occurred, false otherwise.
5500bool
5501Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
5502 MultiExprArg ArgsPtr,
5503 SourceLocation Loc,
John McCall37ad5512010-08-23 06:44:23 +00005504 ASTOwningVector<Expr*> &ConvertedArgs) {
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005505 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5506 unsigned NumArgs = ArgsPtr.size();
5507 Expr **Args = (Expr **)ArgsPtr.get();
5508
5509 const FunctionProtoType *Proto
5510 = Constructor->getType()->getAs<FunctionProtoType>();
5511 assert(Proto && "Constructor without a prototype?");
5512 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005513
5514 // If too few arguments are available, we'll fill in the rest with defaults.
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005515 if (NumArgs < NumArgsInProto)
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005516 ConvertedArgs.reserve(NumArgsInProto);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005517 else
Douglas Gregor5d3507d2009-09-09 23:08:42 +00005518 ConvertedArgs.reserve(NumArgs);
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00005519
5520 VariadicCallType CallType =
5521 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5522 llvm::SmallVector<Expr *, 8> AllArgs;
5523 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
5524 Proto, 0, Args, NumArgs, AllArgs,
5525 CallType);
5526 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
5527 ConvertedArgs.push_back(AllArgs[i]);
5528 return Invalid;
Douglas Gregorc28b57d2008-11-03 20:45:27 +00005529}
5530
Anders Carlssone363c8e2009-12-12 00:32:00 +00005531static inline bool
5532CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
5533 const FunctionDecl *FnDecl) {
Sebastian Redl50c68252010-08-31 00:36:30 +00005534 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
Anders Carlssone363c8e2009-12-12 00:32:00 +00005535 if (isa<NamespaceDecl>(DC)) {
5536 return SemaRef.Diag(FnDecl->getLocation(),
5537 diag::err_operator_new_delete_declared_in_namespace)
5538 << FnDecl->getDeclName();
5539 }
5540
5541 if (isa<TranslationUnitDecl>(DC) &&
John McCall8e7d6562010-08-26 03:08:43 +00005542 FnDecl->getStorageClass() == SC_Static) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005543 return SemaRef.Diag(FnDecl->getLocation(),
5544 diag::err_operator_new_delete_declared_static)
5545 << FnDecl->getDeclName();
5546 }
5547
Anders Carlsson60659a82009-12-12 02:43:16 +00005548 return false;
Anders Carlssone363c8e2009-12-12 00:32:00 +00005549}
5550
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005551static inline bool
5552CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
5553 CanQualType ExpectedResultType,
5554 CanQualType ExpectedFirstParamType,
5555 unsigned DependentParamTypeDiag,
5556 unsigned InvalidParamTypeDiag) {
5557 QualType ResultType =
5558 FnDecl->getType()->getAs<FunctionType>()->getResultType();
5559
5560 // Check that the result type is not dependent.
5561 if (ResultType->isDependentType())
5562 return SemaRef.Diag(FnDecl->getLocation(),
5563 diag::err_operator_new_delete_dependent_result_type)
5564 << FnDecl->getDeclName() << ExpectedResultType;
5565
5566 // Check that the result type is what we expect.
5567 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
5568 return SemaRef.Diag(FnDecl->getLocation(),
5569 diag::err_operator_new_delete_invalid_result_type)
5570 << FnDecl->getDeclName() << ExpectedResultType;
5571
5572 // A function template must have at least 2 parameters.
5573 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
5574 return SemaRef.Diag(FnDecl->getLocation(),
5575 diag::err_operator_new_delete_template_too_few_parameters)
5576 << FnDecl->getDeclName();
5577
5578 // The function decl must have at least 1 parameter.
5579 if (FnDecl->getNumParams() == 0)
5580 return SemaRef.Diag(FnDecl->getLocation(),
5581 diag::err_operator_new_delete_too_few_parameters)
5582 << FnDecl->getDeclName();
5583
5584 // Check the the first parameter type is not dependent.
5585 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
5586 if (FirstParamType->isDependentType())
5587 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
5588 << FnDecl->getDeclName() << ExpectedFirstParamType;
5589
5590 // Check that the first parameter type is what we expect.
Douglas Gregor684d7bd2009-12-22 23:42:49 +00005591 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005592 ExpectedFirstParamType)
5593 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
5594 << FnDecl->getDeclName() << ExpectedFirstParamType;
5595
5596 return false;
5597}
5598
Anders Carlsson12308f42009-12-11 23:23:22 +00005599static bool
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005600CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
Anders Carlssone363c8e2009-12-12 00:32:00 +00005601 // C++ [basic.stc.dynamic.allocation]p1:
5602 // A program is ill-formed if an allocation function is declared in a
5603 // namespace scope other than global scope or declared static in global
5604 // scope.
5605 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5606 return true;
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005607
5608 CanQualType SizeTy =
5609 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
5610
5611 // C++ [basic.stc.dynamic.allocation]p1:
5612 // The return type shall be void*. The first parameter shall have type
5613 // std::size_t.
5614 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
5615 SizeTy,
5616 diag::err_operator_new_dependent_param_type,
5617 diag::err_operator_new_param_type))
5618 return true;
5619
5620 // C++ [basic.stc.dynamic.allocation]p1:
5621 // The first parameter shall not have an associated default argument.
5622 if (FnDecl->getParamDecl(0)->hasDefaultArg())
Anders Carlsson22f443f2009-12-12 00:26:23 +00005623 return SemaRef.Diag(FnDecl->getLocation(),
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005624 diag::err_operator_new_default_arg)
5625 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
5626
5627 return false;
Anders Carlsson22f443f2009-12-12 00:26:23 +00005628}
5629
5630static bool
Anders Carlsson12308f42009-12-11 23:23:22 +00005631CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
5632 // C++ [basic.stc.dynamic.deallocation]p1:
5633 // A program is ill-formed if deallocation functions are declared in a
5634 // namespace scope other than global scope or declared static in global
5635 // scope.
Anders Carlssone363c8e2009-12-12 00:32:00 +00005636 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
5637 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005638
5639 // C++ [basic.stc.dynamic.deallocation]p2:
5640 // Each deallocation function shall return void and its first parameter
5641 // shall be void*.
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005642 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
5643 SemaRef.Context.VoidPtrTy,
5644 diag::err_operator_delete_dependent_param_type,
5645 diag::err_operator_delete_param_type))
5646 return true;
Anders Carlsson12308f42009-12-11 23:23:22 +00005647
Anders Carlsson12308f42009-12-11 23:23:22 +00005648 return false;
5649}
5650
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005651/// CheckOverloadedOperatorDeclaration - Check whether the declaration
5652/// of this overloaded operator is well-formed. If so, returns false;
5653/// otherwise, emits appropriate diagnostics and returns true.
5654bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregord69246b2008-11-17 16:14:12 +00005655 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005656 "Expected an overloaded operator declaration");
5657
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005658 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
5659
Mike Stump11289f42009-09-09 15:08:12 +00005660 // C++ [over.oper]p5:
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005661 // The allocation and deallocation functions, operator new,
5662 // operator new[], operator delete and operator delete[], are
5663 // described completely in 3.7.3. The attributes and restrictions
5664 // found in the rest of this subclause do not apply to them unless
5665 // explicitly stated in 3.7.3.
Anders Carlssonf1f46952009-12-11 23:31:21 +00005666 if (Op == OO_Delete || Op == OO_Array_Delete)
Anders Carlsson12308f42009-12-11 23:23:22 +00005667 return CheckOperatorDeleteDeclaration(*this, FnDecl);
Fariborz Jahanian4e088942009-11-10 23:47:18 +00005668
Anders Carlsson22f443f2009-12-12 00:26:23 +00005669 if (Op == OO_New || Op == OO_Array_New)
5670 return CheckOperatorNewDeclaration(*this, FnDecl);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005671
5672 // C++ [over.oper]p6:
5673 // An operator function shall either be a non-static member
5674 // function or be a non-member function and have at least one
5675 // parameter whose type is a class, a reference to a class, an
5676 // enumeration, or a reference to an enumeration.
Douglas Gregord69246b2008-11-17 16:14:12 +00005677 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
5678 if (MethodDecl->isStatic())
5679 return Diag(FnDecl->getLocation(),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005680 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005681 } else {
5682 bool ClassOrEnumParam = false;
Douglas Gregord69246b2008-11-17 16:14:12 +00005683 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
5684 ParamEnd = FnDecl->param_end();
5685 Param != ParamEnd; ++Param) {
5686 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman173e0b7a2009-06-27 05:59:59 +00005687 if (ParamType->isDependentType() || ParamType->isRecordType() ||
5688 ParamType->isEnumeralType()) {
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005689 ClassOrEnumParam = true;
5690 break;
5691 }
5692 }
5693
Douglas Gregord69246b2008-11-17 16:14:12 +00005694 if (!ClassOrEnumParam)
5695 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005696 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005697 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005698 }
5699
5700 // C++ [over.oper]p8:
5701 // An operator function cannot have default arguments (8.3.6),
5702 // except where explicitly stated below.
5703 //
Mike Stump11289f42009-09-09 15:08:12 +00005704 // Only the function-call operator allows default arguments
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005705 // (C++ [over.call]p1).
5706 if (Op != OO_Call) {
5707 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
5708 Param != FnDecl->param_end(); ++Param) {
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005709 if ((*Param)->hasDefaultArg())
Mike Stump11289f42009-09-09 15:08:12 +00005710 return Diag((*Param)->getLocation(),
Douglas Gregor58354032008-12-24 00:01:03 +00005711 diag::err_operator_overload_default_arg)
Anders Carlsson7e0b2072009-12-13 17:53:43 +00005712 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005713 }
5714 }
5715
Douglas Gregor6cf08062008-11-10 13:38:07 +00005716 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
5717 { false, false, false }
5718#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5719 , { Unary, Binary, MemberOnly }
5720#include "clang/Basic/OperatorKinds.def"
5721 };
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005722
Douglas Gregor6cf08062008-11-10 13:38:07 +00005723 bool CanBeUnaryOperator = OperatorUses[Op][0];
5724 bool CanBeBinaryOperator = OperatorUses[Op][1];
5725 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005726
5727 // C++ [over.oper]p8:
5728 // [...] Operator functions cannot have more or fewer parameters
5729 // than the number required for the corresponding operator, as
5730 // described in the rest of this subclause.
Mike Stump11289f42009-09-09 15:08:12 +00005731 unsigned NumParams = FnDecl->getNumParams()
Douglas Gregord69246b2008-11-17 16:14:12 +00005732 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005733 if (Op != OO_Call &&
5734 ((NumParams == 1 && !CanBeUnaryOperator) ||
5735 (NumParams == 2 && !CanBeBinaryOperator) ||
5736 (NumParams < 1) || (NumParams > 2))) {
5737 // We have the wrong number of parameters.
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005738 unsigned ErrorKind;
Douglas Gregor6cf08062008-11-10 13:38:07 +00005739 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005740 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor6cf08062008-11-10 13:38:07 +00005741 } else if (CanBeUnaryOperator) {
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005742 ErrorKind = 0; // 0 -> unary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005743 } else {
Chris Lattner2b786902008-11-21 07:50:02 +00005744 assert(CanBeBinaryOperator &&
5745 "All non-call overloaded operators are unary or binary!");
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005746 ErrorKind = 1; // 1 -> binary
Douglas Gregor6cf08062008-11-10 13:38:07 +00005747 }
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005748
Chris Lattnerc5bab9f2008-11-21 07:57:12 +00005749 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005750 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005751 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00005752
Douglas Gregord69246b2008-11-17 16:14:12 +00005753 // Overloaded operators other than operator() cannot be variadic.
5754 if (Op != OO_Call &&
John McCall9dd450b2009-09-21 23:43:11 +00005755 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00005756 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005757 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005758 }
5759
5760 // Some operators must be non-static member functions.
Douglas Gregord69246b2008-11-17 16:14:12 +00005761 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
5762 return Diag(FnDecl->getLocation(),
Chris Lattner651d42d2008-11-20 06:38:18 +00005763 diag::err_operator_overload_must_be_member)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00005764 << FnDecl->getDeclName();
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005765 }
5766
5767 // C++ [over.inc]p1:
5768 // The user-defined function called operator++ implements the
5769 // prefix and postfix ++ operator. If this function is a member
5770 // function with no parameters, or a non-member function with one
5771 // parameter of class or enumeration type, it defines the prefix
5772 // increment operator ++ for objects of that type. If the function
5773 // is a member function with one parameter (which shall be of type
5774 // int) or a non-member function with two parameters (the second
5775 // of which shall be of type int), it defines the postfix
5776 // increment operator ++ for objects of that type.
5777 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
5778 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
5779 bool ParamIsInt = false;
John McCall9dd450b2009-09-21 23:43:11 +00005780 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005781 ParamIsInt = BT->getKind() == BuiltinType::Int;
5782
Chris Lattner2b786902008-11-21 07:50:02 +00005783 if (!ParamIsInt)
5784 return Diag(LastParam->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00005785 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005786 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005787 }
5788
Douglas Gregord69246b2008-11-17 16:14:12 +00005789 return false;
Douglas Gregor11d0c4c2008-11-06 22:13:31 +00005790}
Chris Lattner3b024a32008-12-17 07:09:26 +00005791
Alexis Huntc88db062010-01-13 09:01:02 +00005792/// CheckLiteralOperatorDeclaration - Check whether the declaration
5793/// of this literal operator function is well-formed. If so, returns
5794/// false; otherwise, emits appropriate diagnostics and returns true.
5795bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
5796 DeclContext *DC = FnDecl->getDeclContext();
5797 Decl::Kind Kind = DC->getDeclKind();
5798 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
5799 Kind != Decl::LinkageSpec) {
5800 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
5801 << FnDecl->getDeclName();
5802 return true;
5803 }
5804
5805 bool Valid = false;
5806
Alexis Hunt7dd26172010-04-07 23:11:06 +00005807 // template <char...> type operator "" name() is the only valid template
5808 // signature, and the only valid signature with no parameters.
5809 if (FnDecl->param_size() == 0) {
5810 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
5811 // Must have only one template parameter
5812 TemplateParameterList *Params = TpDecl->getTemplateParameters();
5813 if (Params->size() == 1) {
5814 NonTypeTemplateParmDecl *PmDecl =
5815 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
Alexis Huntc88db062010-01-13 09:01:02 +00005816
Alexis Hunt7dd26172010-04-07 23:11:06 +00005817 // The template parameter must be a char parameter pack.
5818 // FIXME: This test will always fail because non-type parameter packs
5819 // have not been implemented.
5820 if (PmDecl && PmDecl->isTemplateParameterPack() &&
5821 Context.hasSameType(PmDecl->getType(), Context.CharTy))
5822 Valid = true;
5823 }
5824 }
5825 } else {
Alexis Huntc88db062010-01-13 09:01:02 +00005826 // Check the first parameter
Alexis Hunt7dd26172010-04-07 23:11:06 +00005827 FunctionDecl::param_iterator Param = FnDecl->param_begin();
5828
Alexis Huntc88db062010-01-13 09:01:02 +00005829 QualType T = (*Param)->getType();
5830
Alexis Hunt079a6f72010-04-07 22:57:35 +00005831 // unsigned long long int, long double, and any character type are allowed
5832 // as the only parameters.
Alexis Huntc88db062010-01-13 09:01:02 +00005833 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
5834 Context.hasSameType(T, Context.LongDoubleTy) ||
5835 Context.hasSameType(T, Context.CharTy) ||
5836 Context.hasSameType(T, Context.WCharTy) ||
5837 Context.hasSameType(T, Context.Char16Ty) ||
5838 Context.hasSameType(T, Context.Char32Ty)) {
5839 if (++Param == FnDecl->param_end())
5840 Valid = true;
5841 goto FinishedParams;
5842 }
5843
Alexis Hunt079a6f72010-04-07 22:57:35 +00005844 // Otherwise it must be a pointer to const; let's strip those qualifiers.
Alexis Huntc88db062010-01-13 09:01:02 +00005845 const PointerType *PT = T->getAs<PointerType>();
5846 if (!PT)
5847 goto FinishedParams;
5848 T = PT->getPointeeType();
5849 if (!T.isConstQualified())
5850 goto FinishedParams;
5851 T = T.getUnqualifiedType();
5852
5853 // Move on to the second parameter;
5854 ++Param;
5855
5856 // If there is no second parameter, the first must be a const char *
5857 if (Param == FnDecl->param_end()) {
5858 if (Context.hasSameType(T, Context.CharTy))
5859 Valid = true;
5860 goto FinishedParams;
5861 }
5862
5863 // const char *, const wchar_t*, const char16_t*, and const char32_t*
5864 // are allowed as the first parameter to a two-parameter function
5865 if (!(Context.hasSameType(T, Context.CharTy) ||
5866 Context.hasSameType(T, Context.WCharTy) ||
5867 Context.hasSameType(T, Context.Char16Ty) ||
5868 Context.hasSameType(T, Context.Char32Ty)))
5869 goto FinishedParams;
5870
5871 // The second and final parameter must be an std::size_t
5872 T = (*Param)->getType().getUnqualifiedType();
5873 if (Context.hasSameType(T, Context.getSizeType()) &&
5874 ++Param == FnDecl->param_end())
5875 Valid = true;
5876 }
5877
5878 // FIXME: This diagnostic is absolutely terrible.
5879FinishedParams:
5880 if (!Valid) {
5881 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
5882 << FnDecl->getDeclName();
5883 return true;
5884 }
5885
5886 return false;
5887}
5888
Douglas Gregor07665a62009-01-05 19:45:36 +00005889/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
5890/// linkage specification, including the language and (if present)
5891/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
5892/// the location of the language string literal, which is provided
5893/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
5894/// the '{' brace. Otherwise, this linkage specification does not
5895/// have any braces.
John McCall48871652010-08-21 09:40:31 +00005896Decl *Sema::ActOnStartLinkageSpecification(Scope *S,
Chris Lattner83f095c2009-03-28 19:18:32 +00005897 SourceLocation ExternLoc,
5898 SourceLocation LangLoc,
Benjamin Kramerbebee842010-05-03 13:08:54 +00005899 llvm::StringRef Lang,
Chris Lattner83f095c2009-03-28 19:18:32 +00005900 SourceLocation LBraceLoc) {
Chris Lattner438e5012008-12-17 07:13:27 +00005901 LinkageSpecDecl::LanguageIDs Language;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005902 if (Lang == "\"C\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005903 Language = LinkageSpecDecl::lang_c;
Benjamin Kramerbebee842010-05-03 13:08:54 +00005904 else if (Lang == "\"C++\"")
Chris Lattner438e5012008-12-17 07:13:27 +00005905 Language = LinkageSpecDecl::lang_cxx;
5906 else {
Douglas Gregor07665a62009-01-05 19:45:36 +00005907 Diag(LangLoc, diag::err_bad_language);
John McCall48871652010-08-21 09:40:31 +00005908 return 0;
Chris Lattner438e5012008-12-17 07:13:27 +00005909 }
Mike Stump11289f42009-09-09 15:08:12 +00005910
Chris Lattner438e5012008-12-17 07:13:27 +00005911 // FIXME: Add all the various semantics of linkage specifications
Mike Stump11289f42009-09-09 15:08:12 +00005912
Douglas Gregor07665a62009-01-05 19:45:36 +00005913 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
Mike Stump11289f42009-09-09 15:08:12 +00005914 LangLoc, Language,
Douglas Gregor07665a62009-01-05 19:45:36 +00005915 LBraceLoc.isValid());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005916 CurContext->addDecl(D);
Douglas Gregor07665a62009-01-05 19:45:36 +00005917 PushDeclContext(S, D);
John McCall48871652010-08-21 09:40:31 +00005918 return D;
Chris Lattner438e5012008-12-17 07:13:27 +00005919}
5920
Abramo Bagnaraed5b6892010-07-30 16:47:02 +00005921/// ActOnFinishLinkageSpecification - Complete the definition of
Douglas Gregor07665a62009-01-05 19:45:36 +00005922/// the C++ linkage specification LinkageSpec. If RBraceLoc is
5923/// valid, it's the position of the closing '}' brace in a linkage
5924/// specification that uses braces.
John McCall48871652010-08-21 09:40:31 +00005925Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
5926 Decl *LinkageSpec,
Chris Lattner83f095c2009-03-28 19:18:32 +00005927 SourceLocation RBraceLoc) {
Douglas Gregor07665a62009-01-05 19:45:36 +00005928 if (LinkageSpec)
5929 PopDeclContext();
5930 return LinkageSpec;
Chris Lattner3b024a32008-12-17 07:09:26 +00005931}
5932
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005933/// \brief Perform semantic analysis for the variable declaration that
5934/// occurs within a C++ catch clause, returning the newly-created
5935/// variable.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00005936VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
John McCallbcd03502009-12-07 02:54:59 +00005937 TypeSourceInfo *TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005938 IdentifierInfo *Name,
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00005939 SourceLocation Loc) {
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005940 bool Invalid = false;
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00005941 QualType ExDeclType = TInfo->getType();
5942
Sebastian Redl54c04d42008-12-22 19:15:10 +00005943 // Arrays and functions decay.
5944 if (ExDeclType->isArrayType())
5945 ExDeclType = Context.getArrayDecayedType(ExDeclType);
5946 else if (ExDeclType->isFunctionType())
5947 ExDeclType = Context.getPointerType(ExDeclType);
5948
5949 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
5950 // The exception-declaration shall not denote a pointer or reference to an
5951 // incomplete type, other than [cv] void*.
Sebastian Redlb28b4072009-03-22 23:49:27 +00005952 // N2844 forbids rvalue references.
Mike Stump11289f42009-09-09 15:08:12 +00005953 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00005954 Diag(Loc, diag::err_catch_rvalue_ref);
Sebastian Redlb28b4072009-03-22 23:49:27 +00005955 Invalid = true;
5956 }
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005957
Douglas Gregor104ee002010-03-08 01:47:36 +00005958 // GCC allows catching pointers and references to incomplete types
5959 // as an extension; so do we, but we warn by default.
5960
Sebastian Redl54c04d42008-12-22 19:15:10 +00005961 QualType BaseType = ExDeclType;
5962 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregordd430f72009-01-19 19:26:10 +00005963 unsigned DK = diag::err_catch_incomplete;
Douglas Gregor104ee002010-03-08 01:47:36 +00005964 bool IncompleteCatchIsInvalid = true;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005965 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00005966 BaseType = Ptr->getPointeeType();
5967 Mode = 1;
Douglas Gregor104ee002010-03-08 01:47:36 +00005968 DK = diag::ext_catch_incomplete_ptr;
5969 IncompleteCatchIsInvalid = false;
Mike Stump11289f42009-09-09 15:08:12 +00005970 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00005971 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl54c04d42008-12-22 19:15:10 +00005972 BaseType = Ref->getPointeeType();
5973 Mode = 2;
Douglas Gregor104ee002010-03-08 01:47:36 +00005974 DK = diag::ext_catch_incomplete_ref;
5975 IncompleteCatchIsInvalid = false;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005976 }
Sebastian Redlb28b4072009-03-22 23:49:27 +00005977 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor104ee002010-03-08 01:47:36 +00005978 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
5979 IncompleteCatchIsInvalid)
Sebastian Redl54c04d42008-12-22 19:15:10 +00005980 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00005981
Mike Stump11289f42009-09-09 15:08:12 +00005982 if (!Invalid && !ExDeclType->isDependentType() &&
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00005983 RequireNonAbstractType(Loc, ExDeclType,
5984 diag::err_abstract_type_in_decl,
5985 AbstractVariableType))
Sebastian Redl2f38ba52009-04-27 21:03:30 +00005986 Invalid = true;
5987
John McCall2ca705e2010-07-24 00:37:23 +00005988 // Only the non-fragile NeXT runtime currently supports C++ catches
5989 // of ObjC types, and no runtime supports catching ObjC types by value.
5990 if (!Invalid && getLangOptions().ObjC1) {
5991 QualType T = ExDeclType;
5992 if (const ReferenceType *RT = T->getAs<ReferenceType>())
5993 T = RT->getPointeeType();
5994
5995 if (T->isObjCObjectType()) {
5996 Diag(Loc, diag::err_objc_object_catch);
5997 Invalid = true;
5998 } else if (T->isObjCObjectPointerType()) {
5999 if (!getLangOptions().NeXTRuntime) {
6000 Diag(Loc, diag::err_objc_pointer_cxx_catch_gnu);
6001 Invalid = true;
6002 } else if (!getLangOptions().ObjCNonFragileABI) {
6003 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
6004 Invalid = true;
6005 }
6006 }
6007 }
6008
Mike Stump11289f42009-09-09 15:08:12 +00006009 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
John McCall8e7d6562010-08-26 03:08:43 +00006010 Name, ExDeclType, TInfo, SC_None,
6011 SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00006012 ExDecl->setExceptionVariable(true);
6013
Douglas Gregor6de584c2010-03-05 23:38:39 +00006014 if (!Invalid) {
6015 if (const RecordType *RecordTy = ExDeclType->getAs<RecordType>()) {
6016 // C++ [except.handle]p16:
6017 // The object declared in an exception-declaration or, if the
6018 // exception-declaration does not specify a name, a temporary (12.2) is
6019 // copy-initialized (8.5) from the exception object. [...]
6020 // The object is destroyed when the handler exits, after the destruction
6021 // of any automatic objects initialized within the handler.
6022 //
6023 // We just pretend to initialize the object with itself, then make sure
6024 // it can be destroyed later.
6025 InitializedEntity Entity = InitializedEntity::InitializeVariable(ExDecl);
6026 Expr *ExDeclRef = DeclRefExpr::Create(Context, 0, SourceRange(), ExDecl,
6027 Loc, ExDeclType, 0);
6028 InitializationKind Kind = InitializationKind::CreateCopy(Loc,
6029 SourceLocation());
6030 InitializationSequence InitSeq(*this, Entity, Kind, &ExDeclRef, 1);
John McCalldadc5752010-08-24 06:29:42 +00006031 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
John McCall37ad5512010-08-23 06:44:23 +00006032 MultiExprArg(*this, &ExDeclRef, 1));
Douglas Gregor6de584c2010-03-05 23:38:39 +00006033 if (Result.isInvalid())
6034 Invalid = true;
6035 else
6036 FinalizeVarWithDestructor(ExDecl, RecordTy);
6037 }
6038 }
6039
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006040 if (Invalid)
6041 ExDecl->setInvalidDecl();
6042
6043 return ExDecl;
6044}
6045
6046/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6047/// handler.
John McCall48871652010-08-21 09:40:31 +00006048Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
John McCall8cb7bdf2010-06-04 23:28:52 +00006049 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6050 QualType ExDeclType = TInfo->getType();
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006051
6052 bool Invalid = D.isInvalidType();
Sebastian Redl54c04d42008-12-22 19:15:10 +00006053 IdentifierInfo *II = D.getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00006054 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
Douglas Gregorb8eaf292010-04-15 23:40:53 +00006055 LookupOrdinaryName,
6056 ForRedeclaration)) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006057 // The scope should be freshly made just for us. There is just no way
6058 // it contains any previous declaration.
John McCall48871652010-08-21 09:40:31 +00006059 assert(!S->isDeclScope(PrevDecl));
Sebastian Redl54c04d42008-12-22 19:15:10 +00006060 if (PrevDecl->isTemplateParameter()) {
6061 // Maybe we will complain about the shadowed template parameter.
6062 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006063 }
6064 }
6065
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006066 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl54c04d42008-12-22 19:15:10 +00006067 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
6068 << D.getCXXScopeSpec().getRange();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006069 Invalid = true;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006070 }
6071
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006072 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006073 D.getIdentifier(),
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00006074 D.getIdentifierLoc());
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006075
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00006076 if (Invalid)
6077 ExDecl->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00006078
Sebastian Redl54c04d42008-12-22 19:15:10 +00006079 // Add the exception declaration into this scope.
Sebastian Redl54c04d42008-12-22 19:15:10 +00006080 if (II)
Douglas Gregor5e16fbe2009-05-18 20:51:54 +00006081 PushOnScopeChains(ExDecl, S);
6082 else
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006083 CurContext->addDecl(ExDecl);
Sebastian Redl54c04d42008-12-22 19:15:10 +00006084
Douglas Gregor758a8692009-06-17 21:51:59 +00006085 ProcessDeclAttributes(S, ExDecl, D);
John McCall48871652010-08-21 09:40:31 +00006086 return ExDecl;
Sebastian Redl54c04d42008-12-22 19:15:10 +00006087}
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006088
John McCall48871652010-08-21 09:40:31 +00006089Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
John McCallb268a282010-08-23 23:25:46 +00006090 Expr *AssertExpr,
6091 Expr *AssertMessageExpr_) {
6092 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006093
Anders Carlsson54b26982009-03-14 00:33:21 +00006094 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
6095 llvm::APSInt Value(32);
6096 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
6097 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
6098 AssertExpr->getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006099 return 0;
Anders Carlsson54b26982009-03-14 00:33:21 +00006100 }
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006101
Anders Carlsson54b26982009-03-14 00:33:21 +00006102 if (Value == 0) {
Mike Stump11289f42009-09-09 15:08:12 +00006103 Diag(AssertLoc, diag::err_static_assert_failed)
Benjamin Kramerb11118b2009-12-11 13:33:18 +00006104 << AssertMessage->getString() << AssertExpr->getSourceRange();
Anders Carlsson54b26982009-03-14 00:33:21 +00006105 }
6106 }
Mike Stump11289f42009-09-09 15:08:12 +00006107
Mike Stump11289f42009-09-09 15:08:12 +00006108 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006109 AssertExpr, AssertMessage);
Mike Stump11289f42009-09-09 15:08:12 +00006110
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00006111 CurContext->addDecl(Decl);
John McCall48871652010-08-21 09:40:31 +00006112 return Decl;
Anders Carlsson5bbe1d72009-03-14 00:25:26 +00006113}
Sebastian Redlf769df52009-03-24 22:27:57 +00006114
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006115/// \brief Perform semantic analysis of the given friend type declaration.
6116///
6117/// \returns A friend declaration that.
6118FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
6119 TypeSourceInfo *TSInfo) {
6120 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
6121
6122 QualType T = TSInfo->getType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006123 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006124
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006125 if (!getLangOptions().CPlusPlus0x) {
6126 // C++03 [class.friend]p2:
6127 // An elaborated-type-specifier shall be used in a friend declaration
6128 // for a class.*
6129 //
6130 // * The class-key of the elaborated-type-specifier is required.
6131 if (!ActiveTemplateInstantiations.empty()) {
6132 // Do not complain about the form of friend template types during
6133 // template instantiation; we will already have complained when the
6134 // template was declared.
6135 } else if (!T->isElaboratedTypeSpecifier()) {
6136 // If we evaluated the type to a record type, suggest putting
6137 // a tag in front.
6138 if (const RecordType *RT = T->getAs<RecordType>()) {
6139 RecordDecl *RD = RT->getDecl();
6140
6141 std::string InsertionText = std::string(" ") + RD->getKindName();
6142
6143 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
6144 << (unsigned) RD->getTagKind()
6145 << T
6146 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
6147 InsertionText);
6148 } else {
6149 Diag(FriendLoc, diag::ext_nonclass_type_friend)
6150 << T
6151 << SourceRange(FriendLoc, TypeRange.getEnd());
6152 }
6153 } else if (T->getAs<EnumType>()) {
6154 Diag(FriendLoc, diag::ext_enum_friend)
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006155 << T
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006156 << SourceRange(FriendLoc, TypeRange.getEnd());
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006157 }
6158 }
6159
Douglas Gregor3b4abb62010-04-07 17:57:12 +00006160 // C++0x [class.friend]p3:
6161 // If the type specifier in a friend declaration designates a (possibly
6162 // cv-qualified) class type, that class is declared as a friend; otherwise,
6163 // the friend declaration is ignored.
6164
6165 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6166 // in [class.friend]p3 that we do not implement.
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006167
6168 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
6169}
6170
John McCall11083da2009-09-16 22:47:08 +00006171/// Handle a friend type declaration. This works in tandem with
6172/// ActOnTag.
6173///
6174/// Notes on friend class templates:
6175///
6176/// We generally treat friend class declarations as if they were
6177/// declaring a class. So, for example, the elaborated type specifier
6178/// in a friend declaration is required to obey the restrictions of a
6179/// class-head (i.e. no typedefs in the scope chain), template
6180/// parameters are required to match up with simple template-ids, &c.
6181/// However, unlike when declaring a template specialization, it's
6182/// okay to refer to a template specialization without an empty
6183/// template parameter declaration, e.g.
6184/// friend class A<T>::B<unsigned>;
6185/// We permit this as a special case; if there are any template
6186/// parameters present at all, require proper matching, i.e.
6187/// template <> template <class T> friend class A<int>::B;
John McCall48871652010-08-21 09:40:31 +00006188Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
John McCall11083da2009-09-16 22:47:08 +00006189 MultiTemplateParamsArg TempParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006190 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall07e91c02009-08-06 02:15:43 +00006191
6192 assert(DS.isFriendSpecified());
6193 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6194
John McCall11083da2009-09-16 22:47:08 +00006195 // Try to convert the decl specifier to a type. This works for
6196 // friend templates because ActOnTag never produces a ClassTemplateDecl
6197 // for a TUK_Friend.
Chris Lattner1fb66f42009-10-25 17:47:27 +00006198 Declarator TheDeclarator(DS, Declarator::MemberContext);
John McCall8cb7bdf2010-06-04 23:28:52 +00006199 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
6200 QualType T = TSI->getType();
Chris Lattner1fb66f42009-10-25 17:47:27 +00006201 if (TheDeclarator.isInvalidType())
John McCall48871652010-08-21 09:40:31 +00006202 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006203
John McCall11083da2009-09-16 22:47:08 +00006204 // This is definitely an error in C++98. It's probably meant to
6205 // be forbidden in C++0x, too, but the specification is just
6206 // poorly written.
6207 //
6208 // The problem is with declarations like the following:
6209 // template <T> friend A<T>::foo;
6210 // where deciding whether a class C is a friend or not now hinges
6211 // on whether there exists an instantiation of A that causes
6212 // 'foo' to equal C. There are restrictions on class-heads
6213 // (which we declare (by fiat) elaborated friend declarations to
6214 // be) that makes this tractable.
6215 //
6216 // FIXME: handle "template <> friend class A<T>;", which
6217 // is possibly well-formed? Who even knows?
Douglas Gregore677daf2010-03-31 22:19:08 +00006218 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
John McCall11083da2009-09-16 22:47:08 +00006219 Diag(Loc, diag::err_tagless_friend_type_template)
6220 << DS.getSourceRange();
John McCall48871652010-08-21 09:40:31 +00006221 return 0;
John McCall11083da2009-09-16 22:47:08 +00006222 }
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006223
John McCallaa74a0c2009-08-28 07:59:38 +00006224 // C++98 [class.friend]p1: A friend of a class is a function
6225 // or class that is not a member of the class . . .
John McCall463e10c2009-12-22 00:59:39 +00006226 // This is fixed in DR77, which just barely didn't make the C++03
6227 // deadline. It's also a very silly restriction that seriously
6228 // affects inner classes and which nobody else seems to implement;
6229 // thus we never diagnose it, not even in -pedantic.
John McCall15ad0962010-03-25 18:04:51 +00006230 //
6231 // But note that we could warn about it: it's always useless to
6232 // friend one of your own members (it's not, however, worthless to
6233 // friend a member of an arbitrary specialization of your template).
John McCallaa74a0c2009-08-28 07:59:38 +00006234
John McCall11083da2009-09-16 22:47:08 +00006235 Decl *D;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006236 if (unsigned NumTempParamLists = TempParams.size())
John McCall11083da2009-09-16 22:47:08 +00006237 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006238 NumTempParamLists,
John McCall11083da2009-09-16 22:47:08 +00006239 (TemplateParameterList**) TempParams.release(),
John McCall15ad0962010-03-25 18:04:51 +00006240 TSI,
John McCall11083da2009-09-16 22:47:08 +00006241 DS.getFriendSpecLoc());
6242 else
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006243 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
6244
6245 if (!D)
John McCall48871652010-08-21 09:40:31 +00006246 return 0;
Douglas Gregorafb9bc12010-04-07 16:53:43 +00006247
John McCall11083da2009-09-16 22:47:08 +00006248 D->setAccess(AS_public);
6249 CurContext->addDecl(D);
John McCallaa74a0c2009-08-28 07:59:38 +00006250
John McCall48871652010-08-21 09:40:31 +00006251 return D;
John McCallaa74a0c2009-08-28 07:59:38 +00006252}
6253
John McCall48871652010-08-21 09:40:31 +00006254Decl *Sema::ActOnFriendFunctionDecl(Scope *S,
6255 Declarator &D,
6256 bool IsDefinition,
John McCall2f212b32009-09-11 21:02:39 +00006257 MultiTemplateParamsArg TemplateParams) {
John McCallaa74a0c2009-08-28 07:59:38 +00006258 const DeclSpec &DS = D.getDeclSpec();
6259
6260 assert(DS.isFriendSpecified());
6261 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
6262
6263 SourceLocation Loc = D.getIdentifierLoc();
John McCall8cb7bdf2010-06-04 23:28:52 +00006264 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6265 QualType T = TInfo->getType();
John McCall07e91c02009-08-06 02:15:43 +00006266
6267 // C++ [class.friend]p1
6268 // A friend of a class is a function or class....
6269 // Note that this sees through typedefs, which is intended.
John McCallaa74a0c2009-08-28 07:59:38 +00006270 // It *doesn't* see through dependent types, which is correct
6271 // according to [temp.arg.type]p3:
6272 // If a declaration acquires a function type through a
6273 // type dependent on a template-parameter and this causes
6274 // a declaration that does not use the syntactic form of a
6275 // function declarator to have a function type, the program
6276 // is ill-formed.
John McCall07e91c02009-08-06 02:15:43 +00006277 if (!T->isFunctionType()) {
6278 Diag(Loc, diag::err_unexpected_friend);
6279
6280 // It might be worthwhile to try to recover by creating an
6281 // appropriate declaration.
John McCall48871652010-08-21 09:40:31 +00006282 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006283 }
6284
6285 // C++ [namespace.memdef]p3
6286 // - If a friend declaration in a non-local class first declares a
6287 // class or function, the friend class or function is a member
6288 // of the innermost enclosing namespace.
6289 // - The name of the friend is not found by simple name lookup
6290 // until a matching declaration is provided in that namespace
6291 // scope (either before or after the class declaration granting
6292 // friendship).
6293 // - If a friend function is called, its name may be found by the
6294 // name lookup that considers functions from namespaces and
6295 // classes associated with the types of the function arguments.
6296 // - When looking for a prior declaration of a class or a function
6297 // declared as a friend, scopes outside the innermost enclosing
6298 // namespace scope are not considered.
6299
John McCallaa74a0c2009-08-28 07:59:38 +00006300 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006301 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6302 DeclarationName Name = NameInfo.getName();
John McCall07e91c02009-08-06 02:15:43 +00006303 assert(Name);
6304
John McCall07e91c02009-08-06 02:15:43 +00006305 // The context we found the declaration in, or in which we should
6306 // create the declaration.
6307 DeclContext *DC;
6308
6309 // FIXME: handle local classes
6310
6311 // Recover from invalid scope qualifiers as if they just weren't there.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006312 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
John McCall1f82f242009-11-18 22:49:29 +00006313 ForRedeclaration);
John McCall07e91c02009-08-06 02:15:43 +00006314 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
6315 DC = computeDeclContext(ScopeQual);
6316
6317 // FIXME: handle dependent contexts
John McCall48871652010-08-21 09:40:31 +00006318 if (!DC) return 0;
6319 if (RequireCompleteDeclContext(ScopeQual, DC)) return 0;
John McCall07e91c02009-08-06 02:15:43 +00006320
John McCall1f82f242009-11-18 22:49:29 +00006321 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006322
John McCall45831862010-05-28 01:41:47 +00006323 // Ignore things found implicitly in the wrong scope.
John McCall07e91c02009-08-06 02:15:43 +00006324 // TODO: better diagnostics for this case. Suggesting the right
6325 // qualified scope would be nice...
John McCall45831862010-05-28 01:41:47 +00006326 LookupResult::Filter F = Previous.makeFilter();
6327 while (F.hasNext()) {
6328 NamedDecl *D = F.next();
Sebastian Redl50c68252010-08-31 00:36:30 +00006329 if (!DC->InEnclosingNamespaceSetOf(
6330 D->getDeclContext()->getRedeclContext()))
John McCall45831862010-05-28 01:41:47 +00006331 F.erase();
6332 }
6333 F.done();
6334
6335 if (Previous.empty()) {
John McCallaa74a0c2009-08-28 07:59:38 +00006336 D.setInvalidType();
John McCall07e91c02009-08-06 02:15:43 +00006337 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
John McCall48871652010-08-21 09:40:31 +00006338 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006339 }
6340
6341 // C++ [class.friend]p1: A friend of a class is a function or
6342 // class that is not a member of the class . . .
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006343 if (DC->Equals(CurContext))
John McCall07e91c02009-08-06 02:15:43 +00006344 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6345
John McCall07e91c02009-08-06 02:15:43 +00006346 // Otherwise walk out to the nearest namespace scope looking for matches.
6347 } else {
6348 // TODO: handle local class contexts.
6349
6350 DC = CurContext;
6351 while (true) {
6352 // Skip class contexts. If someone can cite chapter and verse
6353 // for this behavior, that would be nice --- it's what GCC and
6354 // EDG do, and it seems like a reasonable intent, but the spec
6355 // really only says that checks for unqualified existing
6356 // declarations should stop at the nearest enclosing namespace,
6357 // not that they should only consider the nearest enclosing
6358 // namespace.
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006359 while (DC->isRecord())
6360 DC = DC->getParent();
John McCall07e91c02009-08-06 02:15:43 +00006361
John McCall1f82f242009-11-18 22:49:29 +00006362 LookupQualifiedName(Previous, DC);
John McCall07e91c02009-08-06 02:15:43 +00006363
6364 // TODO: decide what we think about using declarations.
John McCall1f82f242009-11-18 22:49:29 +00006365 if (!Previous.empty())
John McCall07e91c02009-08-06 02:15:43 +00006366 break;
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006367
John McCall07e91c02009-08-06 02:15:43 +00006368 if (DC->isFileContext()) break;
6369 DC = DC->getParent();
6370 }
6371
6372 // C++ [class.friend]p1: A friend of a class is a function or
6373 // class that is not a member of the class . . .
John McCall93343b92009-08-06 20:49:32 +00006374 // C++0x changes this for both friend types and functions.
6375 // Most C++ 98 compilers do seem to give an error here, so
6376 // we do, too.
John McCall1f82f242009-11-18 22:49:29 +00006377 if (!Previous.empty() && DC->Equals(CurContext)
6378 && !getLangOptions().CPlusPlus0x)
John McCall07e91c02009-08-06 02:15:43 +00006379 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
6380 }
6381
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006382 if (DC->isFileContext()) {
John McCall07e91c02009-08-06 02:15:43 +00006383 // This implies that it has to be an operator or function.
Douglas Gregor7861a802009-11-03 01:35:08 +00006384 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
6385 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
6386 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
John McCall07e91c02009-08-06 02:15:43 +00006387 Diag(Loc, diag::err_introducing_special_friend) <<
Douglas Gregor7861a802009-11-03 01:35:08 +00006388 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
6389 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
John McCall48871652010-08-21 09:40:31 +00006390 return 0;
John McCall07e91c02009-08-06 02:15:43 +00006391 }
John McCall07e91c02009-08-06 02:15:43 +00006392 }
6393
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006394 bool Redeclaration = false;
John McCallbcd03502009-12-07 02:54:59 +00006395 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, TInfo, Previous,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00006396 move(TemplateParams),
John McCalld1e9d832009-08-11 06:59:38 +00006397 IsDefinition,
6398 Redeclaration);
John McCall48871652010-08-21 09:40:31 +00006399 if (!ND) return 0;
John McCall759e32b2009-08-31 22:39:49 +00006400
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006401 assert(ND->getDeclContext() == DC);
6402 assert(ND->getLexicalDeclContext() == CurContext);
John McCall5ed6e8f2009-08-18 00:00:49 +00006403
John McCall759e32b2009-08-31 22:39:49 +00006404 // Add the function declaration to the appropriate lookup tables,
6405 // adjusting the redeclarations list as necessary. We don't
6406 // want to do this yet if the friending class is dependent.
Mike Stump11289f42009-09-09 15:08:12 +00006407 //
John McCall759e32b2009-08-31 22:39:49 +00006408 // Also update the scope-based lookup if the target context's
6409 // lookup context is in lexical scope.
6410 if (!CurContext->isDependentContext()) {
Sebastian Redl50c68252010-08-31 00:36:30 +00006411 DC = DC->getRedeclContext();
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006412 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006413 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006414 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
John McCall759e32b2009-08-31 22:39:49 +00006415 }
John McCallaa74a0c2009-08-28 07:59:38 +00006416
6417 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
Douglas Gregora29a3ff2009-09-28 00:08:27 +00006418 D.getIdentifierLoc(), ND,
John McCallaa74a0c2009-08-28 07:59:38 +00006419 DS.getFriendSpecLoc());
John McCall75c03bb2009-08-29 03:50:18 +00006420 FrD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +00006421 CurContext->addDecl(FrD);
John McCall07e91c02009-08-06 02:15:43 +00006422
John McCall48871652010-08-21 09:40:31 +00006423 return ND;
Anders Carlsson38811702009-05-11 22:55:49 +00006424}
6425
John McCall48871652010-08-21 09:40:31 +00006426void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
6427 AdjustDeclIfTemplate(Dcl);
Mike Stump11289f42009-09-09 15:08:12 +00006428
Sebastian Redlf769df52009-03-24 22:27:57 +00006429 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
6430 if (!Fn) {
6431 Diag(DelLoc, diag::err_deleted_non_function);
6432 return;
6433 }
6434 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
6435 Diag(DelLoc, diag::err_deleted_decl_not_first);
6436 Diag(Prev->getLocation(), diag::note_previous_declaration);
6437 // If the declaration wasn't the first, we delete the function anyway for
6438 // recovery.
6439 }
6440 Fn->setDeleted();
6441}
Sebastian Redl4c018662009-04-27 21:33:24 +00006442
6443static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
6444 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
6445 ++CI) {
6446 Stmt *SubStmt = *CI;
6447 if (!SubStmt)
6448 continue;
6449 if (isa<ReturnStmt>(SubStmt))
6450 Self.Diag(SubStmt->getSourceRange().getBegin(),
6451 diag::err_return_in_constructor_handler);
6452 if (!isa<Expr>(SubStmt))
6453 SearchForReturnInStmt(Self, SubStmt);
6454 }
6455}
6456
6457void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
6458 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
6459 CXXCatchStmt *Handler = TryBlock->getHandler(I);
6460 SearchForReturnInStmt(*this, Handler);
6461 }
6462}
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006463
Mike Stump11289f42009-09-09 15:08:12 +00006464bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006465 const CXXMethodDecl *Old) {
John McCall9dd450b2009-09-21 23:43:11 +00006466 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
6467 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006468
Chandler Carruth284bb2e2010-02-15 11:53:20 +00006469 if (Context.hasSameType(NewTy, OldTy) ||
6470 NewTy->isDependentType() || OldTy->isDependentType())
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006471 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006472
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006473 // Check if the return types are covariant
6474 QualType NewClassTy, OldClassTy;
Mike Stump11289f42009-09-09 15:08:12 +00006475
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006476 /// Both types must be pointers or references to classes.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006477 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
6478 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006479 NewClassTy = NewPT->getPointeeType();
6480 OldClassTy = OldPT->getPointeeType();
6481 }
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006482 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
6483 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
6484 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
6485 NewClassTy = NewRT->getPointeeType();
6486 OldClassTy = OldRT->getPointeeType();
6487 }
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006488 }
6489 }
Mike Stump11289f42009-09-09 15:08:12 +00006490
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006491 // The return types aren't either both pointers or references to a class type.
6492 if (NewClassTy.isNull()) {
Mike Stump11289f42009-09-09 15:08:12 +00006493 Diag(New->getLocation(),
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006494 diag::err_different_return_type_for_overriding_virtual_function)
6495 << New->getDeclName() << NewTy << OldTy;
6496 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
Mike Stump11289f42009-09-09 15:08:12 +00006497
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006498 return true;
6499 }
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006500
Anders Carlssone60365b2009-12-31 18:34:24 +00006501 // C++ [class.virtual]p6:
6502 // If the return type of D::f differs from the return type of B::f, the
6503 // class type in the return type of D::f shall be complete at the point of
6504 // declaration of D::f or shall be the class type D.
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006505 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
6506 if (!RT->isBeingDefined() &&
6507 RequireCompleteType(New->getLocation(), NewClassTy,
6508 PDiag(diag::err_covariant_return_incomplete)
6509 << New->getDeclName()))
Anders Carlssone60365b2009-12-31 18:34:24 +00006510 return true;
Anders Carlsson0c9dd842009-12-31 18:54:35 +00006511 }
Anders Carlssone60365b2009-12-31 18:34:24 +00006512
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006513 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006514 // Check if the new class derives from the old class.
6515 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
6516 Diag(New->getLocation(),
6517 diag::err_covariant_return_not_derived)
6518 << New->getDeclName() << NewTy << OldTy;
6519 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6520 return true;
6521 }
Mike Stump11289f42009-09-09 15:08:12 +00006522
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006523 // Check if we the conversion from derived to base is valid.
John McCall1064d7e2010-03-16 05:22:47 +00006524 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
Anders Carlsson7afe4242010-04-24 17:11:09 +00006525 diag::err_covariant_return_inaccessible_base,
6526 diag::err_covariant_return_ambiguous_derived_to_base_conv,
6527 // FIXME: Should this point to the return type?
6528 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006529 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6530 return true;
6531 }
6532 }
Mike Stump11289f42009-09-09 15:08:12 +00006533
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006534 // The qualifiers of the return types must be the same.
Anders Carlsson7caa4cb2010-01-22 17:37:20 +00006535 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006536 Diag(New->getLocation(),
6537 diag::err_covariant_return_type_different_qualifications)
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006538 << New->getDeclName() << NewTy << OldTy;
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006539 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6540 return true;
6541 };
Mike Stump11289f42009-09-09 15:08:12 +00006542
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006543
6544 // The new class type must have the same or less qualifiers as the old type.
6545 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
6546 Diag(New->getLocation(),
6547 diag::err_covariant_return_type_class_type_more_qualified)
6548 << New->getDeclName() << NewTy << OldTy;
6549 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6550 return true;
6551 };
Mike Stump11289f42009-09-09 15:08:12 +00006552
Anders Carlsson8fb0b8a2009-05-14 19:52:19 +00006553 return false;
Anders Carlssonf2a2e332009-05-14 01:09:04 +00006554}
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006555
Alexis Hunt96d5c762009-11-21 08:43:09 +00006556bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
6557 const CXXMethodDecl *Old)
6558{
6559 if (Old->hasAttr<FinalAttr>()) {
6560 Diag(New->getLocation(), diag::err_final_function_overridden)
6561 << New->getDeclName();
6562 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
6563 return true;
6564 }
6565
6566 return false;
6567}
6568
Douglas Gregor21920e372009-12-01 17:24:26 +00006569/// \brief Mark the given method pure.
6570///
6571/// \param Method the method to be marked pure.
6572///
6573/// \param InitRange the source range that covers the "0" initializer.
6574bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
6575 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
6576 Method->setPure();
Douglas Gregor21920e372009-12-01 17:24:26 +00006577 return false;
6578 }
6579
6580 if (!Method->isInvalidDecl())
6581 Diag(Method->getLocation(), diag::err_non_virtual_pure)
6582 << Method->getDeclName() << InitRange;
6583 return true;
6584}
6585
John McCall1f4ee7b2009-12-19 09:28:58 +00006586/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
6587/// an initializer for the out-of-line declaration 'Dcl'. The scope
6588/// is a fresh scope pushed for just this purpose.
6589///
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006590/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6591/// static data member of class X, names should be looked up in the scope of
6592/// class X.
John McCall48871652010-08-21 09:40:31 +00006593void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006594 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006595 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006596
John McCall1f4ee7b2009-12-19 09:28:58 +00006597 // We should only get called for declarations with scope specifiers, like:
6598 // int foo::bar;
6599 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006600 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006601}
6602
6603/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
John McCall48871652010-08-21 09:40:31 +00006604/// initializer for the out-of-line declaration 'D'.
6605void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006606 // If there is no declaration, there was an error parsing it.
John McCall1f4ee7b2009-12-19 09:28:58 +00006607 if (D == 0) return;
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006608
John McCall1f4ee7b2009-12-19 09:28:58 +00006609 assert(D->isOutOfLine());
John McCall6df5fef2009-12-19 10:49:29 +00006610 ExitDeclaratorContext(S);
Argyrios Kyrtzidis3df19782009-06-17 22:50:06 +00006611}
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006612
6613/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
6614/// C++ if/switch/while/for statement.
6615/// e.g: "if (int x = f()) {...}"
John McCall48871652010-08-21 09:40:31 +00006616DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006617 // C++ 6.4p2:
6618 // The declarator shall not specify a function or an array.
6619 // The type-specifier-seq shall not contain typedef and shall not declare a
6620 // new class or enumeration.
6621 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6622 "Parser allowed 'typedef' as storage class of condition decl.");
6623
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006624 TagDecl *OwnedTag = 0;
John McCall8cb7bdf2010-06-04 23:28:52 +00006625 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
6626 QualType Ty = TInfo->getType();
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006627
6628 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
6629 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
6630 // would be created and CXXConditionDeclExpr wants a VarDecl.
6631 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
6632 << D.getSourceRange();
6633 return DeclResult();
6634 } else if (OwnedTag && OwnedTag->isDefinition()) {
6635 // The type-specifier-seq shall not declare a new class or enumeration.
6636 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
6637 }
6638
John McCall48871652010-08-21 09:40:31 +00006639 Decl *Dcl = ActOnDeclarator(S, D);
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006640 if (!Dcl)
6641 return DeclResult();
6642
Douglas Gregor7bab5ff2009-11-25 00:27:52 +00006643 return Dcl;
6644}
Anders Carlssonf98849e2009-12-02 17:15:43 +00006645
Douglas Gregor88d292c2010-05-13 16:44:06 +00006646void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
6647 bool DefinitionRequired) {
6648 // Ignore any vtable uses in unevaluated operands or for classes that do
6649 // not have a vtable.
6650 if (!Class->isDynamicClass() || Class->isDependentContext() ||
6651 CurContext->isDependentContext() ||
6652 ExprEvalContexts.back().Context == Unevaluated)
Rafael Espindolae7113ca2010-03-10 02:19:29 +00006653 return;
6654
Douglas Gregor88d292c2010-05-13 16:44:06 +00006655 // Try to insert this class into the map.
6656 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6657 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
6658 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
6659 if (!Pos.second) {
Daniel Dunbar53217762010-05-25 00:33:13 +00006660 // If we already had an entry, check to see if we are promoting this vtable
6661 // to required a definition. If so, we need to reappend to the VTableUses
6662 // list, since we may have already processed the first entry.
6663 if (DefinitionRequired && !Pos.first->second) {
6664 Pos.first->second = true;
6665 } else {
6666 // Otherwise, we can early exit.
6667 return;
6668 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006669 }
6670
6671 // Local classes need to have their virtual members marked
6672 // immediately. For all other classes, we mark their virtual members
6673 // at the end of the translation unit.
6674 if (Class->isLocalClass())
6675 MarkVirtualMembersReferenced(Loc, Class);
Daniel Dunbar0547ad32010-05-11 21:32:35 +00006676 else
Douglas Gregor88d292c2010-05-13 16:44:06 +00006677 VTableUses.push_back(std::make_pair(Class, Loc));
Douglas Gregor0c4aad12010-05-11 20:24:17 +00006678}
6679
Douglas Gregor88d292c2010-05-13 16:44:06 +00006680bool Sema::DefineUsedVTables() {
6681 // If any dynamic classes have their key function defined within
6682 // this translation unit, then those vtables are considered "used" and must
6683 // be emitted.
6684 for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
6685 if (const CXXMethodDecl *KeyFunction
6686 = Context.getKeyFunction(DynamicClasses[I])) {
6687 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006688 if (KeyFunction->hasBody(Definition))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006689 MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
6690 }
6691 }
6692
6693 if (VTableUses.empty())
Anders Carlsson82fccd02009-12-07 08:24:59 +00006694 return false;
6695
Douglas Gregor88d292c2010-05-13 16:44:06 +00006696 // Note: The VTableUses vector could grow as a result of marking
6697 // the members of a class as "used", so we check the size each
6698 // time through the loop and prefer indices (with are stable) to
6699 // iterators (which are not).
6700 for (unsigned I = 0; I != VTableUses.size(); ++I) {
Daniel Dunbar105ce6d2010-05-25 00:32:58 +00006701 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
Douglas Gregor88d292c2010-05-13 16:44:06 +00006702 if (!Class)
6703 continue;
6704
6705 SourceLocation Loc = VTableUses[I].second;
6706
6707 // If this class has a key function, but that key function is
6708 // defined in another translation unit, we don't need to emit the
6709 // vtable even though we're using it.
6710 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006711 if (KeyFunction && !KeyFunction->hasBody()) {
Douglas Gregor88d292c2010-05-13 16:44:06 +00006712 switch (KeyFunction->getTemplateSpecializationKind()) {
6713 case TSK_Undeclared:
6714 case TSK_ExplicitSpecialization:
6715 case TSK_ExplicitInstantiationDeclaration:
6716 // The key function is in another translation unit.
6717 continue;
6718
6719 case TSK_ExplicitInstantiationDefinition:
6720 case TSK_ImplicitInstantiation:
6721 // We will be instantiating the key function.
6722 break;
6723 }
6724 } else if (!KeyFunction) {
6725 // If we have a class with no key function that is the subject
6726 // of an explicit instantiation declaration, suppress the
6727 // vtable; it will live with the explicit instantiation
6728 // definition.
6729 bool IsExplicitInstantiationDeclaration
6730 = Class->getTemplateSpecializationKind()
6731 == TSK_ExplicitInstantiationDeclaration;
6732 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
6733 REnd = Class->redecls_end();
6734 R != REnd; ++R) {
6735 TemplateSpecializationKind TSK
6736 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
6737 if (TSK == TSK_ExplicitInstantiationDeclaration)
6738 IsExplicitInstantiationDeclaration = true;
6739 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6740 IsExplicitInstantiationDeclaration = false;
6741 break;
6742 }
6743 }
6744
6745 if (IsExplicitInstantiationDeclaration)
6746 continue;
6747 }
6748
6749 // Mark all of the virtual members of this class as referenced, so
6750 // that we can build a vtable. Then, tell the AST consumer that a
6751 // vtable for this class is required.
6752 MarkVirtualMembersReferenced(Loc, Class);
6753 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
6754 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
6755
6756 // Optionally warn if we're emitting a weak vtable.
6757 if (Class->getLinkage() == ExternalLinkage &&
6758 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00006759 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
Douglas Gregor88d292c2010-05-13 16:44:06 +00006760 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
6761 }
Anders Carlssonf98849e2009-12-02 17:15:43 +00006762 }
Douglas Gregor88d292c2010-05-13 16:44:06 +00006763 VTableUses.clear();
6764
Anders Carlsson82fccd02009-12-07 08:24:59 +00006765 return true;
Anders Carlssonf98849e2009-12-02 17:15:43 +00006766}
Anders Carlsson82fccd02009-12-07 08:24:59 +00006767
Rafael Espindola5b334082010-03-26 00:36:59 +00006768void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
6769 const CXXRecordDecl *RD) {
Anders Carlsson82fccd02009-12-07 08:24:59 +00006770 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
6771 e = RD->method_end(); i != e; ++i) {
6772 CXXMethodDecl *MD = *i;
6773
6774 // C++ [basic.def.odr]p2:
6775 // [...] A virtual member function is used if it is not pure. [...]
6776 if (MD->isVirtual() && !MD->isPure())
6777 MarkDeclarationReferenced(Loc, MD);
6778 }
Rafael Espindola5b334082010-03-26 00:36:59 +00006779
6780 // Only classes that have virtual bases need a VTT.
6781 if (RD->getNumVBases() == 0)
6782 return;
6783
6784 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
6785 e = RD->bases_end(); i != e; ++i) {
6786 const CXXRecordDecl *Base =
6787 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Rafael Espindola5b334082010-03-26 00:36:59 +00006788 if (Base->getNumVBases() == 0)
6789 continue;
6790 MarkVirtualMembersReferenced(Loc, Base);
6791 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006792}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006793
6794/// SetIvarInitializers - This routine builds initialization ASTs for the
6795/// Objective-C implementation whose ivars need be initialized.
6796void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
6797 if (!getLangOptions().CPlusPlus)
6798 return;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00006799 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006800 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
6801 CollectIvarsToConstructOrDestruct(OID, ivars);
6802 if (ivars.empty())
6803 return;
6804 llvm::SmallVector<CXXBaseOrMemberInitializer*, 32> AllToInit;
6805 for (unsigned i = 0; i < ivars.size(); i++) {
6806 FieldDecl *Field = ivars[i];
Douglas Gregor527786e2010-05-20 02:24:22 +00006807 if (Field->isInvalidDecl())
6808 continue;
6809
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006810 CXXBaseOrMemberInitializer *Member;
6811 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
6812 InitializationKind InitKind =
6813 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
6814
6815 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
John McCalldadc5752010-08-24 06:29:42 +00006816 ExprResult MemberInit =
John McCallfaf5fb42010-08-26 23:41:50 +00006817 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
John McCallb268a282010-08-23 23:25:46 +00006818 MemberInit = MaybeCreateCXXExprWithTemporaries(MemberInit.get());
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006819 // Note, MemberInit could actually come back empty if no initialization
6820 // is required (e.g., because it would call a trivial default constructor)
6821 if (!MemberInit.get() || MemberInit.isInvalid())
6822 continue;
6823
6824 Member =
6825 new (Context) CXXBaseOrMemberInitializer(Context,
6826 Field, SourceLocation(),
6827 SourceLocation(),
6828 MemberInit.takeAs<Expr>(),
6829 SourceLocation());
6830 AllToInit.push_back(Member);
Douglas Gregor527786e2010-05-20 02:24:22 +00006831
6832 // Be sure that the destructor is accessible and is marked as referenced.
6833 if (const RecordType *RecordTy
6834 = Context.getBaseElementType(Field->getType())
6835 ->getAs<RecordType>()) {
6836 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
Douglas Gregore71edda2010-07-01 22:47:18 +00006837 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
Douglas Gregor527786e2010-05-20 02:24:22 +00006838 MarkDeclarationReferenced(Field->getLocation(), Destructor);
6839 CheckDestructorAccess(Field->getLocation(), Destructor,
6840 PDiag(diag::err_access_dtor_ivar)
6841 << Context.getBaseElementType(Field->getType()));
6842 }
6843 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00006844 }
6845 ObjCImplementation->setIvarInitializers(Context,
6846 AllToInit.data(), AllToInit.size());
6847 }
6848}