blob: 5452963fad00cb4ae6841ed93fa551b8b3ef1bf1 [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))
120 return false;
121
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
129 return true;
130}
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 Carlsson9abf2ae2009-08-16 05:13:48 +00002410Expr *Sema::BuildCXXConstructExpr(QualType DeclInitType,
2411 CXXConstructorDecl *Constructor,
2412 Expr **Exprs, unsigned NumExprs) {
2413 bool Elidable = false;
2414
2415 // [class.copy]p15:
2416 // Whenever a temporary class object is copied using a copy constructor, and
2417 // this object and the copy have the same cv-unqualified type, an
2418 // implementation is permitted to treat the original and the copy as two
2419 // different ways of referring to the same object and not perform a copy at
2420 //all, even if the class copy constructor or destructor have side effects.
2421
2422 // FIXME: Is this enough?
2423 if (Constructor->isCopyConstructor(Context) && NumExprs == 1) {
2424 Expr *E = Exprs[0];
2425 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2426 E = BE->getSubExpr();
2427
2428 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2429 Elidable = true;
2430 }
2431
2432 return BuildCXXConstructExpr(DeclInitType, Constructor, Elidable,
2433 Exprs, NumExprs);
2434}
2435
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002436/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2437/// including handling of its default argument expressions.
Anders Carlsson089c2602009-08-15 23:41:35 +00002438Expr *Sema::BuildCXXConstructExpr(QualType DeclInitType,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002439 CXXConstructorDecl *Constructor,
2440 bool Elidable,
2441 Expr **Exprs, unsigned NumExprs) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002442 CXXConstructExpr *Temp = CXXConstructExpr::Create(Context, DeclInitType,
Fariborz Jahanian2eeed7b2009-08-05 00:26:10 +00002443 Constructor,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002444 Elidable, Exprs, NumExprs);
Fariborz Jahanian2eeed7b2009-08-05 00:26:10 +00002445 // default arguments must be added to constructor call expression.
2446 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor);
2447 unsigned NumArgsInProto = FDecl->param_size();
2448 for (unsigned j = NumExprs; j != NumArgsInProto; j++) {
2449 Expr *DefaultExpr = FDecl->getParamDecl(j)->getDefaultArg();
2450
2451 // If the default expression creates temporaries, we need to
2452 // push them to the current stack of expression temporaries so they'll
2453 // be properly destroyed.
2454 if (CXXExprWithTemporaries *E
2455 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2456 assert(!E->shouldDestroyTemporaries() &&
2457 "Can't destroy temporaries in a default argument expr!");
2458 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2459 ExprTemporaries.push_back(E->getTemporary(I));
2460 }
Anders Carlsson089c2602009-08-15 23:41:35 +00002461 Expr *Arg = CXXDefaultArgExpr::Create(Context, FDecl->getParamDecl(j));
Fariborz Jahanian2eeed7b2009-08-05 00:26:10 +00002462 Temp->setArg(j, Arg);
2463 }
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002464 return Temp;
2465}
2466
2467void Sema::InitializeVarWithConstructor(VarDecl *VD,
2468 CXXConstructorDecl *Constructor,
2469 QualType DeclInitType,
2470 Expr **Exprs, unsigned NumExprs) {
Anders Carlsson089c2602009-08-15 23:41:35 +00002471 Expr *Temp = BuildCXXConstructExpr(DeclInitType, Constructor,
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002472 Exprs, NumExprs);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002473 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00002474 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00002475 VD->setInit(Context, Temp);
Anders Carlsson930e8d02009-04-16 23:50:50 +00002476}
2477
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002478void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType)
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002479{
2480 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00002481 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002482 if (!ClassDecl->hasTrivialDestructor())
2483 if (CXXDestructorDecl *Destructor =
2484 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002485 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002486}
2487
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002488/// AddCXXDirectInitializerToDecl - This action is called immediately after
2489/// ActOnDeclarator, when a C++ direct initializer is present.
2490/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00002491void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2492 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00002493 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002494 SourceLocation *CommaLocs,
2495 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00002496 unsigned NumExprs = Exprs.size();
2497 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00002498 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002499
2500 // If there is no declaration, there was an error parsing it. Just ignore
2501 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002502 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002503 return;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002504
2505 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2506 if (!VDecl) {
2507 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2508 RealDecl->setInvalidDecl();
2509 return;
2510 }
2511
Douglas Gregor615c5d42009-03-24 16:43:20 +00002512 // FIXME: Need to handle dependent types and expressions here.
2513
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00002514 // We will treat direct-initialization as a copy-initialization:
2515 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002516 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2517 //
2518 // Clients that want to distinguish between the two forms, can check for
2519 // direct initializer using VarDecl::hasCXXDirectInitializer().
2520 // A major benefit is that clients that don't particularly care about which
2521 // exactly form was it (like the CodeGen) can handle both cases without
2522 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002523
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002524 // C++ 8.5p11:
2525 // The form of initialization (using parentheses or '=') is generally
2526 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002527 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00002528 QualType DeclInitType = VDecl->getType();
2529 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
2530 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002531
Douglas Gregor615c5d42009-03-24 16:43:20 +00002532 // FIXME: This isn't the right place to complete the type.
2533 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2534 diag::err_typecheck_decl_incomplete_type)) {
2535 VDecl->setInvalidDecl();
2536 return;
2537 }
2538
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002539 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00002540 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00002541 = PerformInitializationByConstructor(DeclInitType,
2542 (Expr **)Exprs.get(), NumExprs,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002543 VDecl->getLocation(),
2544 SourceRange(VDecl->getLocation(),
2545 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002546 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002547 IK_Direct);
Sebastian Redlf53597f2009-03-15 17:47:39 +00002548 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00002549 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00002550 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00002551 VDecl->setCXXDirectInitializer(true);
Anders Carlsson930e8d02009-04-16 23:50:50 +00002552 InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
2553 (Expr**)Exprs.release(), NumExprs);
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002554 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00002555 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002556 return;
2557 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002558
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00002559 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002560 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
2561 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002562 RealDecl->setInvalidDecl();
2563 return;
2564 }
2565
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002566 // Let clients know that initialization was done with a direct initializer.
2567 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00002568
2569 assert(NumExprs == 1 && "Expected 1 expression");
2570 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00002571 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
2572 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002573}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002574
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002575/// PerformInitializationByConstructor - Perform initialization by
2576/// constructor (C++ [dcl.init]p14), which may occur as part of
2577/// direct-initialization or copy-initialization. We are initializing
2578/// an object of type @p ClassType with the given arguments @p
2579/// Args. @p Loc is the location in the source code where the
2580/// initializer occurs (e.g., a declaration, member initializer,
2581/// functional cast, etc.) while @p Range covers the whole
2582/// initialization. @p InitEntity is the entity being initialized,
2583/// which may by the name of a declaration or a type. @p Kind is the
2584/// kind of initialization we're performing, which affects whether
2585/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00002586/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002587/// when the initialization fails, emits a diagnostic and returns
2588/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00002589CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002590Sema::PerformInitializationByConstructor(QualType ClassType,
2591 Expr **Args, unsigned NumArgs,
2592 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002593 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002594 InitializationKind Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002595 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00002596 assert(ClassRec && "Can only initialize a class type here");
2597
2598 // C++ [dcl.init]p14:
2599 //
2600 // If the initialization is direct-initialization, or if it is
2601 // copy-initialization where the cv-unqualified version of the
2602 // source type is the same class as, or a derived class of, the
2603 // class of the destination, constructors are considered. The
2604 // applicable constructors are enumerated (13.3.1.3), and the
2605 // best one is chosen through overload resolution (13.3). The
2606 // constructor so selected is called to initialize the object,
2607 // with the initializer expression(s) as its argument(s). If no
2608 // constructor applies, or the overload resolution is ambiguous,
2609 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00002610 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
2611 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002612
2613 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002614 DeclarationName ConstructorName
2615 = Context.DeclarationNames.getCXXConstructorName(
2616 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002617 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002618 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002619 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00002620 // Find the constructor (which may be a template).
2621 CXXConstructorDecl *Constructor = 0;
2622 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
2623 if (ConstructorTmpl)
2624 Constructor
2625 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2626 else
2627 Constructor = cast<CXXConstructorDecl>(*Con);
2628
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002629 if ((Kind == IK_Direct) ||
2630 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
Douglas Gregordec06662009-08-21 18:42:58 +00002631 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
2632 if (ConstructorTmpl)
2633 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
2634 Args, NumArgs, CandidateSet);
2635 else
2636 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2637 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002638 }
2639
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002640 // FIXME: When we decide not to synthesize the implicitly-declared
2641 // constructors, we'll need to make them appear here.
2642
Douglas Gregor18fe5682008-11-03 20:45:27 +00002643 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002644 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00002645 case OR_Success:
2646 // We found a constructor. Return it.
2647 return cast<CXXConstructorDecl>(Best->Function);
2648
2649 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00002650 if (InitEntity)
2651 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00002652 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00002653 else
2654 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00002655 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00002656 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002657 return 0;
2658
2659 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00002660 if (InitEntity)
2661 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
2662 else
2663 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00002664 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2665 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002666
2667 case OR_Deleted:
2668 if (InitEntity)
2669 Diag(Loc, diag::err_ovl_deleted_init)
2670 << Best->Function->isDeleted()
2671 << InitEntity << Range;
2672 else
2673 Diag(Loc, diag::err_ovl_deleted_init)
2674 << Best->Function->isDeleted()
2675 << InitEntity << Range;
2676 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2677 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00002678 }
2679
2680 return 0;
2681}
2682
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002683/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2684/// determine whether they are reference-related,
2685/// reference-compatible, reference-compatible with added
2686/// qualification, or incompatible, for use in C++ initialization by
2687/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2688/// type, and the first type (T1) is the pointee type of the reference
2689/// type being initialized.
2690Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00002691Sema::CompareReferenceRelationship(QualType T1, QualType T2,
2692 bool& DerivedToBase) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002693 assert(!T1->isReferenceType() &&
2694 "T1 must be the pointee type of the reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002695 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
2696
2697 T1 = Context.getCanonicalType(T1);
2698 T2 = Context.getCanonicalType(T2);
2699 QualType UnqualT1 = T1.getUnqualifiedType();
2700 QualType UnqualT2 = T2.getUnqualifiedType();
2701
2702 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00002703 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2704 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002705 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002706 if (UnqualT1 == UnqualT2)
2707 DerivedToBase = false;
2708 else if (IsDerivedFrom(UnqualT2, UnqualT1))
2709 DerivedToBase = true;
2710 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002711 return Ref_Incompatible;
2712
2713 // At this point, we know that T1 and T2 are reference-related (at
2714 // least).
2715
2716 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00002717 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002718 // reference-related to T2 and cv1 is the same cv-qualification
2719 // as, or greater cv-qualification than, cv2. For purposes of
2720 // overload resolution, cases for which cv1 is greater
2721 // cv-qualification than cv2 are identified as
2722 // reference-compatible with added qualification (see 13.3.3.2).
2723 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2724 return Ref_Compatible;
2725 else if (T1.isMoreQualifiedThan(T2))
2726 return Ref_Compatible_With_Added_Qualification;
2727 else
2728 return Ref_Related;
2729}
2730
2731/// CheckReferenceInit - Check the initialization of a reference
2732/// variable with the given initializer (C++ [dcl.init.ref]). Init is
2733/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00002734/// list), and DeclType is the type of the declaration. When ICS is
2735/// non-null, this routine will compute the implicit conversion
2736/// sequence according to C++ [over.ics.ref] and will not produce any
2737/// diagnostics; when ICS is null, it will emit diagnostics when any
2738/// errors are found. Either way, a return value of true indicates
2739/// that there was a failure, a return value of false indicates that
2740/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00002741///
2742/// When @p SuppressUserConversions, user-defined conversions are
2743/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002744/// When @p AllowExplicit, we also permit explicit user-defined
2745/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00002746/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002747bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002748Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002749 ImplicitConversionSequence *ICS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002750 bool SuppressUserConversions,
Sebastian Redle2b68332009-04-12 17:16:29 +00002751 bool AllowExplicit, bool ForceRValue) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002752 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2753
Ted Kremenek6217b802009-07-29 21:53:49 +00002754 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002755 QualType T2 = Init->getType();
2756
Douglas Gregor904eed32008-11-10 20:40:00 +00002757 // If the initializer is the address of an overloaded function, try
2758 // to resolve the overloaded function. If all goes well, T2 is the
2759 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00002760 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00002761 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
2762 ICS != 0);
2763 if (Fn) {
2764 // Since we're performing this reference-initialization for
2765 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002766 if (!ICS) {
2767 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
2768 return true;
2769
Douglas Gregor904eed32008-11-10 20:40:00 +00002770 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002771 }
Douglas Gregor904eed32008-11-10 20:40:00 +00002772
2773 T2 = Fn->getType();
2774 }
2775 }
2776
Douglas Gregor15da57e2008-10-29 02:00:59 +00002777 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002778 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00002779 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00002780 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2781 Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00002782 ReferenceCompareResult RefRelationship
2783 = CompareReferenceRelationship(T1, T2, DerivedToBase);
2784
2785 // Most paths end in a failed conversion.
2786 if (ICS)
2787 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002788
2789 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00002790 // A reference to type "cv1 T1" is initialized by an expression
2791 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002792
2793 // -- If the initializer expression
2794
Sebastian Redla9845802009-03-29 15:27:50 +00002795 // Rvalue references cannot bind to lvalues (N2812).
2796 // There is absolutely no situation where they can. In particular, note that
2797 // this is ill-formed, even if B has a user-defined conversion to A&&:
2798 // B b;
2799 // A&& r = b;
2800 if (isRValRef && InitLvalue == Expr::LV_Valid) {
2801 if (!ICS)
2802 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
2803 << Init->getSourceRange();
2804 return true;
2805 }
2806
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002807 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00002808 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2809 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00002810 //
2811 // Note that the bit-field check is skipped if we are just computing
2812 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002813 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00002814 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002815 BindsDirectly = true;
2816
Douglas Gregor15da57e2008-10-29 02:00:59 +00002817 if (ICS) {
2818 // C++ [over.ics.ref]p1:
2819 // When a parameter of reference type binds directly (8.5.3)
2820 // to an argument expression, the implicit conversion sequence
2821 // is the identity conversion, unless the argument expression
2822 // has a type that is a derived class of the parameter type,
2823 // in which case the implicit conversion sequence is a
2824 // derived-to-base Conversion (13.3.3.1).
2825 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2826 ICS->Standard.First = ICK_Identity;
2827 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2828 ICS->Standard.Third = ICK_Identity;
2829 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2830 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002831 ICS->Standard.ReferenceBinding = true;
2832 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00002833 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00002834 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00002835
2836 // Nothing more to do: the inaccessibility/ambiguity check for
2837 // derived-to-base conversions is suppressed when we're
2838 // computing the implicit conversion sequence (C++
2839 // [over.best.ics]p2).
2840 return false;
2841 } else {
2842 // Perform the conversion.
Mike Stump390b4cc2009-05-16 07:39:55 +00002843 // FIXME: Binding to a subobject of the lvalue is going to require more
2844 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00002845 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002846 }
2847 }
2848
2849 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00002850 // implicitly converted to an lvalue of type "cv3 T3,"
2851 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002852 // 92) (this conversion is selected by enumerating the
2853 // applicable conversion functions (13.3.1.6) and choosing
2854 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00002855 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2856 !RequireCompleteType(SourceLocation(), T2, 0)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002857 // FIXME: Look for conversions in base classes!
2858 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002859 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002860
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002861 OverloadCandidateSet CandidateSet;
2862 OverloadedFunctionDecl *Conversions
2863 = T2RecordDecl->getConversionFunctions();
2864 for (OverloadedFunctionDecl::function_iterator Func
2865 = Conversions->function_begin();
2866 Func != Conversions->function_end(); ++Func) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002867 FunctionTemplateDecl *ConvTemplate
2868 = dyn_cast<FunctionTemplateDecl>(*Func);
2869 CXXConversionDecl *Conv;
2870 if (ConvTemplate)
2871 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2872 else
2873 Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redldfe292d2009-03-22 21:28:55 +00002874
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002875 // If the conversion function doesn't return a reference type,
2876 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002877 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00002878 (AllowExplicit || !Conv->isExplicit())) {
2879 if (ConvTemplate)
2880 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
2881 CandidateSet);
2882 else
2883 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
2884 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002885 }
2886
2887 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002888 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002889 case OR_Success:
2890 // This is a direct binding.
2891 BindsDirectly = true;
2892
2893 if (ICS) {
2894 // C++ [over.ics.ref]p1:
2895 //
2896 // [...] If the parameter binds directly to the result of
2897 // applying a conversion function to the argument
2898 // expression, the implicit conversion sequence is a
2899 // user-defined conversion sequence (13.3.3.1.2), with the
2900 // second standard conversion sequence either an identity
2901 // conversion or, if the conversion function returns an
2902 // entity of a type that is a derived class of the parameter
2903 // type, a derived-to-base Conversion.
2904 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
2905 ICS->UserDefined.Before = Best->Conversions[0].Standard;
2906 ICS->UserDefined.After = Best->FinalConversion;
2907 ICS->UserDefined.ConversionFunction = Best->Function;
2908 assert(ICS->UserDefined.After.ReferenceBinding &&
2909 ICS->UserDefined.After.DirectBinding &&
2910 "Expected a direct reference binding!");
2911 return false;
2912 } else {
2913 // Perform the conversion.
Mike Stump390b4cc2009-05-16 07:39:55 +00002914 // FIXME: Binding to a subobject of the lvalue is going to require more
2915 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00002916 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002917 }
2918 break;
2919
2920 case OR_Ambiguous:
2921 assert(false && "Ambiguous reference binding conversions not implemented.");
2922 return true;
2923
2924 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002925 case OR_Deleted:
2926 // There was no suitable conversion, or we found a deleted
2927 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00002928 break;
2929 }
2930 }
2931
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002932 if (BindsDirectly) {
2933 // C++ [dcl.init.ref]p4:
2934 // [...] In all cases where the reference-related or
2935 // reference-compatible relationship of two types is used to
2936 // establish the validity of a reference binding, and T1 is a
2937 // base class of T2, a program that necessitates such a binding
2938 // is ill-formed if T1 is an inaccessible (clause 11) or
2939 // ambiguous (10.2) base class of T2.
2940 //
2941 // Note that we only check this condition when we're allowed to
2942 // complain about errors, because we should not be checking for
2943 // ambiguity (or inaccessibility) unless the reference binding
2944 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002945 if (DerivedToBase)
2946 return CheckDerivedToBaseConversion(T2, T1,
2947 Init->getSourceRange().getBegin(),
2948 Init->getSourceRange());
2949 else
2950 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002951 }
2952
2953 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00002954 // type (i.e., cv1 shall be const), or the reference shall be an
2955 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002956 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00002957 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002958 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002959 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00002960 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2961 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002962 return true;
2963 }
2964
2965 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00002966 // class type, and "cv1 T1" is reference-compatible with
2967 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002968 // following ways (the choice is implementation-defined):
2969 //
2970 // -- The reference is bound to the object represented by
2971 // the rvalue (see 3.10) or to a sub-object within that
2972 // object.
2973 //
Eli Friedman33a31382009-08-05 19:21:58 +00002974 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002975 // a constructor is called to copy the entire rvalue
2976 // object into the temporary. The reference is bound to
2977 // the temporary or to a sub-object within the
2978 // temporary.
2979 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002980 // The constructor that would be used to make the copy
2981 // shall be callable whether or not the copy is actually
2982 // done.
2983 //
Sebastian Redla9845802009-03-29 15:27:50 +00002984 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002985 // freedom, so we will always take the first option and never build
2986 // a temporary in this case. FIXME: We will, however, have to check
2987 // for the presence of a copy constructor in C++98/03 mode.
2988 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00002989 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2990 if (ICS) {
2991 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2992 ICS->Standard.First = ICK_Identity;
2993 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2994 ICS->Standard.Third = ICK_Identity;
2995 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2996 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002997 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00002998 ICS->Standard.DirectBinding = false;
2999 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003000 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003001 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +00003002 // FIXME: Binding to a subobject of the rvalue is going to require more
3003 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00003004 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003005 }
3006 return false;
3007 }
3008
Eli Friedman33a31382009-08-05 19:21:58 +00003009 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003010 // initialized from the initializer expression using the
3011 // rules for a non-reference copy initialization (8.5). The
3012 // reference is then bound to the temporary. If T1 is
3013 // reference-related to T2, cv1 must be the same
3014 // cv-qualification as, or greater cv-qualification than,
3015 // cv2; otherwise, the program is ill-formed.
3016 if (RefRelationship == Ref_Related) {
3017 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3018 // we would be reference-compatible or reference-compatible with
3019 // added qualification. But that wasn't the case, so the reference
3020 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003021 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003022 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003023 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003024 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3025 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003026 return true;
3027 }
3028
Douglas Gregor734d9862009-01-30 23:27:23 +00003029 // If at least one of the types is a class type, the types are not
3030 // related, and we aren't allowed any user conversions, the
3031 // reference binding fails. This case is important for breaking
3032 // recursion, since TryImplicitConversion below will attempt to
3033 // create a temporary through the use of a copy constructor.
3034 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3035 (T1->isRecordType() || T2->isRecordType())) {
3036 if (!ICS)
3037 Diag(Init->getSourceRange().getBegin(),
3038 diag::err_typecheck_convert_incompatible)
3039 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3040 return true;
3041 }
3042
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003043 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003044 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003045 // C++ [over.ics.ref]p2:
3046 //
3047 // When a parameter of reference type is not bound directly to
3048 // an argument expression, the conversion sequence is the one
3049 // required to convert the argument expression to the
3050 // underlying type of the reference according to
3051 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3052 // to copy-initializing a temporary of the underlying type with
3053 // the argument expression. Any difference in top-level
3054 // cv-qualification is subsumed by the initialization itself
3055 // and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00003056 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Sebastian Redla9845802009-03-29 15:27:50 +00003057 // Of course, that's still a reference binding.
3058 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3059 ICS->Standard.ReferenceBinding = true;
3060 ICS->Standard.RRefBinding = isRValRef;
3061 } else if(ICS->ConversionKind ==
3062 ImplicitConversionSequence::UserDefinedConversion) {
3063 ICS->UserDefined.After.ReferenceBinding = true;
3064 ICS->UserDefined.After.RRefBinding = isRValRef;
3065 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00003066 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3067 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00003068 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00003069 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003070}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003071
3072/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3073/// of this overloaded operator is well-formed. If so, returns false;
3074/// otherwise, emits appropriate diagnostics and returns true.
3075bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003076 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003077 "Expected an overloaded operator declaration");
3078
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003079 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3080
3081 // C++ [over.oper]p5:
3082 // The allocation and deallocation functions, operator new,
3083 // operator new[], operator delete and operator delete[], are
3084 // described completely in 3.7.3. The attributes and restrictions
3085 // found in the rest of this subclause do not apply to them unless
3086 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00003087 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003088 if (Op == OO_New || Op == OO_Array_New ||
3089 Op == OO_Delete || Op == OO_Array_Delete)
3090 return false;
3091
3092 // C++ [over.oper]p6:
3093 // An operator function shall either be a non-static member
3094 // function or be a non-member function and have at least one
3095 // parameter whose type is a class, a reference to a class, an
3096 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003097 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3098 if (MethodDecl->isStatic())
3099 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003100 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003101 } else {
3102 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003103 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3104 ParamEnd = FnDecl->param_end();
3105 Param != ParamEnd; ++Param) {
3106 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00003107 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3108 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003109 ClassOrEnumParam = true;
3110 break;
3111 }
3112 }
3113
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003114 if (!ClassOrEnumParam)
3115 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003116 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003117 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003118 }
3119
3120 // C++ [over.oper]p8:
3121 // An operator function cannot have default arguments (8.3.6),
3122 // except where explicitly stated below.
3123 //
3124 // Only the function-call operator allows default arguments
3125 // (C++ [over.call]p1).
3126 if (Op != OO_Call) {
3127 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3128 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00003129 if ((*Param)->hasUnparsedDefaultArg())
3130 return Diag((*Param)->getLocation(),
3131 diag::err_operator_overload_default_arg)
3132 << FnDecl->getDeclName();
3133 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003134 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003135 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003136 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003137 }
3138 }
3139
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003140 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3141 { false, false, false }
3142#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3143 , { Unary, Binary, MemberOnly }
3144#include "clang/Basic/OperatorKinds.def"
3145 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003146
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003147 bool CanBeUnaryOperator = OperatorUses[Op][0];
3148 bool CanBeBinaryOperator = OperatorUses[Op][1];
3149 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003150
3151 // C++ [over.oper]p8:
3152 // [...] Operator functions cannot have more or fewer parameters
3153 // than the number required for the corresponding operator, as
3154 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003155 unsigned NumParams = FnDecl->getNumParams()
3156 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003157 if (Op != OO_Call &&
3158 ((NumParams == 1 && !CanBeUnaryOperator) ||
3159 (NumParams == 2 && !CanBeBinaryOperator) ||
3160 (NumParams < 1) || (NumParams > 2))) {
3161 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00003162 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003163 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003164 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003165 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003166 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003167 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003168 assert(CanBeBinaryOperator &&
3169 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00003170 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003171 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003172
Chris Lattner416e46f2008-11-21 07:57:12 +00003173 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003174 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003175 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003176
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003177 // Overloaded operators other than operator() cannot be variadic.
3178 if (Op != OO_Call &&
Douglas Gregor72564e72009-02-26 23:50:07 +00003179 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003180 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003181 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003182 }
3183
3184 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003185 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3186 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003187 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003188 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003189 }
3190
3191 // C++ [over.inc]p1:
3192 // The user-defined function called operator++ implements the
3193 // prefix and postfix ++ operator. If this function is a member
3194 // function with no parameters, or a non-member function with one
3195 // parameter of class or enumeration type, it defines the prefix
3196 // increment operator ++ for objects of that type. If the function
3197 // is a member function with one parameter (which shall be of type
3198 // int) or a non-member function with two parameters (the second
3199 // of which shall be of type int), it defines the postfix
3200 // increment operator ++ for objects of that type.
3201 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3202 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3203 bool ParamIsInt = false;
3204 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
3205 ParamIsInt = BT->getKind() == BuiltinType::Int;
3206
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003207 if (!ParamIsInt)
3208 return Diag(LastParam->getLocation(),
3209 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00003210 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003211 }
3212
Sebastian Redl64b45f72009-01-05 20:52:13 +00003213 // Notify the class if it got an assignment operator.
3214 if (Op == OO_Equal) {
3215 // Would have returned earlier otherwise.
3216 assert(isa<CXXMethodDecl>(FnDecl) &&
3217 "Overloaded = not member, but not filtered.");
3218 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanianad258832009-08-13 21:09:41 +00003219 Method->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003220 Method->getParent()->addedAssignmentOperator(Context, Method);
3221 }
3222
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003223 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003224}
Chris Lattner5a003a42008-12-17 07:09:26 +00003225
Douglas Gregor074149e2009-01-05 19:45:36 +00003226/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3227/// linkage specification, including the language and (if present)
3228/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3229/// the location of the language string literal, which is provided
3230/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3231/// the '{' brace. Otherwise, this linkage specification does not
3232/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003233Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3234 SourceLocation ExternLoc,
3235 SourceLocation LangLoc,
3236 const char *Lang,
3237 unsigned StrSize,
3238 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00003239 LinkageSpecDecl::LanguageIDs Language;
3240 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3241 Language = LinkageSpecDecl::lang_c;
3242 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3243 Language = LinkageSpecDecl::lang_cxx;
3244 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00003245 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003246 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00003247 }
3248
3249 // FIXME: Add all the various semantics of linkage specifications
3250
Douglas Gregor074149e2009-01-05 19:45:36 +00003251 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
3252 LangLoc, Language,
3253 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003254 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00003255 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003256 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00003257}
3258
Douglas Gregor074149e2009-01-05 19:45:36 +00003259/// ActOnFinishLinkageSpecification - Completely the definition of
3260/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3261/// valid, it's the position of the closing '}' brace in a linkage
3262/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003263Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3264 DeclPtrTy LinkageSpec,
3265 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00003266 if (LinkageSpec)
3267 PopDeclContext();
3268 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00003269}
3270
Douglas Gregord308e622009-05-18 20:51:54 +00003271/// \brief Perform semantic analysis for the variable declaration that
3272/// occurs within a C++ catch clause, returning the newly-created
3273/// variable.
3274VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003275 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003276 IdentifierInfo *Name,
3277 SourceLocation Loc,
3278 SourceRange Range) {
3279 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003280
3281 // Arrays and functions decay.
3282 if (ExDeclType->isArrayType())
3283 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3284 else if (ExDeclType->isFunctionType())
3285 ExDeclType = Context.getPointerType(ExDeclType);
3286
3287 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3288 // The exception-declaration shall not denote a pointer or reference to an
3289 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003290 // N2844 forbids rvalue references.
Douglas Gregor2f2433f2009-05-18 21:08:14 +00003291 if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00003292 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003293 Invalid = true;
3294 }
Douglas Gregord308e622009-05-18 20:51:54 +00003295
Sebastian Redl4b07b292008-12-22 19:15:10 +00003296 QualType BaseType = ExDeclType;
3297 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003298 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00003299 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003300 BaseType = Ptr->getPointeeType();
3301 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003302 DK = diag::err_catch_incomplete_ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003303 } else if(const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003304 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003305 BaseType = Ref->getPointeeType();
3306 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003307 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003308 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003309 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00003310 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00003311 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003312
Douglas Gregord308e622009-05-18 20:51:54 +00003313 if (!Invalid && !ExDeclType->isDependentType() &&
3314 RequireNonAbstractType(Loc, ExDeclType,
3315 diag::err_abstract_type_in_decl,
3316 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00003317 Invalid = true;
3318
Douglas Gregord308e622009-05-18 20:51:54 +00003319 // FIXME: Need to test for ability to copy-construct and destroy the
3320 // exception variable.
3321
Sebastian Redl8351da02008-12-22 21:35:02 +00003322 // FIXME: Need to check for abstract classes.
3323
Douglas Gregord308e622009-05-18 20:51:54 +00003324 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003325 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00003326
3327 if (Invalid)
3328 ExDecl->setInvalidDecl();
3329
3330 return ExDecl;
3331}
3332
3333/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3334/// handler.
3335Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003336 DeclaratorInfo *DInfo = 0;
3337 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00003338
3339 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00003340 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003341 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003342 // The scope should be freshly made just for us. There is just no way
3343 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003344 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00003345 if (PrevDecl->isTemplateParameter()) {
3346 // Maybe we will complain about the shadowed template parameter.
3347 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003348 }
3349 }
3350
Chris Lattnereaaebc72009-04-25 08:06:05 +00003351 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003352 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3353 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003354 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003355 }
3356
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003357 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003358 D.getIdentifier(),
3359 D.getIdentifierLoc(),
3360 D.getDeclSpec().getSourceRange());
3361
Chris Lattnereaaebc72009-04-25 08:06:05 +00003362 if (Invalid)
3363 ExDecl->setInvalidDecl();
3364
Sebastian Redl4b07b292008-12-22 19:15:10 +00003365 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003366 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00003367 PushOnScopeChains(ExDecl, S);
3368 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003369 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003370
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003371 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003372 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003373}
Anders Carlssonfb311762009-03-14 00:25:26 +00003374
Chris Lattnerb28317a2009-03-28 19:18:32 +00003375Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
3376 ExprArg assertexpr,
3377 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00003378 Expr *AssertExpr = (Expr *)assertexpr.get();
3379 StringLiteral *AssertMessage =
3380 cast<StringLiteral>((Expr *)assertmessageexpr.get());
3381
Anders Carlssonc3082412009-03-14 00:33:21 +00003382 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3383 llvm::APSInt Value(32);
3384 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3385 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3386 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003387 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00003388 }
Anders Carlssonfb311762009-03-14 00:25:26 +00003389
Anders Carlssonc3082412009-03-14 00:33:21 +00003390 if (Value == 0) {
3391 std::string str(AssertMessage->getStrData(),
3392 AssertMessage->getByteLength());
Anders Carlsson94b15fb2009-03-15 18:44:04 +00003393 Diag(AssertLoc, diag::err_static_assert_failed)
3394 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00003395 }
3396 }
3397
Anders Carlsson77d81422009-03-15 17:35:16 +00003398 assertexpr.release();
3399 assertmessageexpr.release();
Anders Carlssonfb311762009-03-14 00:25:26 +00003400 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
3401 AssertExpr, AssertMessage);
Anders Carlssonfb311762009-03-14 00:25:26 +00003402
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003403 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003404 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00003405}
Sebastian Redl50de12f2009-03-24 22:27:57 +00003406
John McCall67d1a672009-08-06 02:15:43 +00003407Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S,
John McCall3f9a8a62009-08-11 06:59:38 +00003408 llvm::PointerUnion<const DeclSpec*,Declarator*> DU,
3409 bool IsDefinition) {
John McCall67d1a672009-08-06 02:15:43 +00003410 Declarator *D = DU.dyn_cast<Declarator*>();
3411 const DeclSpec &DS = (D ? D->getDeclSpec() : *DU.get<const DeclSpec*>());
3412
3413 assert(DS.isFriendSpecified());
3414 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
3415
3416 // If there's no declarator, then this can only be a friend class
John McCallc48fbdf2009-08-11 21:13:21 +00003417 // declaration (or else it's just syntactically invalid).
John McCall67d1a672009-08-06 02:15:43 +00003418 if (!D) {
John McCallc48fbdf2009-08-11 21:13:21 +00003419 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00003420
John McCallc48fbdf2009-08-11 21:13:21 +00003421 QualType T;
3422 DeclContext *DC;
John McCall67d1a672009-08-06 02:15:43 +00003423
John McCallc48fbdf2009-08-11 21:13:21 +00003424 // In C++0x, we just accept any old type.
3425 if (getLangOptions().CPlusPlus0x) {
3426 bool invalid = false;
3427 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
3428 if (invalid)
3429 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00003430
John McCallc48fbdf2009-08-11 21:13:21 +00003431 // The semantic context in which to create the decl. If it's not
3432 // a record decl (or we don't yet know if it is), create it in the
3433 // current context.
3434 DC = CurContext;
3435 if (const RecordType *RT = T->getAs<RecordType>())
3436 DC = RT->getDecl()->getDeclContext();
3437
3438 // The C++98 rules are somewhat more complex.
3439 } else {
3440 // C++ [class.friend]p2:
3441 // An elaborated-type-specifier shall be used in a friend declaration
3442 // for a class.*
3443 // * The class-key of the elaborated-type-specifier is required.
3444 CXXRecordDecl *RD = 0;
3445
3446 switch (DS.getTypeSpecType()) {
3447 case DeclSpec::TST_class:
3448 case DeclSpec::TST_struct:
3449 case DeclSpec::TST_union:
3450 RD = dyn_cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
3451 if (!RD) return DeclPtrTy();
3452 break;
3453
3454 case DeclSpec::TST_typename:
3455 if (const RecordType *RT =
3456 ((const Type*) DS.getTypeRep())->getAs<RecordType>())
3457 RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
3458 // fallthrough
3459 default:
3460 if (RD) {
3461 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
3462 << (RD->isUnion())
3463 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
3464 RD->isUnion() ? " union" : " class");
3465 return DeclPtrTy::make(RD);
3466 }
3467
3468 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
3469 << DS.getSourceRange();
3470 return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00003471 }
3472
John McCallc48fbdf2009-08-11 21:13:21 +00003473 // The record declaration we get from friend declarations is not
3474 // canonicalized; see ActOnTag.
John McCallc48fbdf2009-08-11 21:13:21 +00003475
3476 // C++ [class.friend]p2: A class shall not be defined inside
3477 // a friend declaration.
3478 if (RD->isDefinition())
3479 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
3480 << RD->getSourceRange();
3481
3482 // C++98 [class.friend]p1: A friend of a class is a function
3483 // or class that is not a member of the class . . .
3484 // But that's a silly restriction which nobody implements for
3485 // inner classes, and C++0x removes it anyway, so we only report
3486 // this (as a warning) if we're being pedantic.
3487 //
3488 // Also, definitions currently get treated in a way that causes
3489 // this error, so only report it if we didn't see a definition.
3490 else if (RD->getDeclContext() == CurContext &&
3491 !getLangOptions().CPlusPlus0x)
3492 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
3493
3494 T = QualType(RD->getTypeForDecl(), 0);
3495 DC = RD->getDeclContext();
John McCall67d1a672009-08-06 02:15:43 +00003496 }
3497
John McCallc48fbdf2009-08-11 21:13:21 +00003498 FriendClassDecl *FCD = FriendClassDecl::Create(Context, DC, Loc, T,
3499 DS.getFriendSpecLoc());
3500 FCD->setLexicalDeclContext(CurContext);
John McCall67d1a672009-08-06 02:15:43 +00003501
John McCallc48fbdf2009-08-11 21:13:21 +00003502 if (CurContext->isDependentContext())
3503 CurContext->addHiddenDecl(FCD);
3504 else
3505 CurContext->addDecl(FCD);
John McCall67d1a672009-08-06 02:15:43 +00003506
John McCallc48fbdf2009-08-11 21:13:21 +00003507 return DeclPtrTy::make(FCD);
Anders Carlsson00338362009-05-11 22:55:49 +00003508 }
John McCall67d1a672009-08-06 02:15:43 +00003509
3510 // We have a declarator.
3511 assert(D);
3512
3513 SourceLocation Loc = D->getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003514 DeclaratorInfo *DInfo = 0;
3515 QualType T = GetTypeForDeclarator(*D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00003516
3517 // C++ [class.friend]p1
3518 // A friend of a class is a function or class....
3519 // Note that this sees through typedefs, which is intended.
3520 if (!T->isFunctionType()) {
3521 Diag(Loc, diag::err_unexpected_friend);
3522
3523 // It might be worthwhile to try to recover by creating an
3524 // appropriate declaration.
3525 return DeclPtrTy();
3526 }
3527
3528 // C++ [namespace.memdef]p3
3529 // - If a friend declaration in a non-local class first declares a
3530 // class or function, the friend class or function is a member
3531 // of the innermost enclosing namespace.
3532 // - The name of the friend is not found by simple name lookup
3533 // until a matching declaration is provided in that namespace
3534 // scope (either before or after the class declaration granting
3535 // friendship).
3536 // - If a friend function is called, its name may be found by the
3537 // name lookup that considers functions from namespaces and
3538 // classes associated with the types of the function arguments.
3539 // - When looking for a prior declaration of a class or a function
3540 // declared as a friend, scopes outside the innermost enclosing
3541 // namespace scope are not considered.
3542
3543 CXXScopeSpec &ScopeQual = D->getCXXScopeSpec();
3544 DeclarationName Name = GetNameForDeclarator(*D);
3545 assert(Name);
3546
3547 // The existing declaration we found.
3548 FunctionDecl *FD = NULL;
3549
3550 // The context we found the declaration in, or in which we should
3551 // create the declaration.
3552 DeclContext *DC;
3553
3554 // FIXME: handle local classes
3555
3556 // Recover from invalid scope qualifiers as if they just weren't there.
3557 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
3558 DC = computeDeclContext(ScopeQual);
3559
3560 // FIXME: handle dependent contexts
3561 if (!DC) return DeclPtrTy();
3562
3563 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3564
3565 // If searching in that context implicitly found a declaration in
3566 // a different context, treat it like it wasn't found at all.
3567 // TODO: better diagnostics for this case. Suggesting the right
3568 // qualified scope would be nice...
3569 if (!Dec || Dec->getDeclContext() != DC) {
3570 D->setInvalidType();
3571 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
3572 return DeclPtrTy();
3573 }
3574
3575 // C++ [class.friend]p1: A friend of a class is a function or
3576 // class that is not a member of the class . . .
3577 if (DC == CurContext)
3578 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
3579
3580 FD = cast<FunctionDecl>(Dec);
3581
3582 // Otherwise walk out to the nearest namespace scope looking for matches.
3583 } else {
3584 // TODO: handle local class contexts.
3585
3586 DC = CurContext;
3587 while (true) {
3588 // Skip class contexts. If someone can cite chapter and verse
3589 // for this behavior, that would be nice --- it's what GCC and
3590 // EDG do, and it seems like a reasonable intent, but the spec
3591 // really only says that checks for unqualified existing
3592 // declarations should stop at the nearest enclosing namespace,
3593 // not that they should only consider the nearest enclosing
3594 // namespace.
3595 while (DC->isRecord()) DC = DC->getParent();
3596
3597 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3598
3599 // TODO: decide what we think about using declarations.
3600 if (Dec) {
3601 FD = cast<FunctionDecl>(Dec);
3602 break;
3603 }
3604 if (DC->isFileContext()) break;
3605 DC = DC->getParent();
3606 }
3607
3608 // C++ [class.friend]p1: A friend of a class is a function or
3609 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00003610 // C++0x changes this for both friend types and functions.
3611 // Most C++ 98 compilers do seem to give an error here, so
3612 // we do, too.
3613 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00003614 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
3615 }
3616
John McCall3f9a8a62009-08-11 06:59:38 +00003617 bool Redeclaration = (FD != 0);
3618
3619 // If we found a match, create a friend function declaration with
3620 // that function as the previous declaration.
3621 if (Redeclaration) {
3622 // Create it in the semantic context of the original declaration.
3623 DC = FD->getDeclContext();
3624
John McCall67d1a672009-08-06 02:15:43 +00003625 // If we didn't find something matching the type exactly, create
3626 // a declaration. This declaration should only be findable via
3627 // argument-dependent lookup.
John McCall3f9a8a62009-08-11 06:59:38 +00003628 } else {
John McCall67d1a672009-08-06 02:15:43 +00003629 assert(DC->isFileContext());
3630
3631 // This implies that it has to be an operator or function.
3632 if (D->getKind() == Declarator::DK_Constructor ||
3633 D->getKind() == Declarator::DK_Destructor ||
3634 D->getKind() == Declarator::DK_Conversion) {
3635 Diag(Loc, diag::err_introducing_special_friend) <<
3636 (D->getKind() == Declarator::DK_Constructor ? 0 :
3637 D->getKind() == Declarator::DK_Destructor ? 1 : 2);
3638 return DeclPtrTy();
3639 }
John McCall67d1a672009-08-06 02:15:43 +00003640 }
3641
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003642 NamedDecl *ND = ActOnFunctionDeclarator(S, *D, DC, T, DInfo,
John McCall3f9a8a62009-08-11 06:59:38 +00003643 /* PrevDecl = */ FD,
3644 MultiTemplateParamsArg(*this),
3645 IsDefinition,
3646 Redeclaration);
3647 FD = cast_or_null<FriendFunctionDecl>(ND);
3648
John McCall88232aa2009-08-18 00:00:49 +00003649 assert(FD->getDeclContext() == DC);
3650 assert(FD->getLexicalDeclContext() == CurContext);
3651
John McCall3f9a8a62009-08-11 06:59:38 +00003652 // If this is a dependent context, just add the decl to the
3653 // class's decl list and don't both with the lookup tables. This
3654 // doesn't affect lookup because any call that might find this
3655 // function via ADL necessarily has to involve dependently-typed
3656 // arguments and hence can't be resolved until
3657 // template-instantiation anyway.
3658 if (CurContext->isDependentContext())
3659 CurContext->addHiddenDecl(FD);
3660 else
3661 CurContext->addDecl(FD);
John McCall67d1a672009-08-06 02:15:43 +00003662
3663 return DeclPtrTy::make(FD);
Anders Carlsson00338362009-05-11 22:55:49 +00003664}
3665
Chris Lattnerb28317a2009-03-28 19:18:32 +00003666void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003667 AdjustDeclIfTemplate(dcl);
3668
Chris Lattnerb28317a2009-03-28 19:18:32 +00003669 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00003670 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
3671 if (!Fn) {
3672 Diag(DelLoc, diag::err_deleted_non_function);
3673 return;
3674 }
3675 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
3676 Diag(DelLoc, diag::err_deleted_decl_not_first);
3677 Diag(Prev->getLocation(), diag::note_previous_declaration);
3678 // If the declaration wasn't the first, we delete the function anyway for
3679 // recovery.
3680 }
3681 Fn->setDeleted();
3682}
Sebastian Redl13e88542009-04-27 21:33:24 +00003683
3684static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
3685 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
3686 ++CI) {
3687 Stmt *SubStmt = *CI;
3688 if (!SubStmt)
3689 continue;
3690 if (isa<ReturnStmt>(SubStmt))
3691 Self.Diag(SubStmt->getSourceRange().getBegin(),
3692 diag::err_return_in_constructor_handler);
3693 if (!isa<Expr>(SubStmt))
3694 SearchForReturnInStmt(Self, SubStmt);
3695 }
3696}
3697
3698void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
3699 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
3700 CXXCatchStmt *Handler = TryBlock->getHandler(I);
3701 SearchForReturnInStmt(*this, Handler);
3702 }
3703}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003704
3705bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3706 const CXXMethodDecl *Old) {
3707 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
3708 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
3709
3710 QualType CNewTy = Context.getCanonicalType(NewTy);
3711 QualType COldTy = Context.getCanonicalType(OldTy);
3712
3713 if (CNewTy == COldTy &&
3714 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
3715 return false;
3716
Anders Carlssonc3a68b22009-05-14 19:52:19 +00003717 // Check if the return types are covariant
3718 QualType NewClassTy, OldClassTy;
3719
3720 /// Both types must be pointers or references to classes.
3721 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
3722 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
3723 NewClassTy = NewPT->getPointeeType();
3724 OldClassTy = OldPT->getPointeeType();
3725 }
3726 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
3727 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
3728 NewClassTy = NewRT->getPointeeType();
3729 OldClassTy = OldRT->getPointeeType();
3730 }
3731 }
3732
3733 // The return types aren't either both pointers or references to a class type.
3734 if (NewClassTy.isNull()) {
3735 Diag(New->getLocation(),
3736 diag::err_different_return_type_for_overriding_virtual_function)
3737 << New->getDeclName() << NewTy << OldTy;
3738 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3739
3740 return true;
3741 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003742
Anders Carlssonc3a68b22009-05-14 19:52:19 +00003743 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
3744 // Check if the new class derives from the old class.
3745 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
3746 Diag(New->getLocation(),
3747 diag::err_covariant_return_not_derived)
3748 << New->getDeclName() << NewTy << OldTy;
3749 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3750 return true;
3751 }
3752
3753 // Check if we the conversion from derived to base is valid.
3754 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
3755 diag::err_covariant_return_inaccessible_base,
3756 diag::err_covariant_return_ambiguous_derived_to_base_conv,
3757 // FIXME: Should this point to the return type?
3758 New->getLocation(), SourceRange(), New->getDeclName())) {
3759 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3760 return true;
3761 }
3762 }
3763
3764 // The qualifiers of the return types must be the same.
3765 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
3766 Diag(New->getLocation(),
3767 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003768 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00003769 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3770 return true;
3771 };
3772
3773
3774 // The new class type must have the same or less qualifiers as the old type.
3775 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
3776 Diag(New->getLocation(),
3777 diag::err_covariant_return_type_class_type_more_qualified)
3778 << New->getDeclName() << NewTy << OldTy;
3779 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3780 return true;
3781 };
3782
3783 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003784}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003785
Sebastian Redl23c7d062009-07-07 20:29:57 +00003786bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
3787 const CXXMethodDecl *Old)
3788{
3789 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
3790 diag::note_overridden_virtual_function,
3791 Old->getType()->getAsFunctionProtoType(),
3792 Old->getLocation(),
3793 New->getType()->getAsFunctionProtoType(),
3794 New->getLocation());
3795}
3796
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003797/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3798/// initializer for the declaration 'Dcl'.
3799/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3800/// static data member of class X, names should be looked up in the scope of
3801/// class X.
3802void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003803 AdjustDeclIfTemplate(Dcl);
3804
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003805 Decl *D = Dcl.getAs<Decl>();
3806 // If there is no declaration, there was an error parsing it.
3807 if (D == 0)
3808 return;
3809
3810 // Check whether it is a declaration with a nested name specifier like
3811 // int foo::bar;
3812 if (!D->isOutOfLine())
3813 return;
3814
3815 // C++ [basic.lookup.unqual]p13
3816 //
3817 // A name used in the definition of a static data member of class X
3818 // (after the qualified-id of the static member) is looked up as if the name
3819 // was used in a member function of X.
3820
3821 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00003822 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003823}
3824
3825/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3826/// initializer for the declaration 'Dcl'.
3827void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003828 AdjustDeclIfTemplate(Dcl);
3829
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003830 Decl *D = Dcl.getAs<Decl>();
3831 // If there is no declaration, there was an error parsing it.
3832 if (D == 0)
3833 return;
3834
3835 // Check whether it is a declaration with a nested name specifier like
3836 // int foo::bar;
3837 if (!D->isOutOfLine())
3838 return;
3839
3840 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00003841 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003842}