blob: c30b974af9d998c4c779d1fb1334414782dd040e [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor7ad83902008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Anders Carlsson8211eff2009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor02189362008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000021#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000024#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000025#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000026#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000027
28using namespace clang;
29
Chris Lattner8123a952008-04-10 02:22:51 +000030//===----------------------------------------------------------------------===//
31// CheckDefaultArgumentVisitor
32//===----------------------------------------------------------------------===//
33
Chris Lattner9e979552008-04-12 23:52:44 +000034namespace {
35 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
36 /// the default argument of a parameter to determine whether it
37 /// contains any ill-formed subexpressions. For example, this will
38 /// diagnose the use of local variables or parameters within the
39 /// default argument expression.
40 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000041 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000042 Expr *DefaultArg;
43 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000044
Chris Lattner9e979552008-04-12 23:52:44 +000045 public:
46 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
47 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000048
Chris Lattner9e979552008-04-12 23:52:44 +000049 bool VisitExpr(Expr *Node);
50 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000051 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000052 };
Chris Lattner8123a952008-04-10 02:22:51 +000053
Chris Lattner9e979552008-04-12 23:52:44 +000054 /// VisitExpr - Visit all of the children of this expression.
55 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
56 bool IsInvalid = false;
Chris Lattnerb77792e2008-07-26 22:17:49 +000057 for (Stmt::child_iterator I = Node->child_begin(),
58 E = Node->child_end(); I != E; ++I)
59 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000060 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000061 }
62
Chris Lattner9e979552008-04-12 23:52:44 +000063 /// VisitDeclRefExpr - Visit a reference to a declaration, to
64 /// determine whether this declaration can be used in the default
65 /// argument expression.
66 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000067 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000068 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
69 // C++ [dcl.fct.default]p9
70 // Default arguments are evaluated each time the function is
71 // called. The order of evaluation of function arguments is
72 // unspecified. Consequently, parameters of a function shall not
73 // be used in default argument expressions, even if they are not
74 // evaluated. Parameters of a function declared before a default
75 // argument expression are in scope and can hide namespace and
76 // class member names.
77 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000078 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000079 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000080 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000081 // C++ [dcl.fct.default]p7
82 // Local variables shall not be used in default argument
83 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000084 if (VDecl->isBlockVarDecl())
85 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000086 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000087 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000088 }
Chris Lattner8123a952008-04-10 02:22:51 +000089
Douglas Gregor3996f232008-11-04 13:41:56 +000090 return false;
91 }
Chris Lattner9e979552008-04-12 23:52:44 +000092
Douglas Gregor796da182008-11-04 14:32:21 +000093 /// VisitCXXThisExpr - Visit a C++ "this" expression.
94 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
95 // C++ [dcl.fct.default]p8:
96 // The keyword this shall not be used in a default argument of a
97 // member function.
98 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_this)
100 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000101 }
Chris Lattner8123a952008-04-10 02:22:51 +0000102}
103
Anders Carlssoned961f92009-08-25 02:29:20 +0000104bool
105Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
106 SourceLocation EqualLoc)
107{
108 QualType ParamType = Param->getType();
109
110 Expr *Arg = (Expr *)DefaultArg.get();
111
112 // C++ [dcl.fct.default]p5
113 // A default argument expression is implicitly converted (clause
114 // 4) to the parameter type. The default argument expression has
115 // the same semantic constraints as the initializer expression in
116 // a declaration of a variable of the parameter type, using the
117 // copy-initialization semantics (8.5).
118 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
119 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000120 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000121
122 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
123
124 // Okay: add the default argument to the parameter
125 Param->setDefaultArg(Arg);
126
127 DefaultArg.release();
128
Anders Carlsson9351c172009-08-25 03:18:48 +0000129 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000130}
131
Chris Lattner8123a952008-04-10 02:22:51 +0000132/// ActOnParamDefaultArgument - Check whether the default argument
133/// provided for a function parameter is well-formed. If so, attach it
134/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000135void
Chris Lattnerb28317a2009-03-28 19:18:32 +0000136Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000137 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000138 if (!param || !defarg.get())
139 return;
140
Chris Lattnerb28317a2009-03-28 19:18:32 +0000141 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000142 UnparsedDefaultArgLocs.erase(Param);
143
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000144 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000145 QualType ParamType = Param->getType();
146
147 // Default arguments are only permitted in C++
148 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000149 Diag(EqualLoc, diag::err_param_default_argument)
150 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000151 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000152 return;
153 }
154
Anders Carlsson66e30672009-08-25 01:02:06 +0000155 // Check that the default argument is well-formed
156 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
157 if (DefaultArgChecker.Visit(DefaultArg.get())) {
158 Param->setInvalidDecl();
159 return;
160 }
161
Anders Carlssoned961f92009-08-25 02:29:20 +0000162 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000163}
164
Douglas Gregor61366e92008-12-24 00:01:03 +0000165/// ActOnParamUnparsedDefaultArgument - We've seen a default
166/// argument for a function parameter, but we can't parse it yet
167/// because we're inside a class definition. Note that this default
168/// argument will be parsed later.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000169void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000170 SourceLocation EqualLoc,
171 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000172 if (!param)
173 return;
174
Chris Lattnerb28317a2009-03-28 19:18:32 +0000175 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000176 if (Param)
177 Param->setUnparsedDefaultArg();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000178
179 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000180}
181
Douglas Gregor72b505b2008-12-16 21:30:33 +0000182/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
183/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000184void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000185 if (!param)
186 return;
187
Anders Carlsson5e300d12009-06-12 16:51:40 +0000188 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
189
190 Param->setInvalidDecl();
191
192 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000193}
194
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000195/// CheckExtraCXXDefaultArguments - Check for any extra default
196/// arguments in the declarator, which is not a function declaration
197/// or definition and therefore is not permitted to have default
198/// arguments. This routine should be invoked for every declarator
199/// that is not a function declaration or definition.
200void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
201 // C++ [dcl.fct.default]p3
202 // A default argument expression shall be specified only in the
203 // parameter-declaration-clause of a function declaration or in a
204 // template-parameter (14.1). It shall not be specified for a
205 // parameter pack. If it is specified in a
206 // parameter-declaration-clause, it shall not occur within a
207 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000208 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000209 DeclaratorChunk &chunk = D.getTypeObject(i);
210 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000211 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
212 ParmVarDecl *Param =
213 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000214 if (Param->hasUnparsedDefaultArg()) {
215 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000216 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
217 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
218 delete Toks;
219 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000220 } else if (Param->getDefaultArg()) {
221 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
222 << Param->getDefaultArg()->getSourceRange();
223 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000224 }
225 }
226 }
227 }
228}
229
Chris Lattner3d1cee32008-04-08 05:04:30 +0000230// MergeCXXFunctionDecl - Merge two declarations of the same C++
231// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000232// type. Subroutine of MergeFunctionDecl. Returns true if there was an
233// error, false otherwise.
234bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
235 bool Invalid = false;
236
Chris Lattner3d1cee32008-04-08 05:04:30 +0000237 // C++ [dcl.fct.default]p4:
238 //
239 // For non-template functions, default arguments can be added in
240 // later declarations of a function in the same
241 // scope. Declarations in different scopes have completely
242 // distinct sets of default arguments. That is, declarations in
243 // inner scopes do not acquire default arguments from
244 // declarations in outer scopes, and vice versa. In a given
245 // function declaration, all parameters subsequent to a
246 // parameter with a default argument shall have default
247 // arguments supplied in this or previous declarations. A
248 // default argument shall not be redefined by a later
249 // declaration (not even to the same value).
250 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
251 ParmVarDecl *OldParam = Old->getParamDecl(p);
252 ParmVarDecl *NewParam = New->getParamDecl(p);
253
254 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
255 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000256 diag::err_param_default_argument_redefinition)
257 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000258 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000259 Invalid = true;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000260 } else if (OldParam->getDefaultArg()) {
261 // Merge the old default argument into the new parameter
262 NewParam->setDefaultArg(OldParam->getDefaultArg());
263 }
264 }
265
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000266 if (CheckEquivalentExceptionSpec(
267 Old->getType()->getAsFunctionProtoType(), Old->getLocation(),
268 New->getType()->getAsFunctionProtoType(), New->getLocation())) {
269 Invalid = true;
270 }
271
Douglas Gregorcda9c672009-02-16 17:45:42 +0000272 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000273}
274
275/// CheckCXXDefaultArguments - Verify that the default arguments for a
276/// function declaration are well-formed according to C++
277/// [dcl.fct.default].
278void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
279 unsigned NumParams = FD->getNumParams();
280 unsigned p;
281
282 // Find first parameter with a default argument
283 for (p = 0; p < NumParams; ++p) {
284 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000285 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000286 break;
287 }
288
289 // C++ [dcl.fct.default]p4:
290 // In a given function declaration, all parameters
291 // subsequent to a parameter with a default argument shall
292 // have default arguments supplied in this or previous
293 // declarations. A default argument shall not be redefined
294 // by a later declaration (not even to the same value).
295 unsigned LastMissingDefaultArg = 0;
296 for(; p < NumParams; ++p) {
297 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000298 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000299 if (Param->isInvalidDecl())
300 /* We already complained about this parameter. */;
301 else if (Param->getIdentifier())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000302 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000303 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000304 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000305 else
306 Diag(Param->getLocation(),
307 diag::err_param_default_argument_missing);
308
309 LastMissingDefaultArg = p;
310 }
311 }
312
313 if (LastMissingDefaultArg > 0) {
314 // Some default arguments were missing. Clear out all of the
315 // default arguments up to (and including) the last missing
316 // default argument, so that we leave the function parameters
317 // in a semantically valid state.
318 for (p = 0; p <= LastMissingDefaultArg; ++p) {
319 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000320 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000321 if (!Param->hasUnparsedDefaultArg())
322 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000323 Param->setDefaultArg(0);
324 }
325 }
326 }
327}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000328
Douglas Gregorb48fe382008-10-31 09:07:45 +0000329/// isCurrentClassName - Determine whether the identifier II is the
330/// name of the class type currently being defined. In the case of
331/// nested classes, this will only return true if II is the name of
332/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000333bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
334 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000335 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000336 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000337 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000338 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
339 } else
340 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
341
342 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000343 return &II == CurDecl->getIdentifier();
344 else
345 return false;
346}
347
Douglas Gregor2943aed2009-03-03 04:44:36 +0000348/// \brief Check the validity of a C++ base class specifier.
349///
350/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
351/// and returns NULL otherwise.
352CXXBaseSpecifier *
353Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
354 SourceRange SpecifierRange,
355 bool Virtual, AccessSpecifier Access,
356 QualType BaseType,
357 SourceLocation BaseLoc) {
358 // C++ [class.union]p1:
359 // A union shall not have base classes.
360 if (Class->isUnion()) {
361 Diag(Class->getLocation(), diag::err_base_clause_on_union)
362 << SpecifierRange;
363 return 0;
364 }
365
366 if (BaseType->isDependentType())
Fariborz Jahanian71c6e712009-07-22 17:41:53 +0000367 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000368 Class->getTagKind() == RecordDecl::TK_class,
369 Access, BaseType);
370
371 // Base specifiers must be record types.
372 if (!BaseType->isRecordType()) {
373 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
374 return 0;
375 }
376
377 // C++ [class.union]p1:
378 // A union shall not be used as a base class.
379 if (BaseType->isUnionType()) {
380 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
381 return 0;
382 }
383
384 // C++ [class.derived]p2:
385 // The class-name in a base-specifier shall not be an incompletely
386 // defined class.
Douglas Gregor86447ec2009-03-09 16:13:40 +0000387 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
Douglas Gregor26dce442009-03-10 00:06:19 +0000388 SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000389 return 0;
390
Eli Friedman1d954f62009-08-15 21:55:26 +0000391 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000392 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000393 assert(BaseDecl && "Record type has no declaration");
394 BaseDecl = BaseDecl->getDefinition(Context);
395 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000396 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
397 assert(CXXBaseDecl && "Base type is not a C++ type");
398 if (!CXXBaseDecl->isEmpty())
399 Class->setEmpty(false);
400 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000401 Class->setPolymorphic(true);
402
403 // C++ [dcl.init.aggr]p1:
404 // An aggregate is [...] a class with [...] no base classes [...].
405 Class->setAggregate(false);
406 Class->setPOD(false);
407
Anders Carlsson347ba892009-04-16 00:08:20 +0000408 if (Virtual) {
409 // C++ [class.ctor]p5:
410 // A constructor is trivial if its class has no virtual base classes.
411 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000412
413 // C++ [class.copy]p6:
414 // A copy constructor is trivial if its class has no virtual base classes.
415 Class->setHasTrivialCopyConstructor(false);
416
417 // C++ [class.copy]p11:
418 // A copy assignment operator is trivial if its class has no virtual
419 // base classes.
420 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000421
422 // C++0x [meta.unary.prop] is_empty:
423 // T is a class type, but not a union type, with ... no virtual base
424 // classes
425 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000426 } else {
427 // C++ [class.ctor]p5:
428 // A constructor is trivial if all the direct base classes of its
429 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000430 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
431 Class->setHasTrivialConstructor(false);
432
433 // C++ [class.copy]p6:
434 // A copy constructor is trivial if all the direct base classes of its
435 // class have trivial copy constructors.
436 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
437 Class->setHasTrivialCopyConstructor(false);
438
439 // C++ [class.copy]p11:
440 // A copy assignment operator is trivial if all the direct base classes
441 // of its class have trivial copy assignment operators.
442 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
443 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000444 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000445
446 // C++ [class.ctor]p3:
447 // A destructor is trivial if all the direct base classes of its class
448 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000449 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
450 Class->setHasTrivialDestructor(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000451
Douglas Gregor2943aed2009-03-03 04:44:36 +0000452 // Create the base specifier.
453 // FIXME: Allocate via ASTContext?
Fariborz Jahanian71c6e712009-07-22 17:41:53 +0000454 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000455 Class->getTagKind() == RecordDecl::TK_class,
456 Access, BaseType);
457}
458
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000459/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
460/// one entry in the base class list of a class specifier, for
461/// example:
462/// class foo : public bar, virtual private baz {
463/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000464Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000465Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000466 bool Virtual, AccessSpecifier Access,
467 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000468 if (!classdecl)
469 return true;
470
Douglas Gregor40808ce2009-03-09 23:48:35 +0000471 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000472 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000473 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000474 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
475 Virtual, Access,
476 BaseType, BaseLoc))
477 return BaseSpec;
478
479 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000480}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000481
Douglas Gregor2943aed2009-03-03 04:44:36 +0000482/// \brief Performs the actual work of attaching the given base class
483/// specifiers to a C++ class.
484bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
485 unsigned NumBases) {
486 if (NumBases == 0)
487 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000488
489 // Used to keep track of which base types we have already seen, so
490 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000491 // that the key is always the unqualified canonical type of the base
492 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000493 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
494
495 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000496 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000497 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000498 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000499 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000500 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000501 NewBaseType = NewBaseType.getUnqualifiedType();
502
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000503 if (KnownBaseTypes[NewBaseType]) {
504 // C++ [class.mi]p3:
505 // A class shall not be specified as a direct base class of a
506 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000507 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000508 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000509 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000510 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000511
512 // Delete the duplicate base class specifier; we're going to
513 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000514 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000515
516 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000517 } else {
518 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000519 KnownBaseTypes[NewBaseType] = Bases[idx];
520 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000521 }
522 }
523
524 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000525 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000526
527 // Delete the remaining (good) base class specifiers, since their
528 // data has been copied into the CXXRecordDecl.
529 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000530 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000531
532 return Invalid;
533}
534
535/// ActOnBaseSpecifiers - Attach the given base specifiers to the
536/// class, after checking whether there are any duplicate base
537/// classes.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000538void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000539 unsigned NumBases) {
540 if (!ClassDecl || !Bases || !NumBases)
541 return;
542
543 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000544 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000545 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000546}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000547
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000548//===----------------------------------------------------------------------===//
549// C++ class member Handling
550//===----------------------------------------------------------------------===//
551
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000552/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
553/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
554/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000555/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000556Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000557Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000558 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000559 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000560 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000561 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000562 Expr *BitWidth = static_cast<Expr*>(BW);
563 Expr *Init = static_cast<Expr*>(InitExpr);
564 SourceLocation Loc = D.getIdentifierLoc();
565
Sebastian Redl669d5d72008-11-14 23:42:31 +0000566 bool isFunc = D.isFunctionDeclarator();
567
John McCall67d1a672009-08-06 02:15:43 +0000568 assert(!DS.isFriendSpecified());
569
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000570 // C++ 9.2p6: A member shall not be declared to have automatic storage
571 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000572 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
573 // data members and cannot be applied to names declared const or static,
574 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000575 switch (DS.getStorageClassSpec()) {
576 case DeclSpec::SCS_unspecified:
577 case DeclSpec::SCS_typedef:
578 case DeclSpec::SCS_static:
579 // FALL THROUGH.
580 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000581 case DeclSpec::SCS_mutable:
582 if (isFunc) {
583 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000584 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000585 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000586 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
587
Sebastian Redla11f42f2008-11-17 23:24:37 +0000588 // FIXME: It would be nicer if the keyword was ignored only for this
589 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000590 D.getMutableDeclSpec().ClearStorageClassSpecs();
591 } else {
592 QualType T = GetTypeForDeclarator(D, S);
593 diag::kind err = static_cast<diag::kind>(0);
594 if (T->isReferenceType())
595 err = diag::err_mutable_reference;
596 else if (T.isConstQualified())
597 err = diag::err_mutable_const;
598 if (err != 0) {
599 if (DS.getStorageClassSpecLoc().isValid())
600 Diag(DS.getStorageClassSpecLoc(), err);
601 else
602 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000603 // FIXME: It would be nicer if the keyword was ignored only for this
604 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000605 D.getMutableDeclSpec().ClearStorageClassSpecs();
606 }
607 }
608 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000609 default:
610 if (DS.getStorageClassSpecLoc().isValid())
611 Diag(DS.getStorageClassSpecLoc(),
612 diag::err_storageclass_invalid_for_member);
613 else
614 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
615 D.getMutableDeclSpec().ClearStorageClassSpecs();
616 }
617
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000618 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000619 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000620 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000621 // Check also for this case:
622 //
623 // typedef int f();
624 // f a;
625 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000626 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000627 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000628 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000629
Sebastian Redl669d5d72008-11-14 23:42:31 +0000630 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
631 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000632 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000633
634 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000635 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000636 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000637 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
638 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000639 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000640 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000641 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
642 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000643 if (!Member) {
644 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000645 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000646 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000647
648 // Non-instance-fields can't have a bitfield.
649 if (BitWidth) {
650 if (Member->isInvalidDecl()) {
651 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000652 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000653 // C++ 9.6p3: A bit-field shall not be a static member.
654 // "static member 'A' cannot be a bit-field"
655 Diag(Loc, diag::err_static_not_bitfield)
656 << Name << BitWidth->getSourceRange();
657 } else if (isa<TypedefDecl>(Member)) {
658 // "typedef member 'x' cannot be a bit-field"
659 Diag(Loc, diag::err_typedef_not_bitfield)
660 << Name << BitWidth->getSourceRange();
661 } else {
662 // A function typedef ("typedef int f(); f a;").
663 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
664 Diag(Loc, diag::err_not_integral_type_bitfield)
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000665 << Name << cast<ValueDecl>(Member)->getType()
666 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000667 }
668
669 DeleteExpr(BitWidth);
670 BitWidth = 0;
671 Member->setInvalidDecl();
672 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000673
674 Member->setAccess(AS);
Douglas Gregor37b372b2009-08-20 22:52:58 +0000675
676 // If we have declared a member function template, set the access of the
677 // templated declaration as well.
678 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
679 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000680 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000681
Douglas Gregor10bd3682008-11-17 22:58:34 +0000682 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000683
Douglas Gregor021c3b32009-03-11 23:00:04 +0000684 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000685 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000686 if (Deleted) // FIXME: Source location is not very good.
687 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000688
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000689 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000690 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000691 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000692 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000693 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000694}
695
Douglas Gregor7ad83902008-11-05 04:29:56 +0000696/// ActOnMemInitializer - Handle a C++ member initializer.
697Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000698Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000699 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000700 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000701 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000702 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000703 SourceLocation IdLoc,
704 SourceLocation LParenLoc,
705 ExprTy **Args, unsigned NumArgs,
706 SourceLocation *CommaLocs,
707 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000708 if (!ConstructorD)
709 return true;
710
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000711 AdjustDeclIfTemplate(ConstructorD);
712
Douglas Gregor7ad83902008-11-05 04:29:56 +0000713 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000714 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000715 if (!Constructor) {
716 // The user wrote a constructor initializer on a function that is
717 // not a C++ constructor. Ignore the error for now, because we may
718 // have more member initializers coming; we'll diagnose it just
719 // once in ActOnMemInitializers.
720 return true;
721 }
722
723 CXXRecordDecl *ClassDecl = Constructor->getParent();
724
725 // C++ [class.base.init]p2:
726 // Names in a mem-initializer-id are looked up in the scope of the
727 // constructor’s class and, if not found in that scope, are looked
728 // up in the scope containing the constructor’s
729 // definition. [Note: if the constructor’s class contains a member
730 // with the same name as a direct or virtual base class of the
731 // class, a mem-initializer-id naming the member or base class and
732 // composed of a single identifier refers to the class member. A
733 // mem-initializer-id for the hidden base class may be specified
734 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000735 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000736 // Look for a member, first.
737 FieldDecl *Member = 0;
738 DeclContext::lookup_result Result
739 = ClassDecl->lookup(MemberOrBase);
740 if (Result.first != Result.second)
741 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000742
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000743 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000744
Eli Friedman59c04372009-07-29 19:44:27 +0000745 if (Member)
746 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
747 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000748 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000749 // It didn't name a member, so see if it names a class.
Fariborz Jahanian96174332009-07-01 19:21:19 +0000750 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
751 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000752 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000753 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
754 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000755
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000756 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000757
Eli Friedman59c04372009-07-29 19:44:27 +0000758 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
759 RParenLoc, ClassDecl);
760}
761
762Sema::MemInitResult
763Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
764 unsigned NumArgs, SourceLocation IdLoc,
765 SourceLocation RParenLoc) {
766 bool HasDependentArg = false;
767 for (unsigned i = 0; i < NumArgs; i++)
768 HasDependentArg |= Args[i]->isTypeDependent();
769
770 CXXConstructorDecl *C = 0;
771 QualType FieldType = Member->getType();
772 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
773 FieldType = Array->getElementType();
774 if (FieldType->isDependentType()) {
775 // Can't check init for dependent type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000776 } else if (FieldType->getAs<RecordType>()) {
Eli Friedman59c04372009-07-29 19:44:27 +0000777 if (!HasDependentArg)
778 C = PerformInitializationByConstructor(
779 FieldType, (Expr **)Args, NumArgs, IdLoc,
780 SourceRange(IdLoc, RParenLoc), Member->getDeclName(), IK_Direct);
781 } else if (NumArgs != 1) {
782 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
783 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
784 } else if (!HasDependentArg) {
785 Expr *NewExp = (Expr*)Args[0];
786 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
787 return true;
788 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +0000789 }
Eli Friedman59c04372009-07-29 19:44:27 +0000790 // FIXME: Perform direct initialization of the member.
791 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
792 NumArgs, C, IdLoc);
793}
794
795Sema::MemInitResult
796Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
797 unsigned NumArgs, SourceLocation IdLoc,
798 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
799 bool HasDependentArg = false;
800 for (unsigned i = 0; i < NumArgs; i++)
801 HasDependentArg |= Args[i]->isTypeDependent();
802
803 if (!BaseType->isDependentType()) {
804 if (!BaseType->isRecordType())
805 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
806 << BaseType << SourceRange(IdLoc, RParenLoc);
807
808 // C++ [class.base.init]p2:
809 // [...] Unless the mem-initializer-id names a nonstatic data
810 // member of the constructor’s class or a direct or virtual base
811 // of that class, the mem-initializer is ill-formed. A
812 // mem-initializer-list can initialize a base class using any
813 // name that denotes that base class type.
814
815 // First, check for a direct base class.
816 const CXXBaseSpecifier *DirectBaseSpec = 0;
817 for (CXXRecordDecl::base_class_const_iterator Base =
818 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
819 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
820 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
821 // We found a direct base of this type. That's what we're
822 // initializing.
823 DirectBaseSpec = &*Base;
824 break;
825 }
826 }
827
828 // Check for a virtual base class.
829 // FIXME: We might be able to short-circuit this if we know in advance that
830 // there are no virtual bases.
831 const CXXBaseSpecifier *VirtualBaseSpec = 0;
832 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
833 // We haven't found a base yet; search the class hierarchy for a
834 // virtual base class.
835 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
836 /*DetectVirtual=*/false);
837 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
838 for (BasePaths::paths_iterator Path = Paths.begin();
839 Path != Paths.end(); ++Path) {
840 if (Path->back().Base->isVirtual()) {
841 VirtualBaseSpec = Path->back().Base;
842 break;
843 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000844 }
845 }
846 }
Eli Friedman59c04372009-07-29 19:44:27 +0000847
848 // C++ [base.class.init]p2:
849 // If a mem-initializer-id is ambiguous because it designates both
850 // a direct non-virtual base class and an inherited virtual base
851 // class, the mem-initializer is ill-formed.
852 if (DirectBaseSpec && VirtualBaseSpec)
853 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
854 << BaseType << SourceRange(IdLoc, RParenLoc);
855 // C++ [base.class.init]p2:
856 // Unless the mem-initializer-id names a nonstatic data membeer of the
857 // constructor's class ot a direst or virtual base of that class, the
858 // mem-initializer is ill-formed.
859 if (!DirectBaseSpec && !VirtualBaseSpec)
860 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
861 << BaseType << ClassDecl->getNameAsCString()
862 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000863 }
864
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +0000865 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +0000866 if (!BaseType->isDependentType() && !HasDependentArg) {
867 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
868 Context.getCanonicalType(BaseType));
869 C = PerformInitializationByConstructor(BaseType, (Expr **)Args, NumArgs,
870 IdLoc, SourceRange(IdLoc, RParenLoc),
871 Name, IK_Direct);
872 }
873
874 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +0000875 NumArgs, C, IdLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000876}
877
Fariborz Jahanian87595e42009-07-23 23:32:59 +0000878void
879Sema::BuildBaseOrMemberInitializers(ASTContext &C,
880 CXXConstructorDecl *Constructor,
881 CXXBaseOrMemberInitializer **Initializers,
882 unsigned NumInitializers
883 ) {
884 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases;
885 llvm::SmallVector<FieldDecl *, 4>Members;
886
887 Constructor->setBaseOrMemberInitializers(C,
888 Initializers, NumInitializers,
889 Bases, Members);
890 for (unsigned int i = 0; i < Bases.size(); i++)
891 Diag(Bases[i]->getSourceRange().getBegin(),
892 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
893 for (unsigned int i = 0; i < Members.size(); i++)
894 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
895 << 1 << Members[i]->getType();
896}
897
Eli Friedman6347f422009-07-21 19:28:10 +0000898static void *GetKeyForTopLevelField(FieldDecl *Field) {
899 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +0000900 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +0000901 if (RT->getDecl()->isAnonymousStructOrUnion())
902 return static_cast<void *>(RT->getDecl());
903 }
904 return static_cast<void *>(Field);
905}
906
Fariborz Jahaniane6494122009-08-11 18:49:54 +0000907static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
908 bool MemberMaybeAnon=false) {
Eli Friedman6347f422009-07-21 19:28:10 +0000909 // For fields injected into the class via declaration of an anonymous union,
910 // use its anonymous union class declaration as the unique key.
911 if (FieldDecl *Field = Member->getMember()) {
Fariborz Jahaniane6494122009-08-11 18:49:54 +0000912 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
913 // data member of the class. Data member used in the initializer list is
914 // in AnonUnionMember field.
915 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
916 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +0000917 if (Field->getDeclContext()->isRecord()) {
918 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
919 if (RD->isAnonymousStructOrUnion())
920 return static_cast<void *>(RD);
921 }
922 return static_cast<void *>(Field);
923 }
924 return static_cast<RecordType *>(Member->getBaseClass());
925}
926
Chris Lattnerb28317a2009-03-28 19:18:32 +0000927void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +0000928 SourceLocation ColonLoc,
929 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000930 if (!ConstructorDecl)
931 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000932
933 AdjustDeclIfTemplate(ConstructorDecl);
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000934
935 CXXConstructorDecl *Constructor
936 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Anders Carlssona7b35212009-03-25 02:58:17 +0000937
938 if (!Constructor) {
939 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
940 return;
941 }
Fariborz Jahanian16dbdce2009-06-30 00:17:27 +0000942 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
Fariborz Jahanian73b85f32009-07-01 23:35:25 +0000943 bool err = false;
Fariborz Jahanian7881a052009-06-29 22:33:26 +0000944 for (unsigned i = 0; i < NumMemInits; i++) {
945 CXXBaseOrMemberInitializer *Member =
946 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
Eli Friedman6347f422009-07-21 19:28:10 +0000947 void *KeyToMember = GetKeyForMember(Member);
Fariborz Jahanian5ac3dfc2009-06-30 21:52:59 +0000948 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
Fariborz Jahanian16dbdce2009-06-30 00:17:27 +0000949 if (!PrevMember) {
Fariborz Jahanian47deacf2009-06-30 00:02:17 +0000950 PrevMember = Member;
Fariborz Jahanian16dbdce2009-06-30 00:17:27 +0000951 continue;
Fariborz Jahanian7881a052009-06-29 22:33:26 +0000952 }
Fariborz Jahanian16dbdce2009-06-30 00:17:27 +0000953 if (FieldDecl *Field = Member->getMember())
954 Diag(Member->getSourceLocation(),
955 diag::error_multiple_mem_initialization)
956 << Field->getNameAsString();
957 else {
958 Type *BaseClass = Member->getBaseClass();
959 assert(BaseClass && "ActOnMemInitializers - neither field or base");
960 Diag(Member->getSourceLocation(),
961 diag::error_multiple_base_initialization)
962 << BaseClass->getDesugaredType(true);
963 }
964 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
965 << 0;
Fariborz Jahanian73b85f32009-07-01 23:35:25 +0000966 err = true;
Fariborz Jahanian7881a052009-06-29 22:33:26 +0000967 }
Fariborz Jahanian87595e42009-07-23 23:32:59 +0000968 if (!err)
969 BuildBaseOrMemberInitializers(Context, Constructor,
970 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
971 NumMemInits);
972
Eli Friedman6347f422009-07-21 19:28:10 +0000973 if (!err && (Diags.getDiagnosticLevel(diag::warn_base_initialized)
974 != Diagnostic::Ignored ||
975 Diags.getDiagnosticLevel(diag::warn_field_initialized)
976 != Diagnostic::Ignored)) {
Fariborz Jahanianeb96e122009-07-09 19:59:47 +0000977 // Also issue warning if order of ctor-initializer list does not match order
978 // of 1) base class declarations and 2) order of non-static data members.
Fariborz Jahanianeb96e122009-07-09 19:59:47 +0000979 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
980
981 CXXRecordDecl *ClassDecl
982 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian40c072f2009-07-10 20:13:23 +0000983 // Push virtual bases before others.
984 for (CXXRecordDecl::base_class_iterator VBase =
985 ClassDecl->vbases_begin(),
986 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Ted Kremenek6217b802009-07-29 21:53:49 +0000987 AllBaseOrMembers.push_back(VBase->getType()->getAs<RecordType>());
Fariborz Jahanian40c072f2009-07-10 20:13:23 +0000988
Fariborz Jahanianeb96e122009-07-09 19:59:47 +0000989 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
Fariborz Jahanian40c072f2009-07-10 20:13:23 +0000990 E = ClassDecl->bases_end(); Base != E; ++Base) {
991 // Virtuals are alread in the virtual base list and are constructed
992 // first.
993 if (Base->isVirtual())
994 continue;
Ted Kremenek6217b802009-07-29 21:53:49 +0000995 AllBaseOrMembers.push_back(Base->getType()->getAs<RecordType>());
Fariborz Jahanian40c072f2009-07-10 20:13:23 +0000996 }
Fariborz Jahanianeb96e122009-07-09 19:59:47 +0000997
998 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
999 E = ClassDecl->field_end(); Field != E; ++Field)
Eli Friedman6347f422009-07-21 19:28:10 +00001000 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001001
1002 int Last = AllBaseOrMembers.size();
1003 int curIndex = 0;
1004 CXXBaseOrMemberInitializer *PrevMember = 0;
1005 for (unsigned i = 0; i < NumMemInits; i++) {
1006 CXXBaseOrMemberInitializer *Member =
1007 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
Fariborz Jahaniane6494122009-08-11 18:49:54 +00001008 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001009
1010 for (; curIndex < Last; curIndex++)
1011 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001012 break;
Eli Friedman6347f422009-07-21 19:28:10 +00001013 if (curIndex == Last) {
1014 assert(PrevMember && "Member not in member list?!");
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001015 // Initializer as specified in ctor-initializer list is out of order.
1016 // Issue a warning diagnostic.
1017 if (PrevMember->isBaseInitializer()) {
1018 // Diagnostics is for an initialized base class.
1019 Type *BaseClass = PrevMember->getBaseClass();
1020 Diag(PrevMember->getSourceLocation(),
1021 diag::warn_base_initialized)
1022 << BaseClass->getDesugaredType(true);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001023 } else {
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001024 FieldDecl *Field = PrevMember->getMember();
1025 Diag(PrevMember->getSourceLocation(),
1026 diag::warn_field_initialized)
1027 << Field->getNameAsString();
1028 }
1029 // Also the note!
1030 if (FieldDecl *Field = Member->getMember())
1031 Diag(Member->getSourceLocation(),
1032 diag::note_fieldorbase_initialized_here) << 0
1033 << Field->getNameAsString();
1034 else {
1035 Type *BaseClass = Member->getBaseClass();
1036 Diag(Member->getSourceLocation(),
1037 diag::note_fieldorbase_initialized_here) << 1
1038 << BaseClass->getDesugaredType(true);
1039 }
Eli Friedman6347f422009-07-21 19:28:10 +00001040 for (curIndex = 0; curIndex < Last; curIndex++)
1041 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1042 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001043 }
1044 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001045 }
1046 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001047}
1048
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001049void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001050 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001051 return;
1052
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001053 AdjustDeclIfTemplate(CDtorDecl);
1054
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001055 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001056 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001057 BuildBaseOrMemberInitializers(Context,
1058 Constructor,
1059 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001060}
1061
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001062namespace {
1063 /// PureVirtualMethodCollector - traverses a class and its superclasses
1064 /// and determines if it has any pure virtual methods.
1065 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1066 ASTContext &Context;
1067
Sebastian Redldfe292d2009-03-22 21:28:55 +00001068 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001069 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001070
1071 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001072 MethodList Methods;
1073
1074 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
1075
1076 public:
1077 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
1078 : Context(Ctx) {
1079
1080 MethodList List;
1081 Collect(RD, List);
1082
1083 // Copy the temporary list to methods, and make sure to ignore any
1084 // null entries.
1085 for (size_t i = 0, e = List.size(); i != e; ++i) {
1086 if (List[i])
1087 Methods.push_back(List[i]);
1088 }
1089 }
1090
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001091 bool empty() const { return Methods.empty(); }
1092
1093 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1094 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001095 };
1096
1097 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
1098 MethodList& Methods) {
1099 // First, collect the pure virtual methods for the base classes.
1100 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1101 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001102 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001103 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001104 if (BaseDecl && BaseDecl->isAbstract())
1105 Collect(BaseDecl, Methods);
1106 }
1107 }
1108
1109 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001110 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
1111
1112 MethodSetTy OverriddenMethods;
1113 size_t MethodsSize = Methods.size();
1114
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001115 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001116 i != e; ++i) {
1117 // Traverse the record, looking for methods.
1118 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001119 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001120 if (MD->isPure()) {
1121 Methods.push_back(MD);
1122 continue;
1123 }
1124
1125 // Otherwise, record all the overridden methods in our set.
1126 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1127 E = MD->end_overridden_methods(); I != E; ++I) {
1128 // Keep track of the overridden methods.
1129 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001130 }
1131 }
1132 }
1133
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001134 // Now go through the methods and zero out all the ones we know are
1135 // overridden.
1136 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1137 if (OverriddenMethods.count(Methods[i]))
1138 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001139 }
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001140
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001141 }
1142}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001143
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001144bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001145 unsigned DiagID, AbstractDiagSelID SelID,
1146 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001147
1148 if (!getLangOptions().CPlusPlus)
1149 return false;
Anders Carlsson11f21a02009-03-23 19:10:31 +00001150
1151 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssone65a3c82009-03-24 17:23:42 +00001152 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
1153 CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001154
Ted Kremenek6217b802009-07-29 21:53:49 +00001155 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001156 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001157 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001158 PT = T;
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001159
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001160 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssone65a3c82009-03-24 17:23:42 +00001161 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
1162 CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001163 }
1164
Ted Kremenek6217b802009-07-29 21:53:49 +00001165 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001166 if (!RT)
1167 return false;
1168
1169 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1170 if (!RD)
1171 return false;
1172
Anders Carlssone65a3c82009-03-24 17:23:42 +00001173 if (CurrentRD && CurrentRD != RD)
1174 return false;
1175
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001176 if (!RD->isAbstract())
1177 return false;
1178
Anders Carlssonb9bbe492009-03-23 17:49:10 +00001179 Diag(Loc, DiagID) << RD->getDeclName() << SelID;
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001180
1181 // Check if we've already emitted the list of pure virtual functions for this
1182 // class.
1183 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1184 return true;
1185
1186 PureVirtualMethodCollector Collector(Context, RD);
1187
1188 for (PureVirtualMethodCollector::MethodList::const_iterator I =
1189 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1190 const CXXMethodDecl *MD = *I;
1191
1192 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
1193 MD->getDeclName();
1194 }
1195
1196 if (!PureVirtualClassDiagSet)
1197 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1198 PureVirtualClassDiagSet->insert(RD);
1199
1200 return true;
1201}
1202
Anders Carlsson8211eff2009-03-24 01:19:16 +00001203namespace {
1204 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
1205 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1206 Sema &SemaRef;
1207 CXXRecordDecl *AbstractClass;
1208
Anders Carlssone65a3c82009-03-24 17:23:42 +00001209 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001210 bool Invalid = false;
1211
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001212 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1213 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001214 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001215
Anders Carlsson8211eff2009-03-24 01:19:16 +00001216 return Invalid;
1217 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00001218
1219 public:
1220 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1221 : SemaRef(SemaRef), AbstractClass(ac) {
1222 Visit(SemaRef.Context.getTranslationUnitDecl());
1223 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001224
Anders Carlssone65a3c82009-03-24 17:23:42 +00001225 bool VisitFunctionDecl(const FunctionDecl *FD) {
1226 if (FD->isThisDeclarationADefinition()) {
1227 // No need to do the check if we're in a definition, because it requires
1228 // that the return/param types are complete.
1229 // because that requires
1230 return VisitDeclContext(FD);
1231 }
1232
1233 // Check the return type.
1234 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
1235 bool Invalid =
1236 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1237 diag::err_abstract_type_in_decl,
1238 Sema::AbstractReturnType,
1239 AbstractClass);
1240
1241 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
1242 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001243 const ParmVarDecl *VD = *I;
1244 Invalid |=
1245 SemaRef.RequireNonAbstractType(VD->getLocation(),
1246 VD->getOriginalType(),
1247 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001248 Sema::AbstractParamType,
1249 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001250 }
1251
1252 return Invalid;
1253 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00001254
1255 bool VisitDecl(const Decl* D) {
1256 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1257 return VisitDeclContext(DC);
1258
1259 return false;
1260 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001261 };
1262}
1263
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001264void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001265 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001266 SourceLocation LBrac,
1267 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001268 if (!TagDecl)
1269 return;
1270
Douglas Gregor42af25f2009-05-11 19:58:34 +00001271 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001272 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001273 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001274 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001275
Chris Lattnerb28317a2009-03-28 19:18:32 +00001276 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001277 if (!RD->isAbstract()) {
1278 // Collect all the pure virtual methods and see if this is an abstract
1279 // class after all.
1280 PureVirtualMethodCollector Collector(Context, RD);
1281 if (!Collector.empty())
1282 RD->setAbstract(true);
1283 }
1284
Anders Carlssone65a3c82009-03-24 17:23:42 +00001285 if (RD->isAbstract())
1286 AbstractClassUsageDiagnoser(*this, RD);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001287
Douglas Gregor42af25f2009-05-11 19:58:34 +00001288 if (!RD->isDependentType())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001289 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001290}
1291
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001292/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1293/// special functions, such as the default constructor, copy
1294/// constructor, or destructor, to the given C++ class (C++
1295/// [special]p1). This routine can only be executed just before the
1296/// definition of the class is complete.
1297void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor50d62d12009-08-05 05:36:45 +00001298 CanQualType ClassType
1299 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001300
Sebastian Redl465226e2009-05-27 22:11:52 +00001301 // FIXME: Implicit declarations have exception specifications, which are
1302 // the union of the specifications of the implicitly called functions.
1303
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001304 if (!ClassDecl->hasUserDeclaredConstructor()) {
1305 // C++ [class.ctor]p5:
1306 // A default constructor for a class X is a constructor of class X
1307 // that can be called without an argument. If there is no
1308 // user-declared constructor for class X, a default constructor is
1309 // implicitly declared. An implicitly-declared default constructor
1310 // is an inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001311 DeclarationName Name
1312 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001313 CXXConstructorDecl *DefaultCon =
1314 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001315 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001316 Context.getFunctionType(Context.VoidTy,
1317 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001318 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001319 /*isExplicit=*/false,
1320 /*isInline=*/true,
1321 /*isImplicitlyDeclared=*/true);
1322 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001323 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001324 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001325 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001326 }
1327
1328 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1329 // C++ [class.copy]p4:
1330 // If the class definition does not explicitly declare a copy
1331 // constructor, one is declared implicitly.
1332
1333 // C++ [class.copy]p5:
1334 // The implicitly-declared copy constructor for a class X will
1335 // have the form
1336 //
1337 // X::X(const X&)
1338 //
1339 // if
1340 bool HasConstCopyConstructor = true;
1341
1342 // -- each direct or virtual base class B of X has a copy
1343 // constructor whose first parameter is of type const B& or
1344 // const volatile B&, and
1345 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1346 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1347 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001348 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001349 HasConstCopyConstructor
1350 = BaseClassDecl->hasConstCopyConstructor(Context);
1351 }
1352
1353 // -- for all the nonstatic data members of X that are of a
1354 // class type M (or array thereof), each such class type
1355 // has a copy constructor whose first parameter is of type
1356 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001357 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1358 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001359 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001360 QualType FieldType = (*Field)->getType();
1361 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1362 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001363 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001364 const CXXRecordDecl *FieldClassDecl
1365 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1366 HasConstCopyConstructor
1367 = FieldClassDecl->hasConstCopyConstructor(Context);
1368 }
1369 }
1370
Sebastian Redl64b45f72009-01-05 20:52:13 +00001371 // Otherwise, the implicitly declared copy constructor will have
1372 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001373 //
1374 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00001375 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001376 if (HasConstCopyConstructor)
1377 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001378 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001379
Sebastian Redl64b45f72009-01-05 20:52:13 +00001380 // An implicitly-declared copy constructor is an inline public
1381 // member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001382 DeclarationName Name
1383 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001384 CXXConstructorDecl *CopyConstructor
1385 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001386 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001387 Context.getFunctionType(Context.VoidTy,
1388 &ArgType, 1,
1389 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001390 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001391 /*isExplicit=*/false,
1392 /*isInline=*/true,
1393 /*isImplicitlyDeclared=*/true);
1394 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001395 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001396 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001397
1398 // Add the parameter to the constructor.
1399 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1400 ClassDecl->getLocation(),
1401 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001402 ArgType, /*DInfo=*/0,
1403 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001404 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001405 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001406 }
1407
Sebastian Redl64b45f72009-01-05 20:52:13 +00001408 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1409 // Note: The following rules are largely analoguous to the copy
1410 // constructor rules. Note that virtual bases are not taken into account
1411 // for determining the argument type of the operator. Note also that
1412 // operators taking an object instead of a reference are allowed.
1413 //
1414 // C++ [class.copy]p10:
1415 // If the class definition does not explicitly declare a copy
1416 // assignment operator, one is declared implicitly.
1417 // The implicitly-defined copy assignment operator for a class X
1418 // will have the form
1419 //
1420 // X& X::operator=(const X&)
1421 //
1422 // if
1423 bool HasConstCopyAssignment = true;
1424
1425 // -- each direct base class B of X has a copy assignment operator
1426 // whose parameter is of type const B&, const volatile B& or B,
1427 // and
1428 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1429 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1430 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001431 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001432 const CXXMethodDecl *MD = 0;
1433 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
1434 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001435 }
1436
1437 // -- for all the nonstatic data members of X that are of a class
1438 // type M (or array thereof), each such class type has a copy
1439 // assignment operator whose parameter is of type const M&,
1440 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001441 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1442 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001443 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001444 QualType FieldType = (*Field)->getType();
1445 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1446 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001447 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001448 const CXXRecordDecl *FieldClassDecl
1449 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001450 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00001451 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001452 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001453 }
1454 }
1455
1456 // Otherwise, the implicitly declared copy assignment operator will
1457 // have the form
1458 //
1459 // X& X::operator=(X&)
1460 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001461 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001462 if (HasConstCopyAssignment)
1463 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001464 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001465
1466 // An implicitly-declared copy assignment operator is an inline public
1467 // member of its class.
1468 DeclarationName Name =
1469 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1470 CXXMethodDecl *CopyAssignment =
1471 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1472 Context.getFunctionType(RetType, &ArgType, 1,
1473 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001474 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001475 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001476 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001477 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001478 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001479
1480 // Add the parameter to the operator.
1481 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1482 ClassDecl->getLocation(),
1483 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001484 ArgType, /*DInfo=*/0,
1485 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001486 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001487
1488 // Don't call addedAssignmentOperator. There is no way to distinguish an
1489 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001490 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001491 }
1492
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001493 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001494 // C++ [class.dtor]p2:
1495 // If a class has no user-declared destructor, a destructor is
1496 // declared implicitly. An implicitly-declared destructor is an
1497 // inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001498 DeclarationName Name
1499 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001500 CXXDestructorDecl *Destructor
1501 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001502 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00001503 Context.getFunctionType(Context.VoidTy,
1504 0, 0, false, 0),
1505 /*isInline=*/true,
1506 /*isImplicitlyDeclared=*/true);
1507 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001508 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001509 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001510 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001511 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001512}
1513
Douglas Gregor6569d682009-05-27 23:11:45 +00001514void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1515 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1516 if (!Template)
1517 return;
1518
1519 TemplateParameterList *Params = Template->getTemplateParameters();
1520 for (TemplateParameterList::iterator Param = Params->begin(),
1521 ParamEnd = Params->end();
1522 Param != ParamEnd; ++Param) {
1523 NamedDecl *Named = cast<NamedDecl>(*Param);
1524 if (Named->getDeclName()) {
1525 S->AddDecl(DeclPtrTy::make(Named));
1526 IdResolver.AddDecl(Named);
1527 }
1528 }
1529}
1530
Douglas Gregor72b505b2008-12-16 21:30:33 +00001531/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1532/// parsing a top-level (non-nested) C++ class, and we are now
1533/// parsing those parts of the given Method declaration that could
1534/// not be parsed earlier (C++ [class.mem]p2), such as default
1535/// arguments. This action should enter the scope of the given
1536/// Method declaration as if we had just parsed the qualified method
1537/// name. However, it should not bring the parameters into scope;
1538/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001539void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001540 if (!MethodD)
1541 return;
1542
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001543 AdjustDeclIfTemplate(MethodD);
1544
Douglas Gregor72b505b2008-12-16 21:30:33 +00001545 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00001546 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregorab452ba2009-03-26 23:50:42 +00001547 QualType ClassTy
1548 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1549 SS.setScopeRep(
1550 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001551 ActOnCXXEnterDeclaratorScope(S, SS);
1552}
1553
1554/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1555/// C++ method declaration. We're (re-)introducing the given
1556/// function parameter into scope for use in parsing later parts of
1557/// the method declaration. For example, we could see an
1558/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001559void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001560 if (!ParamD)
1561 return;
1562
Chris Lattnerb28317a2009-03-28 19:18:32 +00001563 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00001564
1565 // If this parameter has an unparsed default argument, clear it out
1566 // to make way for the parsed default argument.
1567 if (Param->hasUnparsedDefaultArg())
1568 Param->setDefaultArg(0);
1569
Chris Lattnerb28317a2009-03-28 19:18:32 +00001570 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001571 if (Param->getDeclName())
1572 IdResolver.AddDecl(Param);
1573}
1574
1575/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1576/// processing the delayed method declaration for Method. The method
1577/// declaration is now considered finished. There may be a separate
1578/// ActOnStartOfFunctionDef action later (not necessarily
1579/// immediately!) for this method, if it was also defined inside the
1580/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001581void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001582 if (!MethodD)
1583 return;
1584
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001585 AdjustDeclIfTemplate(MethodD);
1586
Chris Lattnerb28317a2009-03-28 19:18:32 +00001587 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00001588 CXXScopeSpec SS;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001589 QualType ClassTy
1590 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1591 SS.setScopeRep(
1592 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001593 ActOnCXXExitDeclaratorScope(S, SS);
1594
1595 // Now that we have our default arguments, check the constructor
1596 // again. It could produce additional diagnostics or affect whether
1597 // the class has implicitly-declared destructors, among other
1598 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00001599 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1600 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00001601
1602 // Check the default arguments, which we may have added.
1603 if (!Method->isInvalidDecl())
1604 CheckCXXDefaultArguments(Method);
1605}
1606
Douglas Gregor42a552f2008-11-05 20:51:48 +00001607/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00001608/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00001609/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00001610/// emit diagnostics and set the invalid bit to true. In any case, the type
1611/// will be updated to reflect a well-formed type for the constructor and
1612/// returned.
1613QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1614 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001615 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001616
1617 // C++ [class.ctor]p3:
1618 // A constructor shall not be virtual (10.3) or static (9.4). A
1619 // constructor can be invoked for a const, volatile or const
1620 // volatile object. A constructor shall not be declared const,
1621 // volatile, or const volatile (9.3.2).
1622 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00001623 if (!D.isInvalidType())
1624 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1625 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1626 << SourceRange(D.getIdentifierLoc());
1627 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001628 }
1629 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00001630 if (!D.isInvalidType())
1631 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1632 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1633 << SourceRange(D.getIdentifierLoc());
1634 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001635 SC = FunctionDecl::None;
1636 }
Chris Lattner65401802009-04-25 08:28:21 +00001637
1638 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1639 if (FTI.TypeQuals != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001640 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001641 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1642 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001643 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001644 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1645 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001646 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001647 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1648 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001649 }
1650
1651 // Rebuild the function type "R" without any type qualifiers (in
1652 // case any of the errors above fired) and with "void" as the
1653 // return type, since constructors don't have return types. We
1654 // *always* have to do this, because GetTypeForDeclarator will
1655 // put in a result type of "int" when none was specified.
Douglas Gregor72564e72009-02-26 23:50:07 +00001656 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattner65401802009-04-25 08:28:21 +00001657 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1658 Proto->getNumArgs(),
1659 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001660}
1661
Douglas Gregor72b505b2008-12-16 21:30:33 +00001662/// CheckConstructor - Checks a fully-formed constructor for
1663/// well-formedness, issuing any diagnostics required. Returns true if
1664/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00001665void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Douglas Gregor33297562009-03-27 04:38:56 +00001666 CXXRecordDecl *ClassDecl
1667 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1668 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00001669 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00001670
1671 // C++ [class.copy]p3:
1672 // A declaration of a constructor for a class X is ill-formed if
1673 // its first parameter is of type (optionally cv-qualified) X and
1674 // either there are no other parameters or else all other
1675 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00001676 if (!Constructor->isInvalidDecl() &&
1677 ((Constructor->getNumParams() == 1) ||
1678 (Constructor->getNumParams() > 1 &&
Anders Carlssonae0b4e72009-06-06 04:14:07 +00001679 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00001680 QualType ParamType = Constructor->getParamDecl(0)->getType();
1681 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1682 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00001683 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
1684 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00001685 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner6e475012009-04-25 08:35:12 +00001686 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00001687 }
1688 }
1689
1690 // Notify the class that we've added a constructor.
1691 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00001692}
1693
Anders Carlsson7786d1c2009-04-30 23:18:11 +00001694static inline bool
1695FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
1696 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1697 FTI.ArgInfo[0].Param &&
1698 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
1699}
1700
Douglas Gregor42a552f2008-11-05 20:51:48 +00001701/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1702/// the well-formednes of the destructor declarator @p D with type @p
1703/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00001704/// emit diagnostics and set the declarator to invalid. Even if this happens,
1705/// will be updated to reflect a well-formed type for the destructor and
1706/// returned.
1707QualType Sema::CheckDestructorDeclarator(Declarator &D,
1708 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001709 // C++ [class.dtor]p1:
1710 // [...] A typedef-name that names a class is a class-name
1711 // (7.1.3); however, a typedef-name that names a class shall not
1712 // be used as the identifier in the declarator for a destructor
1713 // declaration.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001714 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattner65401802009-04-25 08:28:21 +00001715 if (isa<TypedefType>(DeclaratorType)) {
1716 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001717 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00001718 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001719 }
1720
1721 // C++ [class.dtor]p2:
1722 // A destructor is used to destroy objects of its class type. A
1723 // destructor takes no parameters, and no return type can be
1724 // specified for it (not even void). The address of a destructor
1725 // shall not be taken. A destructor shall not be static. A
1726 // destructor can be invoked for a const, volatile or const
1727 // volatile object. A destructor shall not be declared const,
1728 // volatile or const volatile (9.3.2).
1729 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00001730 if (!D.isInvalidType())
1731 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1732 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1733 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001734 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00001735 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001736 }
Chris Lattner65401802009-04-25 08:28:21 +00001737 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001738 // Destructors don't have return types, but the parser will
1739 // happily parse something like:
1740 //
1741 // class X {
1742 // float ~X();
1743 // };
1744 //
1745 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001746 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1747 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1748 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001749 }
Chris Lattner65401802009-04-25 08:28:21 +00001750
1751 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1752 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001753 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001754 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1755 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001756 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001757 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1758 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001759 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001760 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1761 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00001762 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001763 }
1764
1765 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00001766 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001767 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1768
1769 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00001770 FTI.freeArgs();
1771 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001772 }
1773
1774 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00001775 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001776 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00001777 D.setInvalidType();
1778 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00001779
1780 // Rebuild the function type "R" without any type qualifiers or
1781 // parameters (in case any of the errors above fired) and with
1782 // "void" as the return type, since destructors don't have return
1783 // types. We *always* have to do this, because GetTypeForDeclarator
1784 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00001785 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001786}
1787
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001788/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1789/// well-formednes of the conversion function declarator @p D with
1790/// type @p R. If there are any errors in the declarator, this routine
1791/// will emit diagnostics and return true. Otherwise, it will return
1792/// false. Either way, the type @p R will be updated to reflect a
1793/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00001794void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001795 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001796 // C++ [class.conv.fct]p1:
1797 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00001798 // type of a conversion function (8.3.5) is "function taking no
1799 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001800 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00001801 if (!D.isInvalidType())
1802 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1803 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1804 << SourceRange(D.getIdentifierLoc());
1805 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001806 SC = FunctionDecl::None;
1807 }
Chris Lattner6e475012009-04-25 08:35:12 +00001808 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001809 // Conversion functions don't have return types, but the parser will
1810 // happily parse something like:
1811 //
1812 // class X {
1813 // float operator bool();
1814 // };
1815 //
1816 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001817 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1818 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1819 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001820 }
1821
1822 // Make sure we don't have any parameters.
Douglas Gregor72564e72009-02-26 23:50:07 +00001823 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001824 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1825
1826 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00001827 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00001828 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001829 }
1830
1831 // Make sure the conversion function isn't variadic.
Chris Lattner6e475012009-04-25 08:35:12 +00001832 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001833 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00001834 D.setInvalidType();
1835 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001836
1837 // C++ [class.conv.fct]p4:
1838 // The conversion-type-id shall not represent a function type nor
1839 // an array type.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001840 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001841 if (ConvType->isArrayType()) {
1842 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1843 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00001844 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001845 } else if (ConvType->isFunctionType()) {
1846 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1847 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00001848 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001849 }
1850
1851 // Rebuild the function type "R" without any parameters (in case any
1852 // of the errors above fired) and with the conversion type as the
1853 // return type.
1854 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor72564e72009-02-26 23:50:07 +00001855 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001856
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001857 // C++0x explicit conversion operators.
1858 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1859 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1860 diag::warn_explicit_conversion_functions)
1861 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001862}
1863
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001864/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1865/// the declaration of the given C++ conversion function. This routine
1866/// is responsible for recording the conversion function in the C++
1867/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001868Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001869 assert(Conversion && "Expected to receive a conversion function declaration");
1870
Douglas Gregor9d350972008-12-12 08:25:50 +00001871 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001872
1873 // Make sure we aren't redeclaring the conversion function.
1874 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001875
1876 // C++ [class.conv.fct]p1:
1877 // [...] A conversion function is never used to convert a
1878 // (possibly cv-qualified) object to the (possibly cv-qualified)
1879 // same object type (or a reference to it), to a (possibly
1880 // cv-qualified) base class of that type (or a reference to it),
1881 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00001882 // FIXME: Suppress this warning if the conversion function ends up being a
1883 // virtual function that overrides a virtual function in a base class.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001884 QualType ClassType
1885 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00001886 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001887 ConvType = ConvTypeRef->getPointeeType();
1888 if (ConvType->isRecordType()) {
1889 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1890 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00001891 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001892 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001893 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00001894 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001895 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001896 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00001897 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001898 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001899 }
1900
Douglas Gregor70316a02008-12-26 15:00:45 +00001901 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001902 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
1903 if (FunctionTemplateDecl *ConversionTemplate
1904 = Conversion->getDescribedFunctionTemplate())
1905 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00001906 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1907 for (OverloadedFunctionDecl::function_iterator
1908 Conv = Conversions->function_begin(),
1909 ConvEnd = Conversions->function_end();
1910 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001911 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00001912 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00001913 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00001914 }
1915 }
1916 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001917 } else if (FunctionTemplateDecl *ConversionTemplate
1918 = Conversion->getDescribedFunctionTemplate())
1919 ClassDecl->addConversionFunction(Context, ConversionTemplate);
1920 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Douglas Gregor70316a02008-12-26 15:00:45 +00001921 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001922
Chris Lattnerb28317a2009-03-28 19:18:32 +00001923 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001924}
1925
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001926//===----------------------------------------------------------------------===//
1927// Namespace Handling
1928//===----------------------------------------------------------------------===//
1929
1930/// ActOnStartNamespaceDef - This is called at the start of a namespace
1931/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001932Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1933 SourceLocation IdentLoc,
1934 IdentifierInfo *II,
1935 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001936 NamespaceDecl *Namespc =
1937 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1938 Namespc->setLBracLoc(LBrace);
1939
1940 Scope *DeclRegionScope = NamespcScope->getParent();
1941
1942 if (II) {
1943 // C++ [namespace.def]p2:
1944 // The identifier in an original-namespace-definition shall not have been
1945 // previously defined in the declarative region in which the
1946 // original-namespace-definition appears. The identifier in an
1947 // original-namespace-definition is the name of the namespace. Subsequently
1948 // in that declarative region, it is treated as an original-namespace-name.
1949
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001950 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1951 true);
Douglas Gregor44b43212008-12-11 16:49:14 +00001952
1953 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1954 // This is an extended namespace definition.
1955 // Attach this namespace decl to the chain of extended namespace
1956 // definitions.
1957 OrigNS->setNextNamespace(Namespc);
1958 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001959
Douglas Gregor44b43212008-12-11 16:49:14 +00001960 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001961 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001962 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00001963 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001964 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001965 } else if (PrevDecl) {
1966 // This is an invalid name redefinition.
1967 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1968 << Namespc->getDeclName();
1969 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1970 Namespc->setInvalidDecl();
1971 // Continue on to push Namespc as current DeclContext and return it.
1972 }
1973
1974 PushOnScopeChains(Namespc, DeclRegionScope);
1975 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001976 // FIXME: Handle anonymous namespaces
1977 }
1978
1979 // Although we could have an invalid decl (i.e. the namespace name is a
1980 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00001981 // FIXME: We should be able to push Namespc here, so that the each DeclContext
1982 // for the namespace has the declarations that showed up in that particular
1983 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00001984 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00001985 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001986}
1987
1988/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1989/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001990void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
1991 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001992 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1993 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1994 Namespc->setRBracLoc(RBrace);
1995 PopDeclContext();
1996}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001997
Chris Lattnerb28317a2009-03-28 19:18:32 +00001998Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
1999 SourceLocation UsingLoc,
2000 SourceLocation NamespcLoc,
2001 const CXXScopeSpec &SS,
2002 SourceLocation IdentLoc,
2003 IdentifierInfo *NamespcName,
2004 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002005 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2006 assert(NamespcName && "Invalid NamespcName.");
2007 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002008 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002009
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002010 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002011
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002012 // Lookup namespace name.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002013 LookupResult R = LookupParsedName(S, &SS, NamespcName,
2014 LookupNamespaceName, false);
2015 if (R.isAmbiguous()) {
2016 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002017 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002018 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002019 if (NamedDecl *NS = R) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002020 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002021 // C++ [namespace.udir]p1:
2022 // A using-directive specifies that the names in the nominated
2023 // namespace can be used in the scope in which the
2024 // using-directive appears after the using-directive. During
2025 // unqualified name lookup (3.4.1), the names appear as if they
2026 // were declared in the nearest enclosing namespace which
2027 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002028 // namespace. [Note: in this context, "contains" means "contains
2029 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002030
2031 // Find enclosing context containing both using-directive and
2032 // nominated namespace.
2033 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2034 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2035 CommonAncestor = CommonAncestor->getParent();
2036
Douglas Gregor8419fa32009-05-30 06:31:56 +00002037 UDir = UsingDirectiveDecl::Create(Context,
2038 CurContext, UsingLoc,
2039 NamespcLoc,
2040 SS.getRange(),
2041 (NestedNameSpecifier *)SS.getScopeRep(),
2042 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002043 cast<NamespaceDecl>(NS),
2044 CommonAncestor);
2045 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002046 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002047 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002048 }
2049
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002050 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002051 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002052 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002053}
2054
2055void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2056 // If scope has associated entity, then using directive is at namespace
2057 // or translation unit scope. We add UsingDirectiveDecls, into
2058 // it's lookup structure.
2059 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002060 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002061 else
2062 // Otherwise it is block-sope. using-directives will affect lookup
2063 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002064 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002065}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002066
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002067
2068Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
2069 SourceLocation UsingLoc,
2070 const CXXScopeSpec &SS,
2071 SourceLocation IdentLoc,
2072 IdentifierInfo *TargetName,
Anders Carlsson0c6139d2009-06-27 00:27:47 +00002073 OverloadedOperatorKind Op,
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002074 AttributeList *AttrList,
2075 bool IsTypeName) {
2076 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Eli Friedman5d39dee2009-06-27 05:59:59 +00002077 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002078 assert(IdentLoc.isValid() && "Invalid TargetName location.");
2079 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2080
2081 UsingDecl *UsingAlias = 0;
2082
Anders Carlsson0c6139d2009-06-27 00:27:47 +00002083 DeclarationName Name;
2084 if (TargetName)
2085 Name = TargetName;
2086 else
2087 Name = Context.DeclarationNames.getCXXOperatorName(Op);
2088
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002089 // Lookup target name.
Anders Carlsson0c6139d2009-06-27 00:27:47 +00002090 LookupResult R = LookupParsedName(S, &SS, Name, LookupOrdinaryName, false);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002091
2092 if (NamedDecl *NS = R) {
2093 if (IsTypeName && !isa<TypeDecl>(NS)) {
2094 Diag(IdentLoc, diag::err_using_typename_non_type);
2095 }
2096 UsingAlias = UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2097 NS->getLocation(), UsingLoc, NS,
2098 static_cast<NestedNameSpecifier *>(SS.getScopeRep()),
2099 IsTypeName);
2100 PushOnScopeChains(UsingAlias, S);
2101 } else {
2102 Diag(IdentLoc, diag::err_using_requires_qualname) << SS.getRange();
2103 }
2104
2105 // FIXME: We ignore attributes for now.
2106 delete AttrList;
2107 return DeclPtrTy::make(UsingAlias);
2108}
2109
Anders Carlsson81c85c42009-03-28 23:53:49 +00002110/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2111/// is a namespace alias, returns the namespace it points to.
2112static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2113 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2114 return AD->getNamespace();
2115 return dyn_cast_or_null<NamespaceDecl>(D);
2116}
2117
Chris Lattnerb28317a2009-03-28 19:18:32 +00002118Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002119 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002120 SourceLocation AliasLoc,
2121 IdentifierInfo *Alias,
2122 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002123 SourceLocation IdentLoc,
2124 IdentifierInfo *Ident) {
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002125
Anders Carlsson81c85c42009-03-28 23:53:49 +00002126 // Lookup the namespace name.
2127 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2128
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002129 // Check if we have a previous declaration with the same name.
Anders Carlssondd729fc2009-03-28 23:49:35 +00002130 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002131 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
2132 // We already have an alias with the same name that points to the same
2133 // namespace, so don't create a new one.
2134 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2135 return DeclPtrTy();
2136 }
2137
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002138 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2139 diag::err_redefinition_different_kind;
2140 Diag(AliasLoc, DiagID) << Alias;
2141 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002142 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002143 }
2144
Anders Carlsson5721c682009-03-28 06:42:02 +00002145 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002146 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002147 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002148 }
2149
2150 if (!R) {
2151 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002152 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002153 }
2154
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002155 NamespaceAliasDecl *AliasDecl =
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002156 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2157 Alias, SS.getRange(),
2158 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlsson68771c72009-03-28 22:58:02 +00002159 IdentLoc, R);
2160
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002161 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00002162 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00002163}
2164
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002165void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2166 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00002167 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2168 !Constructor->isUsed()) &&
2169 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002170
2171 CXXRecordDecl *ClassDecl
2172 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002173 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002174 // Before the implicitly-declared default constructor for a class is
2175 // implicitly defined, all the implicitly-declared default constructors
2176 // for its base class and its non-static data members shall have been
2177 // implicitly defined.
2178 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002179 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2180 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002181 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002182 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002183 if (!BaseClassDecl->hasTrivialConstructor()) {
2184 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002185 BaseClassDecl->getDefaultConstructor(Context))
2186 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002187 else {
2188 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002189 << Context.getTagDeclType(ClassDecl) << 1
2190 << Context.getTagDeclType(BaseClassDecl);
2191 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
2192 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002193 err = true;
2194 }
2195 }
2196 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002197 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2198 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002199 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2200 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2201 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002202 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002203 CXXRecordDecl *FieldClassDecl
2204 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands6887e632009-06-25 09:03:06 +00002205 if (!FieldClassDecl->hasTrivialConstructor()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002206 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002207 FieldClassDecl->getDefaultConstructor(Context))
2208 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002209 else {
2210 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002211 << Context.getTagDeclType(ClassDecl) << 0 <<
2212 Context.getTagDeclType(FieldClassDecl);
2213 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
2214 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002215 err = true;
2216 }
2217 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002218 } else if (FieldType->isReferenceType()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002219 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002220 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002221 Diag((*Field)->getLocation(), diag::note_declared_at);
2222 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002223 } else if (FieldType.isConstQualified()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002224 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002225 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002226 Diag((*Field)->getLocation(), diag::note_declared_at);
2227 err = true;
2228 }
2229 }
2230 if (!err)
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002231 Constructor->setUsed();
2232 else
2233 Constructor->setInvalidDecl();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002234}
2235
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002236void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
2237 CXXDestructorDecl *Destructor) {
2238 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2239 "DefineImplicitDestructor - call it for implicit default dtor");
2240
2241 CXXRecordDecl *ClassDecl
2242 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2243 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2244 // C++ [class.dtor] p5
2245 // Before the implicitly-declared default destructor for a class is
2246 // implicitly defined, all the implicitly-declared default destructors
2247 // for its base class and its non-static data members shall have been
2248 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002249 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2250 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002251 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002252 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002253 if (!BaseClassDecl->hasTrivialDestructor()) {
2254 if (CXXDestructorDecl *BaseDtor =
2255 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2256 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2257 else
2258 assert(false &&
2259 "DefineImplicitDestructor - missing dtor in a base class");
2260 }
2261 }
2262
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002263 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2264 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002265 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2266 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2267 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002268 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002269 CXXRecordDecl *FieldClassDecl
2270 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2271 if (!FieldClassDecl->hasTrivialDestructor()) {
2272 if (CXXDestructorDecl *FieldDtor =
2273 const_cast<CXXDestructorDecl*>(
2274 FieldClassDecl->getDestructor(Context)))
2275 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2276 else
2277 assert(false &&
2278 "DefineImplicitDestructor - missing dtor in class of a data member");
2279 }
2280 }
2281 }
2282 Destructor->setUsed();
2283}
2284
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002285void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2286 CXXMethodDecl *MethodDecl) {
2287 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2288 MethodDecl->getOverloadedOperator() == OO_Equal &&
2289 !MethodDecl->isUsed()) &&
2290 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
2291
2292 CXXRecordDecl *ClassDecl
2293 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002294
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002295 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002296 // Before the implicitly-declared copy assignment operator for a class is
2297 // implicitly defined, all implicitly-declared copy assignment operators
2298 // for its direct base classes and its nonstatic data members shall have
2299 // been implicitly defined.
2300 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002301 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2302 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002303 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002304 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002305 if (CXXMethodDecl *BaseAssignOpMethod =
2306 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2307 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2308 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002309 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2310 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002311 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2312 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2313 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002314 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002315 CXXRecordDecl *FieldClassDecl
2316 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2317 if (CXXMethodDecl *FieldAssignOpMethod =
2318 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2319 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002320 } else if (FieldType->isReferenceType()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002321 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002322 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2323 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002324 Diag(CurrentLocation, diag::note_first_required_here);
2325 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002326 } else if (FieldType.isConstQualified()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002327 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002328 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2329 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002330 Diag(CurrentLocation, diag::note_first_required_here);
2331 err = true;
2332 }
2333 }
2334 if (!err)
2335 MethodDecl->setUsed();
2336}
2337
2338CXXMethodDecl *
2339Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2340 CXXRecordDecl *ClassDecl) {
2341 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2342 QualType RHSType(LHSType);
2343 // If class's assignment operator argument is const/volatile qualified,
2344 // look for operator = (const/volatile B&). Otherwise, look for
2345 // operator = (B&).
2346 if (ParmDecl->getType().isConstQualified())
2347 RHSType.addConst();
2348 if (ParmDecl->getType().isVolatileQualified())
2349 RHSType.addVolatile();
2350 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2351 LHSType,
2352 SourceLocation()));
2353 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2354 RHSType,
2355 SourceLocation()));
2356 Expr *Args[2] = { &*LHS, &*RHS };
2357 OverloadCandidateSet CandidateSet;
2358 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
2359 CandidateSet);
2360 OverloadCandidateSet::iterator Best;
2361 if (BestViableFunction(CandidateSet,
2362 ClassDecl->getLocation(), Best) == OR_Success)
2363 return cast<CXXMethodDecl>(Best->Function);
2364 assert(false &&
2365 "getAssignOperatorMethod - copy assignment operator method not found");
2366 return 0;
2367}
2368
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002369void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2370 CXXConstructorDecl *CopyConstructor,
2371 unsigned TypeQuals) {
2372 assert((CopyConstructor->isImplicit() &&
2373 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2374 !CopyConstructor->isUsed()) &&
2375 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
2376
2377 CXXRecordDecl *ClassDecl
2378 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2379 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002380 // C++ [class.copy] p209
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002381 // Before the implicitly-declared copy constructor for a class is
2382 // implicitly defined, all the implicitly-declared copy constructors
2383 // for its base class and its non-static data members shall have been
2384 // implicitly defined.
2385 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2386 Base != ClassDecl->bases_end(); ++Base) {
2387 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002388 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002389 if (CXXConstructorDecl *BaseCopyCtor =
2390 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002391 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002392 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002393 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2394 FieldEnd = ClassDecl->field_end();
2395 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002396 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2397 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2398 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002399 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002400 CXXRecordDecl *FieldClassDecl
2401 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2402 if (CXXConstructorDecl *FieldCopyCtor =
2403 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002404 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002405 }
2406 }
2407 CopyConstructor->setUsed();
2408}
2409
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002410Sema::OwningExprResult
2411Sema::BuildCXXConstructExpr(QualType DeclInitType,
2412 CXXConstructorDecl *Constructor,
2413 Expr **Exprs, unsigned NumExprs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002414 bool Elidable = false;
2415
2416 // [class.copy]p15:
2417 // Whenever a temporary class object is copied using a copy constructor, and
2418 // this object and the copy have the same cv-unqualified type, an
2419 // implementation is permitted to treat the original and the copy as two
2420 // different ways of referring to the same object and not perform a copy at
2421 //all, even if the class copy constructor or destructor have side effects.
2422
2423 // FIXME: Is this enough?
2424 if (Constructor->isCopyConstructor(Context) && NumExprs == 1) {
2425 Expr *E = Exprs[0];
2426 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2427 E = BE->getSubExpr();
2428
2429 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2430 Elidable = true;
2431 }
2432
2433 return BuildCXXConstructExpr(DeclInitType, Constructor, Elidable,
2434 Exprs, NumExprs);
2435}
2436
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002437/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2438/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002439Sema::OwningExprResult
2440Sema::BuildCXXConstructExpr(QualType DeclInitType,
2441 CXXConstructorDecl *Constructor,
2442 bool Elidable,
2443 Expr **Exprs,
2444 unsigned NumExprs) {
Anders Carlsson8644aec2009-08-25 13:07:08 +00002445 ExprOwningPtr<CXXConstructExpr> Temp(this,
2446 CXXConstructExpr::Create(Context,
2447 DeclInitType,
2448 Constructor,
2449 Elidable,
2450 Exprs,
2451 NumExprs));
Fariborz Jahanian2eeed7b2009-08-05 00:26:10 +00002452 // default arguments must be added to constructor call expression.
2453 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor);
2454 unsigned NumArgsInProto = FDecl->param_size();
2455 for (unsigned j = NumExprs; j != NumArgsInProto; j++) {
Anders Carlsson8644aec2009-08-25 13:07:08 +00002456 ParmVarDecl *Param = FDecl->getParamDecl(j);
2457
2458 OwningExprResult ArgExpr =
2459 BuildCXXDefaultArgExpr(/*FIXME:*/SourceLocation(),
2460 FDecl, Param);
2461 if (ArgExpr.isInvalid())
2462 return ExprError();
2463
2464 Temp->setArg(j, ArgExpr.takeAs<Expr>());
Fariborz Jahanian2eeed7b2009-08-05 00:26:10 +00002465 }
Anders Carlsson8644aec2009-08-25 13:07:08 +00002466 return move(Temp);
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002467}
2468
Anders Carlssonfe2de492009-08-25 05:18:00 +00002469bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002470 CXXConstructorDecl *Constructor,
2471 QualType DeclInitType,
2472 Expr **Exprs, unsigned NumExprs) {
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002473 OwningExprResult TempResult = BuildCXXConstructExpr(DeclInitType, Constructor,
2474 Exprs, NumExprs);
Anders Carlssonfe2de492009-08-25 05:18:00 +00002475 if (TempResult.isInvalid())
2476 return true;
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002477
2478 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002479 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00002480 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00002481 VD->setInit(Context, Temp);
Anders Carlssonfe2de492009-08-25 05:18:00 +00002482
2483 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00002484}
2485
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002486void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType)
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002487{
2488 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00002489 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002490 if (!ClassDecl->hasTrivialDestructor())
2491 if (CXXDestructorDecl *Destructor =
2492 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002493 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002494}
2495
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002496/// AddCXXDirectInitializerToDecl - This action is called immediately after
2497/// ActOnDeclarator, when a C++ direct initializer is present.
2498/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00002499void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2500 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00002501 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002502 SourceLocation *CommaLocs,
2503 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00002504 unsigned NumExprs = Exprs.size();
2505 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00002506 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002507
2508 // If there is no declaration, there was an error parsing it. Just ignore
2509 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002510 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002511 return;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002512
2513 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2514 if (!VDecl) {
2515 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2516 RealDecl->setInvalidDecl();
2517 return;
2518 }
2519
Douglas Gregor615c5d42009-03-24 16:43:20 +00002520 // FIXME: Need to handle dependent types and expressions here.
2521
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00002522 // We will treat direct-initialization as a copy-initialization:
2523 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002524 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2525 //
2526 // Clients that want to distinguish between the two forms, can check for
2527 // direct initializer using VarDecl::hasCXXDirectInitializer().
2528 // A major benefit is that clients that don't particularly care about which
2529 // exactly form was it (like the CodeGen) can handle both cases without
2530 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002531
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002532 // C++ 8.5p11:
2533 // The form of initialization (using parentheses or '=') is generally
2534 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002535 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00002536 QualType DeclInitType = VDecl->getType();
2537 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
2538 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002539
Douglas Gregor615c5d42009-03-24 16:43:20 +00002540 // FIXME: This isn't the right place to complete the type.
2541 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2542 diag::err_typecheck_decl_incomplete_type)) {
2543 VDecl->setInvalidDecl();
2544 return;
2545 }
2546
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002547 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00002548 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00002549 = PerformInitializationByConstructor(DeclInitType,
2550 (Expr **)Exprs.get(), NumExprs,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002551 VDecl->getLocation(),
2552 SourceRange(VDecl->getLocation(),
2553 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002554 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002555 IK_Direct);
Sebastian Redlf53597f2009-03-15 17:47:39 +00002556 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00002557 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00002558 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00002559 VDecl->setCXXDirectInitializer(true);
Anders Carlssonfe2de492009-08-25 05:18:00 +00002560 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
2561 (Expr**)Exprs.release(), NumExprs))
2562 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002563 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00002564 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002565 return;
2566 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002567
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00002568 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002569 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
2570 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002571 RealDecl->setInvalidDecl();
2572 return;
2573 }
2574
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002575 // Let clients know that initialization was done with a direct initializer.
2576 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00002577
2578 assert(NumExprs == 1 && "Expected 1 expression");
2579 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00002580 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
2581 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002582}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002583
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002584/// PerformInitializationByConstructor - Perform initialization by
2585/// constructor (C++ [dcl.init]p14), which may occur as part of
2586/// direct-initialization or copy-initialization. We are initializing
2587/// an object of type @p ClassType with the given arguments @p
2588/// Args. @p Loc is the location in the source code where the
2589/// initializer occurs (e.g., a declaration, member initializer,
2590/// functional cast, etc.) while @p Range covers the whole
2591/// initialization. @p InitEntity is the entity being initialized,
2592/// which may by the name of a declaration or a type. @p Kind is the
2593/// kind of initialization we're performing, which affects whether
2594/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00002595/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002596/// when the initialization fails, emits a diagnostic and returns
2597/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00002598CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002599Sema::PerformInitializationByConstructor(QualType ClassType,
2600 Expr **Args, unsigned NumArgs,
2601 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002602 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002603 InitializationKind Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002604 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00002605 assert(ClassRec && "Can only initialize a class type here");
2606
2607 // C++ [dcl.init]p14:
2608 //
2609 // If the initialization is direct-initialization, or if it is
2610 // copy-initialization where the cv-unqualified version of the
2611 // source type is the same class as, or a derived class of, the
2612 // class of the destination, constructors are considered. The
2613 // applicable constructors are enumerated (13.3.1.3), and the
2614 // best one is chosen through overload resolution (13.3). The
2615 // constructor so selected is called to initialize the object,
2616 // with the initializer expression(s) as its argument(s). If no
2617 // constructor applies, or the overload resolution is ambiguous,
2618 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00002619 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
2620 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002621
2622 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002623 DeclarationName ConstructorName
2624 = Context.DeclarationNames.getCXXConstructorName(
2625 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002626 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002627 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002628 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00002629 // Find the constructor (which may be a template).
2630 CXXConstructorDecl *Constructor = 0;
2631 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
2632 if (ConstructorTmpl)
2633 Constructor
2634 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2635 else
2636 Constructor = cast<CXXConstructorDecl>(*Con);
2637
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002638 if ((Kind == IK_Direct) ||
2639 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
Douglas Gregordec06662009-08-21 18:42:58 +00002640 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
2641 if (ConstructorTmpl)
2642 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
2643 Args, NumArgs, CandidateSet);
2644 else
2645 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2646 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002647 }
2648
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002649 // FIXME: When we decide not to synthesize the implicitly-declared
2650 // constructors, we'll need to make them appear here.
2651
Douglas Gregor18fe5682008-11-03 20:45:27 +00002652 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002653 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00002654 case OR_Success:
2655 // We found a constructor. Return it.
2656 return cast<CXXConstructorDecl>(Best->Function);
2657
2658 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00002659 if (InitEntity)
2660 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00002661 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00002662 else
2663 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00002664 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00002665 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002666 return 0;
2667
2668 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00002669 if (InitEntity)
2670 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
2671 else
2672 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00002673 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2674 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002675
2676 case OR_Deleted:
2677 if (InitEntity)
2678 Diag(Loc, diag::err_ovl_deleted_init)
2679 << Best->Function->isDeleted()
2680 << InitEntity << Range;
2681 else
2682 Diag(Loc, diag::err_ovl_deleted_init)
2683 << Best->Function->isDeleted()
2684 << InitEntity << Range;
2685 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2686 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00002687 }
2688
2689 return 0;
2690}
2691
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002692/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2693/// determine whether they are reference-related,
2694/// reference-compatible, reference-compatible with added
2695/// qualification, or incompatible, for use in C++ initialization by
2696/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2697/// type, and the first type (T1) is the pointee type of the reference
2698/// type being initialized.
2699Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00002700Sema::CompareReferenceRelationship(QualType T1, QualType T2,
2701 bool& DerivedToBase) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002702 assert(!T1->isReferenceType() &&
2703 "T1 must be the pointee type of the reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002704 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
2705
2706 T1 = Context.getCanonicalType(T1);
2707 T2 = Context.getCanonicalType(T2);
2708 QualType UnqualT1 = T1.getUnqualifiedType();
2709 QualType UnqualT2 = T2.getUnqualifiedType();
2710
2711 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00002712 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2713 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002714 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002715 if (UnqualT1 == UnqualT2)
2716 DerivedToBase = false;
2717 else if (IsDerivedFrom(UnqualT2, UnqualT1))
2718 DerivedToBase = true;
2719 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002720 return Ref_Incompatible;
2721
2722 // At this point, we know that T1 and T2 are reference-related (at
2723 // least).
2724
2725 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00002726 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002727 // reference-related to T2 and cv1 is the same cv-qualification
2728 // as, or greater cv-qualification than, cv2. For purposes of
2729 // overload resolution, cases for which cv1 is greater
2730 // cv-qualification than cv2 are identified as
2731 // reference-compatible with added qualification (see 13.3.3.2).
2732 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2733 return Ref_Compatible;
2734 else if (T1.isMoreQualifiedThan(T2))
2735 return Ref_Compatible_With_Added_Qualification;
2736 else
2737 return Ref_Related;
2738}
2739
2740/// CheckReferenceInit - Check the initialization of a reference
2741/// variable with the given initializer (C++ [dcl.init.ref]). Init is
2742/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00002743/// list), and DeclType is the type of the declaration. When ICS is
2744/// non-null, this routine will compute the implicit conversion
2745/// sequence according to C++ [over.ics.ref] and will not produce any
2746/// diagnostics; when ICS is null, it will emit diagnostics when any
2747/// errors are found. Either way, a return value of true indicates
2748/// that there was a failure, a return value of false indicates that
2749/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00002750///
2751/// When @p SuppressUserConversions, user-defined conversions are
2752/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002753/// When @p AllowExplicit, we also permit explicit user-defined
2754/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00002755/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002756bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002757Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002758 ImplicitConversionSequence *ICS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002759 bool SuppressUserConversions,
Sebastian Redle2b68332009-04-12 17:16:29 +00002760 bool AllowExplicit, bool ForceRValue) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002761 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2762
Ted Kremenek6217b802009-07-29 21:53:49 +00002763 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002764 QualType T2 = Init->getType();
2765
Douglas Gregor904eed32008-11-10 20:40:00 +00002766 // If the initializer is the address of an overloaded function, try
2767 // to resolve the overloaded function. If all goes well, T2 is the
2768 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00002769 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00002770 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
2771 ICS != 0);
2772 if (Fn) {
2773 // Since we're performing this reference-initialization for
2774 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002775 if (!ICS) {
2776 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
2777 return true;
2778
Douglas Gregor904eed32008-11-10 20:40:00 +00002779 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002780 }
Douglas Gregor904eed32008-11-10 20:40:00 +00002781
2782 T2 = Fn->getType();
2783 }
2784 }
2785
Douglas Gregor15da57e2008-10-29 02:00:59 +00002786 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002787 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00002788 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00002789 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2790 Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00002791 ReferenceCompareResult RefRelationship
2792 = CompareReferenceRelationship(T1, T2, DerivedToBase);
2793
2794 // Most paths end in a failed conversion.
2795 if (ICS)
2796 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002797
2798 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00002799 // A reference to type "cv1 T1" is initialized by an expression
2800 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002801
2802 // -- If the initializer expression
2803
Sebastian Redla9845802009-03-29 15:27:50 +00002804 // Rvalue references cannot bind to lvalues (N2812).
2805 // There is absolutely no situation where they can. In particular, note that
2806 // this is ill-formed, even if B has a user-defined conversion to A&&:
2807 // B b;
2808 // A&& r = b;
2809 if (isRValRef && InitLvalue == Expr::LV_Valid) {
2810 if (!ICS)
2811 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
2812 << Init->getSourceRange();
2813 return true;
2814 }
2815
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002816 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00002817 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2818 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00002819 //
2820 // Note that the bit-field check is skipped if we are just computing
2821 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002822 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00002823 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002824 BindsDirectly = true;
2825
Douglas Gregor15da57e2008-10-29 02:00:59 +00002826 if (ICS) {
2827 // C++ [over.ics.ref]p1:
2828 // When a parameter of reference type binds directly (8.5.3)
2829 // to an argument expression, the implicit conversion sequence
2830 // is the identity conversion, unless the argument expression
2831 // has a type that is a derived class of the parameter type,
2832 // in which case the implicit conversion sequence is a
2833 // derived-to-base Conversion (13.3.3.1).
2834 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2835 ICS->Standard.First = ICK_Identity;
2836 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2837 ICS->Standard.Third = ICK_Identity;
2838 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2839 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002840 ICS->Standard.ReferenceBinding = true;
2841 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00002842 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00002843 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00002844
2845 // Nothing more to do: the inaccessibility/ambiguity check for
2846 // derived-to-base conversions is suppressed when we're
2847 // computing the implicit conversion sequence (C++
2848 // [over.best.ics]p2).
2849 return false;
2850 } else {
2851 // Perform the conversion.
Mike Stump390b4cc2009-05-16 07:39:55 +00002852 // FIXME: Binding to a subobject of the lvalue is going to require more
2853 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00002854 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002855 }
2856 }
2857
2858 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00002859 // implicitly converted to an lvalue of type "cv3 T3,"
2860 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002861 // 92) (this conversion is selected by enumerating the
2862 // applicable conversion functions (13.3.1.6) and choosing
2863 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00002864 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2865 !RequireCompleteType(SourceLocation(), T2, 0)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002866 // FIXME: Look for conversions in base classes!
2867 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002868 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002869
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002870 OverloadCandidateSet CandidateSet;
2871 OverloadedFunctionDecl *Conversions
2872 = T2RecordDecl->getConversionFunctions();
2873 for (OverloadedFunctionDecl::function_iterator Func
2874 = Conversions->function_begin();
2875 Func != Conversions->function_end(); ++Func) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002876 FunctionTemplateDecl *ConvTemplate
2877 = dyn_cast<FunctionTemplateDecl>(*Func);
2878 CXXConversionDecl *Conv;
2879 if (ConvTemplate)
2880 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2881 else
2882 Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redldfe292d2009-03-22 21:28:55 +00002883
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002884 // If the conversion function doesn't return a reference type,
2885 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002886 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002887 (AllowExplicit || !Conv->isExplicit())) {
2888 if (ConvTemplate)
2889 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
2890 CandidateSet);
2891 else
2892 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
2893 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002894 }
2895
2896 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002897 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002898 case OR_Success:
2899 // This is a direct binding.
2900 BindsDirectly = true;
2901
2902 if (ICS) {
2903 // C++ [over.ics.ref]p1:
2904 //
2905 // [...] If the parameter binds directly to the result of
2906 // applying a conversion function to the argument
2907 // expression, the implicit conversion sequence is a
2908 // user-defined conversion sequence (13.3.3.1.2), with the
2909 // second standard conversion sequence either an identity
2910 // conversion or, if the conversion function returns an
2911 // entity of a type that is a derived class of the parameter
2912 // type, a derived-to-base Conversion.
2913 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
2914 ICS->UserDefined.Before = Best->Conversions[0].Standard;
2915 ICS->UserDefined.After = Best->FinalConversion;
2916 ICS->UserDefined.ConversionFunction = Best->Function;
2917 assert(ICS->UserDefined.After.ReferenceBinding &&
2918 ICS->UserDefined.After.DirectBinding &&
2919 "Expected a direct reference binding!");
2920 return false;
2921 } else {
2922 // Perform the conversion.
Mike Stump390b4cc2009-05-16 07:39:55 +00002923 // FIXME: Binding to a subobject of the lvalue is going to require more
2924 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00002925 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002926 }
2927 break;
2928
2929 case OR_Ambiguous:
2930 assert(false && "Ambiguous reference binding conversions not implemented.");
2931 return true;
2932
2933 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002934 case OR_Deleted:
2935 // There was no suitable conversion, or we found a deleted
2936 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002937 break;
2938 }
2939 }
2940
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002941 if (BindsDirectly) {
2942 // C++ [dcl.init.ref]p4:
2943 // [...] In all cases where the reference-related or
2944 // reference-compatible relationship of two types is used to
2945 // establish the validity of a reference binding, and T1 is a
2946 // base class of T2, a program that necessitates such a binding
2947 // is ill-formed if T1 is an inaccessible (clause 11) or
2948 // ambiguous (10.2) base class of T2.
2949 //
2950 // Note that we only check this condition when we're allowed to
2951 // complain about errors, because we should not be checking for
2952 // ambiguity (or inaccessibility) unless the reference binding
2953 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002954 if (DerivedToBase)
2955 return CheckDerivedToBaseConversion(T2, T1,
2956 Init->getSourceRange().getBegin(),
2957 Init->getSourceRange());
2958 else
2959 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002960 }
2961
2962 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00002963 // type (i.e., cv1 shall be const), or the reference shall be an
2964 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002965 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00002966 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002967 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002968 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00002969 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2970 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002971 return true;
2972 }
2973
2974 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00002975 // class type, and "cv1 T1" is reference-compatible with
2976 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002977 // following ways (the choice is implementation-defined):
2978 //
2979 // -- The reference is bound to the object represented by
2980 // the rvalue (see 3.10) or to a sub-object within that
2981 // object.
2982 //
Eli Friedman33a31382009-08-05 19:21:58 +00002983 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002984 // a constructor is called to copy the entire rvalue
2985 // object into the temporary. The reference is bound to
2986 // the temporary or to a sub-object within the
2987 // temporary.
2988 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002989 // The constructor that would be used to make the copy
2990 // shall be callable whether or not the copy is actually
2991 // done.
2992 //
Sebastian Redla9845802009-03-29 15:27:50 +00002993 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002994 // freedom, so we will always take the first option and never build
2995 // a temporary in this case. FIXME: We will, however, have to check
2996 // for the presence of a copy constructor in C++98/03 mode.
2997 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00002998 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2999 if (ICS) {
3000 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3001 ICS->Standard.First = ICK_Identity;
3002 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3003 ICS->Standard.Third = ICK_Identity;
3004 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3005 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003006 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003007 ICS->Standard.DirectBinding = false;
3008 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003009 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003010 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +00003011 // FIXME: Binding to a subobject of the rvalue is going to require more
3012 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00003013 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003014 }
3015 return false;
3016 }
3017
Eli Friedman33a31382009-08-05 19:21:58 +00003018 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003019 // initialized from the initializer expression using the
3020 // rules for a non-reference copy initialization (8.5). The
3021 // reference is then bound to the temporary. If T1 is
3022 // reference-related to T2, cv1 must be the same
3023 // cv-qualification as, or greater cv-qualification than,
3024 // cv2; otherwise, the program is ill-formed.
3025 if (RefRelationship == Ref_Related) {
3026 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3027 // we would be reference-compatible or reference-compatible with
3028 // added qualification. But that wasn't the case, so the reference
3029 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003030 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003031 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003032 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003033 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3034 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003035 return true;
3036 }
3037
Douglas Gregor734d9862009-01-30 23:27:23 +00003038 // If at least one of the types is a class type, the types are not
3039 // related, and we aren't allowed any user conversions, the
3040 // reference binding fails. This case is important for breaking
3041 // recursion, since TryImplicitConversion below will attempt to
3042 // create a temporary through the use of a copy constructor.
3043 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3044 (T1->isRecordType() || T2->isRecordType())) {
3045 if (!ICS)
3046 Diag(Init->getSourceRange().getBegin(),
3047 diag::err_typecheck_convert_incompatible)
3048 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3049 return true;
3050 }
3051
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003052 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003053 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003054 // C++ [over.ics.ref]p2:
3055 //
3056 // When a parameter of reference type is not bound directly to
3057 // an argument expression, the conversion sequence is the one
3058 // required to convert the argument expression to the
3059 // underlying type of the reference according to
3060 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3061 // to copy-initializing a temporary of the underlying type with
3062 // the argument expression. Any difference in top-level
3063 // cv-qualification is subsumed by the initialization itself
3064 // and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003065 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Sebastian Redla9845802009-03-29 15:27:50 +00003066 // Of course, that's still a reference binding.
3067 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3068 ICS->Standard.ReferenceBinding = true;
3069 ICS->Standard.RRefBinding = isRValRef;
3070 } else if(ICS->ConversionKind ==
3071 ImplicitConversionSequence::UserDefinedConversion) {
3072 ICS->UserDefined.After.ReferenceBinding = true;
3073 ICS->UserDefined.After.RRefBinding = isRValRef;
3074 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00003075 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3076 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00003077 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00003078 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003079}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003080
3081/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3082/// of this overloaded operator is well-formed. If so, returns false;
3083/// otherwise, emits appropriate diagnostics and returns true.
3084bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003085 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003086 "Expected an overloaded operator declaration");
3087
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003088 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3089
3090 // C++ [over.oper]p5:
3091 // The allocation and deallocation functions, operator new,
3092 // operator new[], operator delete and operator delete[], are
3093 // described completely in 3.7.3. The attributes and restrictions
3094 // found in the rest of this subclause do not apply to them unless
3095 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00003096 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003097 if (Op == OO_New || Op == OO_Array_New ||
3098 Op == OO_Delete || Op == OO_Array_Delete)
3099 return false;
3100
3101 // C++ [over.oper]p6:
3102 // An operator function shall either be a non-static member
3103 // function or be a non-member function and have at least one
3104 // parameter whose type is a class, a reference to a class, an
3105 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003106 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3107 if (MethodDecl->isStatic())
3108 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003109 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003110 } else {
3111 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003112 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3113 ParamEnd = FnDecl->param_end();
3114 Param != ParamEnd; ++Param) {
3115 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00003116 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3117 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003118 ClassOrEnumParam = true;
3119 break;
3120 }
3121 }
3122
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003123 if (!ClassOrEnumParam)
3124 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003125 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003126 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003127 }
3128
3129 // C++ [over.oper]p8:
3130 // An operator function cannot have default arguments (8.3.6),
3131 // except where explicitly stated below.
3132 //
3133 // Only the function-call operator allows default arguments
3134 // (C++ [over.call]p1).
3135 if (Op != OO_Call) {
3136 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3137 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00003138 if ((*Param)->hasUnparsedDefaultArg())
3139 return Diag((*Param)->getLocation(),
3140 diag::err_operator_overload_default_arg)
3141 << FnDecl->getDeclName();
3142 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003143 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003144 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003145 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003146 }
3147 }
3148
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003149 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3150 { false, false, false }
3151#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3152 , { Unary, Binary, MemberOnly }
3153#include "clang/Basic/OperatorKinds.def"
3154 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003155
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003156 bool CanBeUnaryOperator = OperatorUses[Op][0];
3157 bool CanBeBinaryOperator = OperatorUses[Op][1];
3158 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003159
3160 // C++ [over.oper]p8:
3161 // [...] Operator functions cannot have more or fewer parameters
3162 // than the number required for the corresponding operator, as
3163 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003164 unsigned NumParams = FnDecl->getNumParams()
3165 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003166 if (Op != OO_Call &&
3167 ((NumParams == 1 && !CanBeUnaryOperator) ||
3168 (NumParams == 2 && !CanBeBinaryOperator) ||
3169 (NumParams < 1) || (NumParams > 2))) {
3170 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00003171 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003172 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003173 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003174 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003175 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003176 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003177 assert(CanBeBinaryOperator &&
3178 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00003179 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003180 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003181
Chris Lattner416e46f2008-11-21 07:57:12 +00003182 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003183 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003184 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003185
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003186 // Overloaded operators other than operator() cannot be variadic.
3187 if (Op != OO_Call &&
Douglas Gregor72564e72009-02-26 23:50:07 +00003188 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003189 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003190 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003191 }
3192
3193 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003194 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3195 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003196 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003197 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003198 }
3199
3200 // C++ [over.inc]p1:
3201 // The user-defined function called operator++ implements the
3202 // prefix and postfix ++ operator. If this function is a member
3203 // function with no parameters, or a non-member function with one
3204 // parameter of class or enumeration type, it defines the prefix
3205 // increment operator ++ for objects of that type. If the function
3206 // is a member function with one parameter (which shall be of type
3207 // int) or a non-member function with two parameters (the second
3208 // of which shall be of type int), it defines the postfix
3209 // increment operator ++ for objects of that type.
3210 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3211 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3212 bool ParamIsInt = false;
3213 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
3214 ParamIsInt = BT->getKind() == BuiltinType::Int;
3215
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003216 if (!ParamIsInt)
3217 return Diag(LastParam->getLocation(),
3218 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00003219 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003220 }
3221
Sebastian Redl64b45f72009-01-05 20:52:13 +00003222 // Notify the class if it got an assignment operator.
3223 if (Op == OO_Equal) {
3224 // Would have returned earlier otherwise.
3225 assert(isa<CXXMethodDecl>(FnDecl) &&
3226 "Overloaded = not member, but not filtered.");
3227 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanianad258832009-08-13 21:09:41 +00003228 Method->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003229 Method->getParent()->addedAssignmentOperator(Context, Method);
3230 }
3231
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003232 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003233}
Chris Lattner5a003a42008-12-17 07:09:26 +00003234
Douglas Gregor074149e2009-01-05 19:45:36 +00003235/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3236/// linkage specification, including the language and (if present)
3237/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3238/// the location of the language string literal, which is provided
3239/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3240/// the '{' brace. Otherwise, this linkage specification does not
3241/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003242Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3243 SourceLocation ExternLoc,
3244 SourceLocation LangLoc,
3245 const char *Lang,
3246 unsigned StrSize,
3247 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00003248 LinkageSpecDecl::LanguageIDs Language;
3249 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3250 Language = LinkageSpecDecl::lang_c;
3251 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3252 Language = LinkageSpecDecl::lang_cxx;
3253 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00003254 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003255 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00003256 }
3257
3258 // FIXME: Add all the various semantics of linkage specifications
3259
Douglas Gregor074149e2009-01-05 19:45:36 +00003260 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
3261 LangLoc, Language,
3262 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003263 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00003264 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003265 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00003266}
3267
Douglas Gregor074149e2009-01-05 19:45:36 +00003268/// ActOnFinishLinkageSpecification - Completely the definition of
3269/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3270/// valid, it's the position of the closing '}' brace in a linkage
3271/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003272Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3273 DeclPtrTy LinkageSpec,
3274 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00003275 if (LinkageSpec)
3276 PopDeclContext();
3277 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00003278}
3279
Douglas Gregord308e622009-05-18 20:51:54 +00003280/// \brief Perform semantic analysis for the variable declaration that
3281/// occurs within a C++ catch clause, returning the newly-created
3282/// variable.
3283VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003284 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003285 IdentifierInfo *Name,
3286 SourceLocation Loc,
3287 SourceRange Range) {
3288 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003289
3290 // Arrays and functions decay.
3291 if (ExDeclType->isArrayType())
3292 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3293 else if (ExDeclType->isFunctionType())
3294 ExDeclType = Context.getPointerType(ExDeclType);
3295
3296 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3297 // The exception-declaration shall not denote a pointer or reference to an
3298 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003299 // N2844 forbids rvalue references.
Douglas Gregor2f2433f2009-05-18 21:08:14 +00003300 if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00003301 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003302 Invalid = true;
3303 }
Douglas Gregord308e622009-05-18 20:51:54 +00003304
Sebastian Redl4b07b292008-12-22 19:15:10 +00003305 QualType BaseType = ExDeclType;
3306 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003307 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00003308 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003309 BaseType = Ptr->getPointeeType();
3310 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003311 DK = diag::err_catch_incomplete_ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003312 } else if(const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003313 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003314 BaseType = Ref->getPointeeType();
3315 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003316 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003317 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003318 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00003319 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00003320 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003321
Douglas Gregord308e622009-05-18 20:51:54 +00003322 if (!Invalid && !ExDeclType->isDependentType() &&
3323 RequireNonAbstractType(Loc, ExDeclType,
3324 diag::err_abstract_type_in_decl,
3325 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00003326 Invalid = true;
3327
Douglas Gregord308e622009-05-18 20:51:54 +00003328 // FIXME: Need to test for ability to copy-construct and destroy the
3329 // exception variable.
3330
Sebastian Redl8351da02008-12-22 21:35:02 +00003331 // FIXME: Need to check for abstract classes.
3332
Douglas Gregord308e622009-05-18 20:51:54 +00003333 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003334 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00003335
3336 if (Invalid)
3337 ExDecl->setInvalidDecl();
3338
3339 return ExDecl;
3340}
3341
3342/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3343/// handler.
3344Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003345 DeclaratorInfo *DInfo = 0;
3346 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00003347
3348 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00003349 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003350 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003351 // The scope should be freshly made just for us. There is just no way
3352 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003353 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00003354 if (PrevDecl->isTemplateParameter()) {
3355 // Maybe we will complain about the shadowed template parameter.
3356 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003357 }
3358 }
3359
Chris Lattnereaaebc72009-04-25 08:06:05 +00003360 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003361 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3362 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003363 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003364 }
3365
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003366 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003367 D.getIdentifier(),
3368 D.getIdentifierLoc(),
3369 D.getDeclSpec().getSourceRange());
3370
Chris Lattnereaaebc72009-04-25 08:06:05 +00003371 if (Invalid)
3372 ExDecl->setInvalidDecl();
3373
Sebastian Redl4b07b292008-12-22 19:15:10 +00003374 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003375 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00003376 PushOnScopeChains(ExDecl, S);
3377 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003378 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003379
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003380 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003381 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003382}
Anders Carlssonfb311762009-03-14 00:25:26 +00003383
Chris Lattnerb28317a2009-03-28 19:18:32 +00003384Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
3385 ExprArg assertexpr,
3386 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00003387 Expr *AssertExpr = (Expr *)assertexpr.get();
3388 StringLiteral *AssertMessage =
3389 cast<StringLiteral>((Expr *)assertmessageexpr.get());
3390
Anders Carlssonc3082412009-03-14 00:33:21 +00003391 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3392 llvm::APSInt Value(32);
3393 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3394 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3395 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003396 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00003397 }
Anders Carlssonfb311762009-03-14 00:25:26 +00003398
Anders Carlssonc3082412009-03-14 00:33:21 +00003399 if (Value == 0) {
3400 std::string str(AssertMessage->getStrData(),
3401 AssertMessage->getByteLength());
Anders Carlsson94b15fb2009-03-15 18:44:04 +00003402 Diag(AssertLoc, diag::err_static_assert_failed)
3403 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00003404 }
3405 }
3406
Anders Carlsson77d81422009-03-15 17:35:16 +00003407 assertexpr.release();
3408 assertmessageexpr.release();
Anders Carlssonfb311762009-03-14 00:25:26 +00003409 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
3410 AssertExpr, AssertMessage);
Anders Carlssonfb311762009-03-14 00:25:26 +00003411
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003412 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003413 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00003414}
Sebastian Redl50de12f2009-03-24 22:27:57 +00003415
John McCall67d1a672009-08-06 02:15:43 +00003416Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S,
John McCall3f9a8a62009-08-11 06:59:38 +00003417 llvm::PointerUnion<const DeclSpec*,Declarator*> DU,
3418 bool IsDefinition) {
John McCall67d1a672009-08-06 02:15:43 +00003419 Declarator *D = DU.dyn_cast<Declarator*>();
3420 const DeclSpec &DS = (D ? D->getDeclSpec() : *DU.get<const DeclSpec*>());
3421
3422 assert(DS.isFriendSpecified());
3423 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
3424
3425 // If there's no declarator, then this can only be a friend class
John McCallc48fbdf2009-08-11 21:13:21 +00003426 // declaration (or else it's just syntactically invalid).
John McCall67d1a672009-08-06 02:15:43 +00003427 if (!D) {
John McCallc48fbdf2009-08-11 21:13:21 +00003428 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00003429
John McCallc48fbdf2009-08-11 21:13:21 +00003430 QualType T;
3431 DeclContext *DC;
John McCall67d1a672009-08-06 02:15:43 +00003432
John McCallc48fbdf2009-08-11 21:13:21 +00003433 // In C++0x, we just accept any old type.
3434 if (getLangOptions().CPlusPlus0x) {
3435 bool invalid = false;
3436 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
3437 if (invalid)
3438 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00003439
John McCallc48fbdf2009-08-11 21:13:21 +00003440 // The semantic context in which to create the decl. If it's not
3441 // a record decl (or we don't yet know if it is), create it in the
3442 // current context.
3443 DC = CurContext;
3444 if (const RecordType *RT = T->getAs<RecordType>())
3445 DC = RT->getDecl()->getDeclContext();
3446
3447 // The C++98 rules are somewhat more complex.
3448 } else {
3449 // C++ [class.friend]p2:
3450 // An elaborated-type-specifier shall be used in a friend declaration
3451 // for a class.*
3452 // * The class-key of the elaborated-type-specifier is required.
3453 CXXRecordDecl *RD = 0;
3454
3455 switch (DS.getTypeSpecType()) {
3456 case DeclSpec::TST_class:
3457 case DeclSpec::TST_struct:
3458 case DeclSpec::TST_union:
3459 RD = dyn_cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
3460 if (!RD) return DeclPtrTy();
3461 break;
3462
3463 case DeclSpec::TST_typename:
3464 if (const RecordType *RT =
3465 ((const Type*) DS.getTypeRep())->getAs<RecordType>())
3466 RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
3467 // fallthrough
3468 default:
3469 if (RD) {
3470 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
3471 << (RD->isUnion())
3472 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
3473 RD->isUnion() ? " union" : " class");
3474 return DeclPtrTy::make(RD);
3475 }
3476
3477 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
3478 << DS.getSourceRange();
3479 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00003480 }
3481
John McCallc48fbdf2009-08-11 21:13:21 +00003482 // The record declaration we get from friend declarations is not
3483 // canonicalized; see ActOnTag.
John McCallc48fbdf2009-08-11 21:13:21 +00003484
3485 // C++ [class.friend]p2: A class shall not be defined inside
3486 // a friend declaration.
3487 if (RD->isDefinition())
3488 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
3489 << RD->getSourceRange();
3490
3491 // C++98 [class.friend]p1: A friend of a class is a function
3492 // or class that is not a member of the class . . .
3493 // But that's a silly restriction which nobody implements for
3494 // inner classes, and C++0x removes it anyway, so we only report
3495 // this (as a warning) if we're being pedantic.
3496 //
3497 // Also, definitions currently get treated in a way that causes
3498 // this error, so only report it if we didn't see a definition.
3499 else if (RD->getDeclContext() == CurContext &&
3500 !getLangOptions().CPlusPlus0x)
3501 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
3502
3503 T = QualType(RD->getTypeForDecl(), 0);
3504 DC = RD->getDeclContext();
John McCall67d1a672009-08-06 02:15:43 +00003505 }
3506
John McCallc48fbdf2009-08-11 21:13:21 +00003507 FriendClassDecl *FCD = FriendClassDecl::Create(Context, DC, Loc, T,
3508 DS.getFriendSpecLoc());
3509 FCD->setLexicalDeclContext(CurContext);
John McCall67d1a672009-08-06 02:15:43 +00003510
John McCallc48fbdf2009-08-11 21:13:21 +00003511 if (CurContext->isDependentContext())
3512 CurContext->addHiddenDecl(FCD);
3513 else
3514 CurContext->addDecl(FCD);
John McCall67d1a672009-08-06 02:15:43 +00003515
John McCallc48fbdf2009-08-11 21:13:21 +00003516 return DeclPtrTy::make(FCD);
Anders Carlsson00338362009-05-11 22:55:49 +00003517 }
John McCall67d1a672009-08-06 02:15:43 +00003518
3519 // We have a declarator.
3520 assert(D);
3521
3522 SourceLocation Loc = D->getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003523 DeclaratorInfo *DInfo = 0;
3524 QualType T = GetTypeForDeclarator(*D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00003525
3526 // C++ [class.friend]p1
3527 // A friend of a class is a function or class....
3528 // Note that this sees through typedefs, which is intended.
3529 if (!T->isFunctionType()) {
3530 Diag(Loc, diag::err_unexpected_friend);
3531
3532 // It might be worthwhile to try to recover by creating an
3533 // appropriate declaration.
3534 return DeclPtrTy();
3535 }
3536
3537 // C++ [namespace.memdef]p3
3538 // - If a friend declaration in a non-local class first declares a
3539 // class or function, the friend class or function is a member
3540 // of the innermost enclosing namespace.
3541 // - The name of the friend is not found by simple name lookup
3542 // until a matching declaration is provided in that namespace
3543 // scope (either before or after the class declaration granting
3544 // friendship).
3545 // - If a friend function is called, its name may be found by the
3546 // name lookup that considers functions from namespaces and
3547 // classes associated with the types of the function arguments.
3548 // - When looking for a prior declaration of a class or a function
3549 // declared as a friend, scopes outside the innermost enclosing
3550 // namespace scope are not considered.
3551
3552 CXXScopeSpec &ScopeQual = D->getCXXScopeSpec();
3553 DeclarationName Name = GetNameForDeclarator(*D);
3554 assert(Name);
3555
3556 // The existing declaration we found.
3557 FunctionDecl *FD = NULL;
3558
3559 // The context we found the declaration in, or in which we should
3560 // create the declaration.
3561 DeclContext *DC;
3562
3563 // FIXME: handle local classes
3564
3565 // Recover from invalid scope qualifiers as if they just weren't there.
3566 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
3567 DC = computeDeclContext(ScopeQual);
3568
3569 // FIXME: handle dependent contexts
3570 if (!DC) return DeclPtrTy();
3571
3572 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3573
3574 // If searching in that context implicitly found a declaration in
3575 // a different context, treat it like it wasn't found at all.
3576 // TODO: better diagnostics for this case. Suggesting the right
3577 // qualified scope would be nice...
3578 if (!Dec || Dec->getDeclContext() != DC) {
3579 D->setInvalidType();
3580 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
3581 return DeclPtrTy();
3582 }
3583
3584 // C++ [class.friend]p1: A friend of a class is a function or
3585 // class that is not a member of the class . . .
3586 if (DC == CurContext)
3587 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
3588
3589 FD = cast<FunctionDecl>(Dec);
3590
3591 // Otherwise walk out to the nearest namespace scope looking for matches.
3592 } else {
3593 // TODO: handle local class contexts.
3594
3595 DC = CurContext;
3596 while (true) {
3597 // Skip class contexts. If someone can cite chapter and verse
3598 // for this behavior, that would be nice --- it's what GCC and
3599 // EDG do, and it seems like a reasonable intent, but the spec
3600 // really only says that checks for unqualified existing
3601 // declarations should stop at the nearest enclosing namespace,
3602 // not that they should only consider the nearest enclosing
3603 // namespace.
3604 while (DC->isRecord()) DC = DC->getParent();
3605
3606 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3607
3608 // TODO: decide what we think about using declarations.
3609 if (Dec) {
3610 FD = cast<FunctionDecl>(Dec);
3611 break;
3612 }
3613 if (DC->isFileContext()) break;
3614 DC = DC->getParent();
3615 }
3616
3617 // C++ [class.friend]p1: A friend of a class is a function or
3618 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00003619 // C++0x changes this for both friend types and functions.
3620 // Most C++ 98 compilers do seem to give an error here, so
3621 // we do, too.
3622 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00003623 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
3624 }
3625
John McCall3f9a8a62009-08-11 06:59:38 +00003626 bool Redeclaration = (FD != 0);
3627
3628 // If we found a match, create a friend function declaration with
3629 // that function as the previous declaration.
3630 if (Redeclaration) {
3631 // Create it in the semantic context of the original declaration.
3632 DC = FD->getDeclContext();
3633
John McCall67d1a672009-08-06 02:15:43 +00003634 // If we didn't find something matching the type exactly, create
3635 // a declaration. This declaration should only be findable via
3636 // argument-dependent lookup.
John McCall3f9a8a62009-08-11 06:59:38 +00003637 } else {
John McCall67d1a672009-08-06 02:15:43 +00003638 assert(DC->isFileContext());
3639
3640 // This implies that it has to be an operator or function.
3641 if (D->getKind() == Declarator::DK_Constructor ||
3642 D->getKind() == Declarator::DK_Destructor ||
3643 D->getKind() == Declarator::DK_Conversion) {
3644 Diag(Loc, diag::err_introducing_special_friend) <<
3645 (D->getKind() == Declarator::DK_Constructor ? 0 :
3646 D->getKind() == Declarator::DK_Destructor ? 1 : 2);
3647 return DeclPtrTy();
3648 }
John McCall67d1a672009-08-06 02:15:43 +00003649 }
3650
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003651 NamedDecl *ND = ActOnFunctionDeclarator(S, *D, DC, T, DInfo,
John McCall3f9a8a62009-08-11 06:59:38 +00003652 /* PrevDecl = */ FD,
3653 MultiTemplateParamsArg(*this),
3654 IsDefinition,
3655 Redeclaration);
3656 FD = cast_or_null<FriendFunctionDecl>(ND);
3657
John McCall88232aa2009-08-18 00:00:49 +00003658 assert(FD->getDeclContext() == DC);
3659 assert(FD->getLexicalDeclContext() == CurContext);
3660
John McCall3f9a8a62009-08-11 06:59:38 +00003661 // If this is a dependent context, just add the decl to the
3662 // class's decl list and don't both with the lookup tables. This
3663 // doesn't affect lookup because any call that might find this
3664 // function via ADL necessarily has to involve dependently-typed
3665 // arguments and hence can't be resolved until
3666 // template-instantiation anyway.
3667 if (CurContext->isDependentContext())
3668 CurContext->addHiddenDecl(FD);
3669 else
3670 CurContext->addDecl(FD);
John McCall67d1a672009-08-06 02:15:43 +00003671
3672 return DeclPtrTy::make(FD);
Anders Carlsson00338362009-05-11 22:55:49 +00003673}
3674
Chris Lattnerb28317a2009-03-28 19:18:32 +00003675void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003676 AdjustDeclIfTemplate(dcl);
3677
Chris Lattnerb28317a2009-03-28 19:18:32 +00003678 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00003679 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
3680 if (!Fn) {
3681 Diag(DelLoc, diag::err_deleted_non_function);
3682 return;
3683 }
3684 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
3685 Diag(DelLoc, diag::err_deleted_decl_not_first);
3686 Diag(Prev->getLocation(), diag::note_previous_declaration);
3687 // If the declaration wasn't the first, we delete the function anyway for
3688 // recovery.
3689 }
3690 Fn->setDeleted();
3691}
Sebastian Redl13e88542009-04-27 21:33:24 +00003692
3693static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
3694 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
3695 ++CI) {
3696 Stmt *SubStmt = *CI;
3697 if (!SubStmt)
3698 continue;
3699 if (isa<ReturnStmt>(SubStmt))
3700 Self.Diag(SubStmt->getSourceRange().getBegin(),
3701 diag::err_return_in_constructor_handler);
3702 if (!isa<Expr>(SubStmt))
3703 SearchForReturnInStmt(Self, SubStmt);
3704 }
3705}
3706
3707void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
3708 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
3709 CXXCatchStmt *Handler = TryBlock->getHandler(I);
3710 SearchForReturnInStmt(*this, Handler);
3711 }
3712}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003713
3714bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3715 const CXXMethodDecl *Old) {
3716 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
3717 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
3718
3719 QualType CNewTy = Context.getCanonicalType(NewTy);
3720 QualType COldTy = Context.getCanonicalType(OldTy);
3721
3722 if (CNewTy == COldTy &&
3723 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
3724 return false;
3725
Anders Carlssonc3a68b22009-05-14 19:52:19 +00003726 // Check if the return types are covariant
3727 QualType NewClassTy, OldClassTy;
3728
3729 /// Both types must be pointers or references to classes.
3730 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
3731 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
3732 NewClassTy = NewPT->getPointeeType();
3733 OldClassTy = OldPT->getPointeeType();
3734 }
3735 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
3736 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
3737 NewClassTy = NewRT->getPointeeType();
3738 OldClassTy = OldRT->getPointeeType();
3739 }
3740 }
3741
3742 // The return types aren't either both pointers or references to a class type.
3743 if (NewClassTy.isNull()) {
3744 Diag(New->getLocation(),
3745 diag::err_different_return_type_for_overriding_virtual_function)
3746 << New->getDeclName() << NewTy << OldTy;
3747 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3748
3749 return true;
3750 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003751
Anders Carlssonc3a68b22009-05-14 19:52:19 +00003752 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
3753 // Check if the new class derives from the old class.
3754 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
3755 Diag(New->getLocation(),
3756 diag::err_covariant_return_not_derived)
3757 << New->getDeclName() << NewTy << OldTy;
3758 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3759 return true;
3760 }
3761
3762 // Check if we the conversion from derived to base is valid.
3763 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
3764 diag::err_covariant_return_inaccessible_base,
3765 diag::err_covariant_return_ambiguous_derived_to_base_conv,
3766 // FIXME: Should this point to the return type?
3767 New->getLocation(), SourceRange(), New->getDeclName())) {
3768 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3769 return true;
3770 }
3771 }
3772
3773 // The qualifiers of the return types must be the same.
3774 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
3775 Diag(New->getLocation(),
3776 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003777 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00003778 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3779 return true;
3780 };
3781
3782
3783 // The new class type must have the same or less qualifiers as the old type.
3784 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
3785 Diag(New->getLocation(),
3786 diag::err_covariant_return_type_class_type_more_qualified)
3787 << New->getDeclName() << NewTy << OldTy;
3788 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3789 return true;
3790 };
3791
3792 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003793}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003794
Sebastian Redl23c7d062009-07-07 20:29:57 +00003795bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
3796 const CXXMethodDecl *Old)
3797{
3798 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
3799 diag::note_overridden_virtual_function,
3800 Old->getType()->getAsFunctionProtoType(),
3801 Old->getLocation(),
3802 New->getType()->getAsFunctionProtoType(),
3803 New->getLocation());
3804}
3805
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003806/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3807/// initializer for the declaration 'Dcl'.
3808/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3809/// static data member of class X, names should be looked up in the scope of
3810/// class X.
3811void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003812 AdjustDeclIfTemplate(Dcl);
3813
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003814 Decl *D = Dcl.getAs<Decl>();
3815 // If there is no declaration, there was an error parsing it.
3816 if (D == 0)
3817 return;
3818
3819 // Check whether it is a declaration with a nested name specifier like
3820 // int foo::bar;
3821 if (!D->isOutOfLine())
3822 return;
3823
3824 // C++ [basic.lookup.unqual]p13
3825 //
3826 // A name used in the definition of a static data member of class X
3827 // (after the qualified-id of the static member) is looked up as if the name
3828 // was used in a member function of X.
3829
3830 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00003831 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003832}
3833
3834/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3835/// initializer for the declaration 'Dcl'.
3836void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003837 AdjustDeclIfTemplate(Dcl);
3838
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003839 Decl *D = Dcl.getAs<Decl>();
3840 // If there is no declaration, there was an error parsing it.
3841 if (D == 0)
3842 return;
3843
3844 // Check whether it is a declaration with a nested name specifier like
3845 // int foo::bar;
3846 if (!D->isOutOfLine())
3847 return;
3848
3849 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00003850 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003851}