blob: 89ea7cce27b3d7e1481e4a1ec18189abd9ec1944 [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"
Anders Carlssonb7906612009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000027#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000028
29using namespace clang;
30
Chris Lattner8123a952008-04-10 02:22:51 +000031//===----------------------------------------------------------------------===//
32// CheckDefaultArgumentVisitor
33//===----------------------------------------------------------------------===//
34
Chris Lattner9e979552008-04-12 23:52:44 +000035namespace {
36 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
37 /// the default argument of a parameter to determine whether it
38 /// contains any ill-formed subexpressions. For example, this will
39 /// diagnose the use of local variables or parameters within the
40 /// default argument expression.
41 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerb77792e2008-07-26 22:17:49 +000042 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000043 Expr *DefaultArg;
44 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000045
Chris Lattner9e979552008-04-12 23:52:44 +000046 public:
47 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
48 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000049
Chris Lattner9e979552008-04-12 23:52:44 +000050 bool VisitExpr(Expr *Node);
51 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000052 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000053 };
Chris Lattner8123a952008-04-10 02:22:51 +000054
Chris Lattner9e979552008-04-12 23:52:44 +000055 /// VisitExpr - Visit all of the children of this expression.
56 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
57 bool IsInvalid = false;
Chris Lattnerb77792e2008-07-26 22:17:49 +000058 for (Stmt::child_iterator I = Node->child_begin(),
59 E = Node->child_end(); I != E; ++I)
60 IsInvalid |= Visit(*I);
Chris Lattner9e979552008-04-12 23:52:44 +000061 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000062 }
63
Chris Lattner9e979552008-04-12 23:52:44 +000064 /// VisitDeclRefExpr - Visit a reference to a declaration, to
65 /// determine whether this declaration can be used in the default
66 /// argument expression.
67 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000068 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-04-12 23:52:44 +000069 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
70 // C++ [dcl.fct.default]p9
71 // Default arguments are evaluated each time the function is
72 // called. The order of evaluation of function arguments is
73 // unspecified. Consequently, parameters of a function shall not
74 // be used in default argument expressions, even if they are not
75 // evaluated. Parameters of a function declared before a default
76 // argument expression are in scope and can hide namespace and
77 // class member names.
78 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000079 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000080 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000081 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000082 // C++ [dcl.fct.default]p7
83 // Local variables shall not be used in default argument
84 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000085 if (VDecl->isBlockVarDecl())
86 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000088 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000089 }
Chris Lattner8123a952008-04-10 02:22:51 +000090
Douglas Gregor3996f232008-11-04 13:41:56 +000091 return false;
92 }
Chris Lattner9e979552008-04-12 23:52:44 +000093
Douglas Gregor796da182008-11-04 14:32:21 +000094 /// VisitCXXThisExpr - Visit a C++ "this" expression.
95 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
96 // C++ [dcl.fct.default]p8:
97 // The keyword this shall not be used in a default argument of a
98 // member function.
99 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_this)
101 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000102 }
Chris Lattner8123a952008-04-10 02:22:51 +0000103}
104
Anders Carlssoned961f92009-08-25 02:29:20 +0000105bool
106Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
107 SourceLocation EqualLoc)
108{
109 QualType ParamType = Param->getType();
110
Anders Carlsson5653ca52009-08-25 13:46:13 +0000111 if (RequireCompleteType(Param->getLocation(), Param->getType(),
112 diag::err_typecheck_decl_incomplete_type)) {
113 Param->setInvalidDecl();
114 return true;
115 }
116
Anders Carlssoned961f92009-08-25 02:29:20 +0000117 Expr *Arg = (Expr *)DefaultArg.get();
118
119 // C++ [dcl.fct.default]p5
120 // A default argument expression is implicitly converted (clause
121 // 4) to the parameter type. The default argument expression has
122 // the same semantic constraints as the initializer expression in
123 // a declaration of a variable of the parameter type, using the
124 // copy-initialization semantics (8.5).
125 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
126 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson9351c172009-08-25 03:18:48 +0000127 return true;
Anders Carlssoned961f92009-08-25 02:29:20 +0000128
129 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
130
131 // Okay: add the default argument to the parameter
132 Param->setDefaultArg(Arg);
133
134 DefaultArg.release();
135
Anders Carlsson9351c172009-08-25 03:18:48 +0000136 return false;
Anders Carlssoned961f92009-08-25 02:29:20 +0000137}
138
Chris Lattner8123a952008-04-10 02:22:51 +0000139/// ActOnParamDefaultArgument - Check whether the default argument
140/// provided for a function parameter is well-formed. If so, attach it
141/// to the parameter declaration.
Chris Lattner3d1cee32008-04-08 05:04:30 +0000142void
Chris Lattnerb28317a2009-03-28 19:18:32 +0000143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +0000144 ExprArg defarg) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000145 if (!param || !defarg.get())
146 return;
147
Chris Lattnerb28317a2009-03-28 19:18:32 +0000148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlsson5e300d12009-06-12 16:51:40 +0000149 UnparsedDefaultArgLocs.erase(Param);
150
Anders Carlssonf1b1d592009-05-01 19:30:39 +0000151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattner3d1cee32008-04-08 05:04:30 +0000152 QualType ParamType = Param->getType();
153
154 // Default arguments are only permitted in C++
155 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000156 Diag(EqualLoc, diag::err_param_default_argument)
157 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000158 Param->setInvalidDecl();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000159 return;
160 }
161
Anders Carlsson66e30672009-08-25 01:02:06 +0000162 // Check that the default argument is well-formed
163 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
164 if (DefaultArgChecker.Visit(DefaultArg.get())) {
165 Param->setInvalidDecl();
166 return;
167 }
168
Anders Carlssoned961f92009-08-25 02:29:20 +0000169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000170}
171
Douglas Gregor61366e92008-12-24 00:01:03 +0000172/// ActOnParamUnparsedDefaultArgument - We've seen a default
173/// argument for a function parameter, but we can't parse it yet
174/// because we're inside a class definition. Note that this default
175/// argument will be parsed later.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlsson5e300d12009-06-12 16:51:40 +0000177 SourceLocation EqualLoc,
178 SourceLocation ArgLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000179 if (!param)
180 return;
181
Chris Lattnerb28317a2009-03-28 19:18:32 +0000182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000183 if (Param)
184 Param->setUnparsedDefaultArg();
Anders Carlsson5e300d12009-06-12 16:51:40 +0000185
186 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor61366e92008-12-24 00:01:03 +0000187}
188
Douglas Gregor72b505b2008-12-16 21:30:33 +0000189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
190/// the default argument for the parameter param failed.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000192 if (!param)
193 return;
194
Anders Carlsson5e300d12009-06-12 16:51:40 +0000195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
196
197 Param->setInvalidDecl();
198
199 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000200}
201
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000202/// CheckExtraCXXDefaultArguments - Check for any extra default
203/// arguments in the declarator, which is not a function declaration
204/// or definition and therefore is not permitted to have default
205/// arguments. This routine should be invoked for every declarator
206/// that is not a function declaration or definition.
207void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
208 // C++ [dcl.fct.default]p3
209 // A default argument expression shall be specified only in the
210 // parameter-declaration-clause of a function declaration or in a
211 // template-parameter (14.1). It shall not be specified for a
212 // parameter pack. If it is specified in a
213 // parameter-declaration-clause, it shall not occur within a
214 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000216 DeclaratorChunk &chunk = D.getTypeObject(i);
217 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000218 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
219 ParmVarDecl *Param =
220 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +0000221 if (Param->hasUnparsedDefaultArg()) {
222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000223 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
224 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
225 delete Toks;
226 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor61366e92008-12-24 00:01:03 +0000227 } else if (Param->getDefaultArg()) {
228 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
229 << Param->getDefaultArg()->getSourceRange();
230 Param->setDefaultArg(0);
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000231 }
232 }
233 }
234 }
235}
236
Chris Lattner3d1cee32008-04-08 05:04:30 +0000237// MergeCXXFunctionDecl - Merge two declarations of the same C++
238// function, once we already know that they have the same
Douglas Gregorcda9c672009-02-16 17:45:42 +0000239// type. Subroutine of MergeFunctionDecl. Returns true if there was an
240// error, false otherwise.
241bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
242 bool Invalid = false;
243
Chris Lattner3d1cee32008-04-08 05:04:30 +0000244 // C++ [dcl.fct.default]p4:
245 //
246 // For non-template functions, default arguments can be added in
247 // later declarations of a function in the same
248 // scope. Declarations in different scopes have completely
249 // distinct sets of default arguments. That is, declarations in
250 // inner scopes do not acquire default arguments from
251 // declarations in outer scopes, and vice versa. In a given
252 // function declaration, all parameters subsequent to a
253 // parameter with a default argument shall have default
254 // arguments supplied in this or previous declarations. A
255 // default argument shall not be redefined by a later
256 // declaration (not even to the same value).
257 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
258 ParmVarDecl *OldParam = Old->getParamDecl(p);
259 ParmVarDecl *NewParam = New->getParamDecl(p);
260
261 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
262 Diag(NewParam->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000263 diag::err_param_default_argument_redefinition)
264 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000265 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000266 Invalid = true;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000267 } else if (OldParam->getDefaultArg()) {
268 // Merge the old default argument into the new parameter
269 NewParam->setDefaultArg(OldParam->getDefaultArg());
270 }
271 }
272
Sebastian Redl4994d2d2009-07-04 11:39:00 +0000273 if (CheckEquivalentExceptionSpec(
274 Old->getType()->getAsFunctionProtoType(), Old->getLocation(),
275 New->getType()->getAsFunctionProtoType(), New->getLocation())) {
276 Invalid = true;
277 }
278
Douglas Gregorcda9c672009-02-16 17:45:42 +0000279 return Invalid;
Chris Lattner3d1cee32008-04-08 05:04:30 +0000280}
281
282/// CheckCXXDefaultArguments - Verify that the default arguments for a
283/// function declaration are well-formed according to C++
284/// [dcl.fct.default].
285void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
286 unsigned NumParams = FD->getNumParams();
287 unsigned p;
288
289 // Find first parameter with a default argument
290 for (p = 0; p < NumParams; ++p) {
291 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000292 if (Param->hasDefaultArg())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000293 break;
294 }
295
296 // C++ [dcl.fct.default]p4:
297 // In a given function declaration, all parameters
298 // subsequent to a parameter with a default argument shall
299 // have default arguments supplied in this or previous
300 // declarations. A default argument shall not be redefined
301 // by a later declaration (not even to the same value).
302 unsigned LastMissingDefaultArg = 0;
303 for(; p < NumParams; ++p) {
304 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5f49a0c2009-08-25 01:23:32 +0000305 if (!Param->hasDefaultArg()) {
Douglas Gregor72b505b2008-12-16 21:30:33 +0000306 if (Param->isInvalidDecl())
307 /* We already complained about this parameter. */;
308 else if (Param->getIdentifier())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000309 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000310 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000311 << Param->getIdentifier();
Chris Lattner3d1cee32008-04-08 05:04:30 +0000312 else
313 Diag(Param->getLocation(),
314 diag::err_param_default_argument_missing);
315
316 LastMissingDefaultArg = p;
317 }
318 }
319
320 if (LastMissingDefaultArg > 0) {
321 // Some default arguments were missing. Clear out all of the
322 // default arguments up to (and including) the last missing
323 // default argument, so that we leave the function parameters
324 // in a semantically valid state.
325 for (p = 0; p <= LastMissingDefaultArg; ++p) {
326 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson5e300d12009-06-12 16:51:40 +0000327 if (Param->hasDefaultArg()) {
Douglas Gregor61366e92008-12-24 00:01:03 +0000328 if (!Param->hasUnparsedDefaultArg())
329 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000330 Param->setDefaultArg(0);
331 }
332 }
333 }
334}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000335
Douglas Gregorb48fe382008-10-31 09:07:45 +0000336/// isCurrentClassName - Determine whether the identifier II is the
337/// name of the class type currently being defined. In the case of
338/// nested classes, this will only return true if II is the name of
339/// the innermost class.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000340bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
341 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000342 CXXRecordDecl *CurDecl;
Douglas Gregore4e5b052009-03-19 00:18:19 +0000343 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregorac373c42009-08-21 22:16:40 +0000344 DeclContext *DC = computeDeclContext(*SS, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000345 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
346 } else
347 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
348
349 if (CurDecl)
Douglas Gregorb48fe382008-10-31 09:07:45 +0000350 return &II == CurDecl->getIdentifier();
351 else
352 return false;
353}
354
Douglas Gregor2943aed2009-03-03 04:44:36 +0000355/// \brief Check the validity of a C++ base class specifier.
356///
357/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
358/// and returns NULL otherwise.
359CXXBaseSpecifier *
360Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
361 SourceRange SpecifierRange,
362 bool Virtual, AccessSpecifier Access,
363 QualType BaseType,
364 SourceLocation BaseLoc) {
365 // C++ [class.union]p1:
366 // A union shall not have base classes.
367 if (Class->isUnion()) {
368 Diag(Class->getLocation(), diag::err_base_clause_on_union)
369 << SpecifierRange;
370 return 0;
371 }
372
373 if (BaseType->isDependentType())
Fariborz Jahanian71c6e712009-07-22 17:41:53 +0000374 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000375 Class->getTagKind() == RecordDecl::TK_class,
376 Access, BaseType);
377
378 // Base specifiers must be record types.
379 if (!BaseType->isRecordType()) {
380 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
381 return 0;
382 }
383
384 // C++ [class.union]p1:
385 // A union shall not be used as a base class.
386 if (BaseType->isUnionType()) {
387 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
388 return 0;
389 }
390
391 // C++ [class.derived]p2:
392 // The class-name in a base-specifier shall not be an incompletely
393 // defined class.
Anders Carlssonb7906612009-08-26 23:45:07 +0000394 if (RequireCompleteType(BaseLoc, BaseType,
395 PDiag(diag::err_incomplete_base_class)
396 << SpecifierRange))
Douglas Gregor2943aed2009-03-03 04:44:36 +0000397 return 0;
398
Eli Friedman1d954f62009-08-15 21:55:26 +0000399 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenek6217b802009-07-29 21:53:49 +0000400 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregor2943aed2009-03-03 04:44:36 +0000401 assert(BaseDecl && "Record type has no declaration");
402 BaseDecl = BaseDecl->getDefinition(Context);
403 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman1d954f62009-08-15 21:55:26 +0000404 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
405 assert(CXXBaseDecl && "Base type is not a C++ type");
406 if (!CXXBaseDecl->isEmpty())
407 Class->setEmpty(false);
408 if (CXXBaseDecl->isPolymorphic())
Douglas Gregor2943aed2009-03-03 04:44:36 +0000409 Class->setPolymorphic(true);
410
411 // C++ [dcl.init.aggr]p1:
412 // An aggregate is [...] a class with [...] no base classes [...].
413 Class->setAggregate(false);
414 Class->setPOD(false);
415
Anders Carlsson347ba892009-04-16 00:08:20 +0000416 if (Virtual) {
417 // C++ [class.ctor]p5:
418 // A constructor is trivial if its class has no virtual base classes.
419 Class->setHasTrivialConstructor(false);
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000420
421 // C++ [class.copy]p6:
422 // A copy constructor is trivial if its class has no virtual base classes.
423 Class->setHasTrivialCopyConstructor(false);
424
425 // C++ [class.copy]p11:
426 // A copy assignment operator is trivial if its class has no virtual
427 // base classes.
428 Class->setHasTrivialCopyAssignment(false);
Eli Friedman1d954f62009-08-15 21:55:26 +0000429
430 // C++0x [meta.unary.prop] is_empty:
431 // T is a class type, but not a union type, with ... no virtual base
432 // classes
433 Class->setEmpty(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000434 } else {
435 // C++ [class.ctor]p5:
436 // A constructor is trivial if all the direct base classes of its
437 // class have trivial constructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000438 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
439 Class->setHasTrivialConstructor(false);
440
441 // C++ [class.copy]p6:
442 // A copy constructor is trivial if all the direct base classes of its
443 // class have trivial copy constructors.
444 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
445 Class->setHasTrivialCopyConstructor(false);
446
447 // C++ [class.copy]p11:
448 // A copy assignment operator is trivial if all the direct base classes
449 // of its class have trivial copy assignment operators.
450 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
451 Class->setHasTrivialCopyAssignment(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000452 }
Anders Carlsson072abef2009-04-17 02:34:54 +0000453
454 // C++ [class.ctor]p3:
455 // A destructor is trivial if all the direct base classes of its class
456 // have trivial destructors.
Douglas Gregor1f2023a2009-07-22 18:25:24 +0000457 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
458 Class->setHasTrivialDestructor(false);
Anders Carlsson347ba892009-04-16 00:08:20 +0000459
Douglas Gregor2943aed2009-03-03 04:44:36 +0000460 // Create the base specifier.
461 // FIXME: Allocate via ASTContext?
Fariborz Jahanian71c6e712009-07-22 17:41:53 +0000462 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000463 Class->getTagKind() == RecordDecl::TK_class,
464 Access, BaseType);
465}
466
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000467/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
468/// one entry in the base class list of a class specifier, for
469/// example:
470/// class foo : public bar, virtual private baz {
471/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000472Sema::BaseResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000473Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000474 bool Virtual, AccessSpecifier Access,
475 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000476 if (!classdecl)
477 return true;
478
Douglas Gregor40808ce2009-03-09 23:48:35 +0000479 AdjustDeclIfTemplate(classdecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000480 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000481 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000482 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
483 Virtual, Access,
484 BaseType, BaseLoc))
485 return BaseSpec;
486
487 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000488}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000489
Douglas Gregor2943aed2009-03-03 04:44:36 +0000490/// \brief Performs the actual work of attaching the given base class
491/// specifiers to a C++ class.
492bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
493 unsigned NumBases) {
494 if (NumBases == 0)
495 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000496
497 // Used to keep track of which base types we have already seen, so
498 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000499 // that the key is always the unqualified canonical type of the base
500 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000501 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
502
503 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000504 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000505 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000506 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000507 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000508 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000509 NewBaseType = NewBaseType.getUnqualifiedType();
510
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000511 if (KnownBaseTypes[NewBaseType]) {
512 // C++ [class.mi]p3:
513 // A class shall not be specified as a direct base class of a
514 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000515 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000516 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000517 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000518 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000519
520 // Delete the duplicate base class specifier; we're going to
521 // overwrite its pointer later.
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000522 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000523
524 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000525 } else {
526 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000527 KnownBaseTypes[NewBaseType] = Bases[idx];
528 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000529 }
530 }
531
532 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian5ffcd7b2009-07-02 18:26:15 +0000533 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000534
535 // Delete the remaining (good) base class specifiers, since their
536 // data has been copied into the CXXRecordDecl.
537 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2aef06d2009-07-22 20:55:49 +0000538 Context.Deallocate(Bases[idx]);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000539
540 return Invalid;
541}
542
543/// ActOnBaseSpecifiers - Attach the given base specifiers to the
544/// class, after checking whether there are any duplicate base
545/// classes.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000546void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregor2943aed2009-03-03 04:44:36 +0000547 unsigned NumBases) {
548 if (!ClassDecl || !Bases || !NumBases)
549 return;
550
551 AdjustDeclIfTemplate(ClassDecl);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000552 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregor2943aed2009-03-03 04:44:36 +0000553 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000554}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000555
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000556//===----------------------------------------------------------------------===//
557// C++ class member Handling
558//===----------------------------------------------------------------------===//
559
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000560/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
561/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
562/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerb6688e02009-04-12 22:37:57 +0000563/// any.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000564Sema::DeclPtrTy
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000565Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor37b372b2009-08-20 22:52:58 +0000566 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redle2b68332009-04-12 17:16:29 +0000567 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000568 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000569 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000570 Expr *BitWidth = static_cast<Expr*>(BW);
571 Expr *Init = static_cast<Expr*>(InitExpr);
572 SourceLocation Loc = D.getIdentifierLoc();
573
Sebastian Redl669d5d72008-11-14 23:42:31 +0000574 bool isFunc = D.isFunctionDeclarator();
575
John McCall67d1a672009-08-06 02:15:43 +0000576 assert(!DS.isFriendSpecified());
577
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000578 // C++ 9.2p6: A member shall not be declared to have automatic storage
579 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000580 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
581 // data members and cannot be applied to names declared const or static,
582 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000583 switch (DS.getStorageClassSpec()) {
584 case DeclSpec::SCS_unspecified:
585 case DeclSpec::SCS_typedef:
586 case DeclSpec::SCS_static:
587 // FALL THROUGH.
588 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000589 case DeclSpec::SCS_mutable:
590 if (isFunc) {
591 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000592 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000593 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000594 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
595
Sebastian Redla11f42f2008-11-17 23:24:37 +0000596 // FIXME: It would be nicer if the keyword was ignored only for this
597 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000598 D.getMutableDeclSpec().ClearStorageClassSpecs();
599 } else {
600 QualType T = GetTypeForDeclarator(D, S);
601 diag::kind err = static_cast<diag::kind>(0);
602 if (T->isReferenceType())
603 err = diag::err_mutable_reference;
604 else if (T.isConstQualified())
605 err = diag::err_mutable_const;
606 if (err != 0) {
607 if (DS.getStorageClassSpecLoc().isValid())
608 Diag(DS.getStorageClassSpecLoc(), err);
609 else
610 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000611 // FIXME: It would be nicer if the keyword was ignored only for this
612 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000613 D.getMutableDeclSpec().ClearStorageClassSpecs();
614 }
615 }
616 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000617 default:
618 if (DS.getStorageClassSpecLoc().isValid())
619 Diag(DS.getStorageClassSpecLoc(),
620 diag::err_storageclass_invalid_for_member);
621 else
622 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
623 D.getMutableDeclSpec().ClearStorageClassSpecs();
624 }
625
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000626 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000627 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000628 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000629 // Check also for this case:
630 //
631 // typedef int f();
632 // f a;
633 //
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000634 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000635 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000636 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000637
Sebastian Redl669d5d72008-11-14 23:42:31 +0000638 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
639 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000640 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000641
642 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000643 if (isInstField) {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000644 // FIXME: Check for template parameters!
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000645 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
646 AS);
Chris Lattner6f8ce142009-03-05 23:03:49 +0000647 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000648 } else {
Douglas Gregor37b372b2009-08-20 22:52:58 +0000649 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
650 .getAs<Decl>();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000651 if (!Member) {
652 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattner682bf922009-03-29 16:50:03 +0000653 return DeclPtrTy();
Chris Lattner6f8ce142009-03-05 23:03:49 +0000654 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000655
656 // Non-instance-fields can't have a bitfield.
657 if (BitWidth) {
658 if (Member->isInvalidDecl()) {
659 // don't emit another diagnostic.
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +0000660 } else if (isa<VarDecl>(Member)) {
Chris Lattner8b963ef2009-03-05 23:01:03 +0000661 // C++ 9.6p3: A bit-field shall not be a static member.
662 // "static member 'A' cannot be a bit-field"
663 Diag(Loc, diag::err_static_not_bitfield)
664 << Name << BitWidth->getSourceRange();
665 } else if (isa<TypedefDecl>(Member)) {
666 // "typedef member 'x' cannot be a bit-field"
667 Diag(Loc, diag::err_typedef_not_bitfield)
668 << Name << BitWidth->getSourceRange();
669 } else {
670 // A function typedef ("typedef int f(); f a;").
671 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
672 Diag(Loc, diag::err_not_integral_type_bitfield)
Douglas Gregor3cf538d2009-03-11 18:59:21 +0000673 << Name << cast<ValueDecl>(Member)->getType()
674 << BitWidth->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000675 }
676
677 DeleteExpr(BitWidth);
678 BitWidth = 0;
679 Member->setInvalidDecl();
680 }
Douglas Gregor4dd55f52009-03-11 20:50:30 +0000681
682 Member->setAccess(AS);
Douglas Gregor37b372b2009-08-20 22:52:58 +0000683
684 // If we have declared a member function template, set the access of the
685 // templated declaration as well.
686 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
687 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner24793662009-03-05 22:45:59 +0000688 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000689
Douglas Gregor10bd3682008-11-17 22:58:34 +0000690 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000691
Douglas Gregor021c3b32009-03-11 23:00:04 +0000692 if (Init)
Chris Lattnerb28317a2009-03-28 19:18:32 +0000693 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redle2b68332009-04-12 17:16:29 +0000694 if (Deleted) // FIXME: Source location is not very good.
695 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000696
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000697 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000698 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattner682bf922009-03-29 16:50:03 +0000699 return DeclPtrTy();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000700 }
Chris Lattnerb28317a2009-03-28 19:18:32 +0000701 return DeclPtrTy::make(Member);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000702}
703
Douglas Gregor7ad83902008-11-05 04:29:56 +0000704/// ActOnMemInitializer - Handle a C++ member initializer.
705Sema::MemInitResult
Chris Lattnerb28317a2009-03-28 19:18:32 +0000706Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000707 Scope *S,
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000708 const CXXScopeSpec &SS,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000709 IdentifierInfo *MemberOrBase,
Fariborz Jahanian96174332009-07-01 19:21:19 +0000710 TypeTy *TemplateTypeTy,
Douglas Gregor7ad83902008-11-05 04:29:56 +0000711 SourceLocation IdLoc,
712 SourceLocation LParenLoc,
713 ExprTy **Args, unsigned NumArgs,
714 SourceLocation *CommaLocs,
715 SourceLocation RParenLoc) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000716 if (!ConstructorD)
717 return true;
718
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000719 AdjustDeclIfTemplate(ConstructorD);
720
Douglas Gregor7ad83902008-11-05 04:29:56 +0000721 CXXConstructorDecl *Constructor
Chris Lattnerb28317a2009-03-28 19:18:32 +0000722 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregor7ad83902008-11-05 04:29:56 +0000723 if (!Constructor) {
724 // The user wrote a constructor initializer on a function that is
725 // not a C++ constructor. Ignore the error for now, because we may
726 // have more member initializers coming; we'll diagnose it just
727 // once in ActOnMemInitializers.
728 return true;
729 }
730
731 CXXRecordDecl *ClassDecl = Constructor->getParent();
732
733 // C++ [class.base.init]p2:
734 // Names in a mem-initializer-id are looked up in the scope of the
735 // constructor’s class and, if not found in that scope, are looked
736 // up in the scope containing the constructor’s
737 // definition. [Note: if the constructor’s class contains a member
738 // with the same name as a direct or virtual base class of the
739 // class, a mem-initializer-id naming the member or base class and
740 // composed of a single identifier refers to the class member. A
741 // mem-initializer-id for the hidden base class may be specified
742 // using a qualified name. ]
Fariborz Jahanian96174332009-07-01 19:21:19 +0000743 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000744 // Look for a member, first.
745 FieldDecl *Member = 0;
746 DeclContext::lookup_result Result
747 = ClassDecl->lookup(MemberOrBase);
748 if (Result.first != Result.second)
749 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000750
Fariborz Jahanianbcfad542009-06-30 23:26:25 +0000751 // FIXME: Handle members of an anonymous union.
Douglas Gregor7ad83902008-11-05 04:29:56 +0000752
Eli Friedman59c04372009-07-29 19:44:27 +0000753 if (Member)
754 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
755 RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000756 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000757 // It didn't name a member, so see if it names a class.
Fariborz Jahanian96174332009-07-01 19:21:19 +0000758 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
759 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000760 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000761 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
762 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000763
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000764 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000765
Eli Friedman59c04372009-07-29 19:44:27 +0000766 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
767 RParenLoc, ClassDecl);
768}
769
770Sema::MemInitResult
771Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
772 unsigned NumArgs, SourceLocation IdLoc,
773 SourceLocation RParenLoc) {
774 bool HasDependentArg = false;
775 for (unsigned i = 0; i < NumArgs; i++)
776 HasDependentArg |= Args[i]->isTypeDependent();
777
778 CXXConstructorDecl *C = 0;
779 QualType FieldType = Member->getType();
780 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
781 FieldType = Array->getElementType();
782 if (FieldType->isDependentType()) {
783 // Can't check init for dependent type.
Ted Kremenek6217b802009-07-29 21:53:49 +0000784 } else if (FieldType->getAs<RecordType>()) {
Eli Friedman59c04372009-07-29 19:44:27 +0000785 if (!HasDependentArg)
786 C = PerformInitializationByConstructor(
787 FieldType, (Expr **)Args, NumArgs, IdLoc,
788 SourceRange(IdLoc, RParenLoc), Member->getDeclName(), IK_Direct);
789 } else if (NumArgs != 1) {
790 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
791 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
792 } else if (!HasDependentArg) {
793 Expr *NewExp = (Expr*)Args[0];
794 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
795 return true;
796 Args[0] = NewExp;
Douglas Gregor7ad83902008-11-05 04:29:56 +0000797 }
Eli Friedman59c04372009-07-29 19:44:27 +0000798 // FIXME: Perform direct initialization of the member.
799 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +0000800 NumArgs, C, IdLoc, RParenLoc);
Eli Friedman59c04372009-07-29 19:44:27 +0000801}
802
803Sema::MemInitResult
804Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
805 unsigned NumArgs, SourceLocation IdLoc,
806 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
807 bool HasDependentArg = false;
808 for (unsigned i = 0; i < NumArgs; i++)
809 HasDependentArg |= Args[i]->isTypeDependent();
810
811 if (!BaseType->isDependentType()) {
812 if (!BaseType->isRecordType())
813 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
814 << BaseType << SourceRange(IdLoc, RParenLoc);
815
816 // C++ [class.base.init]p2:
817 // [...] Unless the mem-initializer-id names a nonstatic data
818 // member of the constructor’s class or a direct or virtual base
819 // of that class, the mem-initializer is ill-formed. A
820 // mem-initializer-list can initialize a base class using any
821 // name that denotes that base class type.
822
823 // First, check for a direct base class.
824 const CXXBaseSpecifier *DirectBaseSpec = 0;
825 for (CXXRecordDecl::base_class_const_iterator Base =
826 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
827 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
828 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
829 // We found a direct base of this type. That's what we're
830 // initializing.
831 DirectBaseSpec = &*Base;
832 break;
833 }
834 }
835
836 // Check for a virtual base class.
837 // FIXME: We might be able to short-circuit this if we know in advance that
838 // there are no virtual bases.
839 const CXXBaseSpecifier *VirtualBaseSpec = 0;
840 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
841 // We haven't found a base yet; search the class hierarchy for a
842 // virtual base class.
843 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
844 /*DetectVirtual=*/false);
845 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
846 for (BasePaths::paths_iterator Path = Paths.begin();
847 Path != Paths.end(); ++Path) {
848 if (Path->back().Base->isVirtual()) {
849 VirtualBaseSpec = Path->back().Base;
850 break;
851 }
Douglas Gregor7ad83902008-11-05 04:29:56 +0000852 }
853 }
854 }
Eli Friedman59c04372009-07-29 19:44:27 +0000855
856 // C++ [base.class.init]p2:
857 // If a mem-initializer-id is ambiguous because it designates both
858 // a direct non-virtual base class and an inherited virtual base
859 // class, the mem-initializer is ill-formed.
860 if (DirectBaseSpec && VirtualBaseSpec)
861 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
862 << BaseType << SourceRange(IdLoc, RParenLoc);
863 // C++ [base.class.init]p2:
864 // Unless the mem-initializer-id names a nonstatic data membeer of the
865 // constructor's class ot a direst or virtual base of that class, the
866 // mem-initializer is ill-formed.
867 if (!DirectBaseSpec && !VirtualBaseSpec)
868 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
869 << BaseType << ClassDecl->getNameAsCString()
870 << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000871 }
872
Fariborz Jahaniand7b27e12009-07-23 00:42:24 +0000873 CXXConstructorDecl *C = 0;
Eli Friedman59c04372009-07-29 19:44:27 +0000874 if (!BaseType->isDependentType() && !HasDependentArg) {
875 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
876 Context.getCanonicalType(BaseType));
877 C = PerformInitializationByConstructor(BaseType, (Expr **)Args, NumArgs,
878 IdLoc, SourceRange(IdLoc, RParenLoc),
879 Name, IK_Direct);
880 }
881
882 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Anders Carlsson8c57a662009-08-29 01:31:33 +0000883 NumArgs, C, IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000884}
885
Fariborz Jahanian87595e42009-07-23 23:32:59 +0000886void
887Sema::BuildBaseOrMemberInitializers(ASTContext &C,
888 CXXConstructorDecl *Constructor,
889 CXXBaseOrMemberInitializer **Initializers,
890 unsigned NumInitializers
891 ) {
892 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases;
893 llvm::SmallVector<FieldDecl *, 4>Members;
894
895 Constructor->setBaseOrMemberInitializers(C,
896 Initializers, NumInitializers,
897 Bases, Members);
898 for (unsigned int i = 0; i < Bases.size(); i++)
899 Diag(Bases[i]->getSourceRange().getBegin(),
900 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
901 for (unsigned int i = 0; i < Members.size(); i++)
902 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
903 << 1 << Members[i]->getType();
904}
905
Eli Friedman6347f422009-07-21 19:28:10 +0000906static void *GetKeyForTopLevelField(FieldDecl *Field) {
907 // For anonymous unions, use the class declaration as the key.
Ted Kremenek6217b802009-07-29 21:53:49 +0000908 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman6347f422009-07-21 19:28:10 +0000909 if (RT->getDecl()->isAnonymousStructOrUnion())
910 return static_cast<void *>(RT->getDecl());
911 }
912 return static_cast<void *>(Field);
913}
914
Fariborz Jahaniane6494122009-08-11 18:49:54 +0000915static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
916 bool MemberMaybeAnon=false) {
Eli Friedman6347f422009-07-21 19:28:10 +0000917 // For fields injected into the class via declaration of an anonymous union,
918 // use its anonymous union class declaration as the unique key.
919 if (FieldDecl *Field = Member->getMember()) {
Fariborz Jahaniane6494122009-08-11 18:49:54 +0000920 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
921 // data member of the class. Data member used in the initializer list is
922 // in AnonUnionMember field.
923 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
924 Field = Member->getAnonUnionMember();
Eli Friedman6347f422009-07-21 19:28:10 +0000925 if (Field->getDeclContext()->isRecord()) {
926 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
927 if (RD->isAnonymousStructOrUnion())
928 return static_cast<void *>(RD);
929 }
930 return static_cast<void *>(Field);
931 }
932 return static_cast<RecordType *>(Member->getBaseClass());
933}
934
Chris Lattnerb28317a2009-03-28 19:18:32 +0000935void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssona7b35212009-03-25 02:58:17 +0000936 SourceLocation ColonLoc,
937 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000938 if (!ConstructorDecl)
939 return;
Douglas Gregorefd5bda2009-08-24 11:57:43 +0000940
941 AdjustDeclIfTemplate(ConstructorDecl);
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +0000942
943 CXXConstructorDecl *Constructor
944 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Anders Carlssona7b35212009-03-25 02:58:17 +0000945
946 if (!Constructor) {
947 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
948 return;
949 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +0000950
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +0000951 if (!Constructor->isDependentContext()) {
952 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
953 bool err = false;
954 for (unsigned i = 0; i < NumMemInits; i++) {
955 CXXBaseOrMemberInitializer *Member =
956 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
957 void *KeyToMember = GetKeyForMember(Member);
958 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
959 if (!PrevMember) {
960 PrevMember = Member;
961 continue;
962 }
963 if (FieldDecl *Field = Member->getMember())
964 Diag(Member->getSourceLocation(),
965 diag::error_multiple_mem_initialization)
966 << Field->getNameAsString();
967 else {
968 Type *BaseClass = Member->getBaseClass();
969 assert(BaseClass && "ActOnMemInitializers - neither field or base");
970 Diag(Member->getSourceLocation(),
971 diag::error_multiple_base_initialization)
972 << BaseClass->getDesugaredType(true);
973 }
974 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
975 << 0;
976 err = true;
977 }
978
979 if (err)
980 return;
981 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +0000982
983 BuildBaseOrMemberInitializers(Context, Constructor,
Fariborz Jahanian87595e42009-07-23 23:32:59 +0000984 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
985 NumMemInits);
986
Anders Carlsson8d4c5ea2009-08-27 05:57:30 +0000987 if (Constructor->isDependentContext())
988 return;
989
Anders Carlsson5c36fb22009-08-27 05:45:01 +0000990 if (Diags.getDiagnosticLevel(diag::warn_base_initialized) ==
991 Diagnostic::Ignored &&
992 Diags.getDiagnosticLevel(diag::warn_field_initialized) ==
993 Diagnostic::Ignored)
994 return;
995
996 // Also issue warning if order of ctor-initializer list does not match order
997 // of 1) base class declarations and 2) order of non-static data members.
998 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
999
1000 CXXRecordDecl *ClassDecl
1001 = cast<CXXRecordDecl>(Constructor->getDeclContext());
1002 // Push virtual bases before others.
1003 for (CXXRecordDecl::base_class_iterator VBase =
1004 ClassDecl->vbases_begin(),
1005 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
1006 AllBaseOrMembers.push_back(VBase->getType()->getAs<RecordType>());
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001007
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001008 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
1009 E = ClassDecl->bases_end(); Base != E; ++Base) {
1010 // Virtuals are alread in the virtual base list and are constructed
1011 // first.
1012 if (Base->isVirtual())
1013 continue;
1014 AllBaseOrMembers.push_back(Base->getType()->getAs<RecordType>());
1015 }
1016
1017 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1018 E = ClassDecl->field_end(); Field != E; ++Field)
1019 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
1020
1021 int Last = AllBaseOrMembers.size();
1022 int curIndex = 0;
1023 CXXBaseOrMemberInitializer *PrevMember = 0;
1024 for (unsigned i = 0; i < NumMemInits; i++) {
1025 CXXBaseOrMemberInitializer *Member =
1026 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
1027 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman6347f422009-07-21 19:28:10 +00001028
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001029 for (; curIndex < Last; curIndex++)
1030 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1031 break;
1032 if (curIndex == Last) {
1033 assert(PrevMember && "Member not in member list?!");
1034 // Initializer as specified in ctor-initializer list is out of order.
1035 // Issue a warning diagnostic.
1036 if (PrevMember->isBaseInitializer()) {
1037 // Diagnostics is for an initialized base class.
1038 Type *BaseClass = PrevMember->getBaseClass();
1039 Diag(PrevMember->getSourceLocation(),
1040 diag::warn_base_initialized)
1041 << BaseClass->getDesugaredType(true);
1042 } else {
1043 FieldDecl *Field = PrevMember->getMember();
1044 Diag(PrevMember->getSourceLocation(),
1045 diag::warn_field_initialized)
1046 << Field->getNameAsString();
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001047 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001048 // Also the note!
1049 if (FieldDecl *Field = Member->getMember())
1050 Diag(Member->getSourceLocation(),
1051 diag::note_fieldorbase_initialized_here) << 0
1052 << Field->getNameAsString();
1053 else {
1054 Type *BaseClass = Member->getBaseClass();
1055 Diag(Member->getSourceLocation(),
1056 diag::note_fieldorbase_initialized_here) << 1
1057 << BaseClass->getDesugaredType(true);
1058 }
1059 for (curIndex = 0; curIndex < Last; curIndex++)
1060 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1061 break;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001062 }
Anders Carlsson5c36fb22009-08-27 05:45:01 +00001063 PrevMember = Member;
Fariborz Jahanianeb96e122009-07-09 19:59:47 +00001064 }
Anders Carlssona7b35212009-03-25 02:58:17 +00001065}
1066
Fariborz Jahanian393612e2009-07-21 22:36:06 +00001067void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian560de452009-07-15 22:34:08 +00001068 if (!CDtorDecl)
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001069 return;
1070
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001071 AdjustDeclIfTemplate(CDtorDecl);
1072
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001073 if (CXXConstructorDecl *Constructor
Fariborz Jahanian560de452009-07-15 22:34:08 +00001074 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian87595e42009-07-23 23:32:59 +00001075 BuildBaseOrMemberInitializers(Context,
1076 Constructor,
1077 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahaniand01c9152009-07-14 18:24:21 +00001078}
1079
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001080namespace {
1081 /// PureVirtualMethodCollector - traverses a class and its superclasses
1082 /// and determines if it has any pure virtual methods.
1083 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1084 ASTContext &Context;
1085
Sebastian Redldfe292d2009-03-22 21:28:55 +00001086 public:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001087 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redldfe292d2009-03-22 21:28:55 +00001088
1089 private:
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001090 MethodList Methods;
1091
1092 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
1093
1094 public:
1095 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
1096 : Context(Ctx) {
1097
1098 MethodList List;
1099 Collect(RD, List);
1100
1101 // Copy the temporary list to methods, and make sure to ignore any
1102 // null entries.
1103 for (size_t i = 0, e = List.size(); i != e; ++i) {
1104 if (List[i])
1105 Methods.push_back(List[i]);
1106 }
1107 }
1108
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001109 bool empty() const { return Methods.empty(); }
1110
1111 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1112 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001113 };
1114
1115 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
1116 MethodList& Methods) {
1117 // First, collect the pure virtual methods for the base classes.
1118 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1119 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001120 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner64540d72009-03-29 05:01:10 +00001121 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001122 if (BaseDecl && BaseDecl->isAbstract())
1123 Collect(BaseDecl, Methods);
1124 }
1125 }
1126
1127 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001128 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
1129
1130 MethodSetTy OverriddenMethods;
1131 size_t MethodsSize = Methods.size();
1132
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001133 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001134 i != e; ++i) {
1135 // Traverse the record, looking for methods.
1136 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl23c7d062009-07-07 20:29:57 +00001137 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001138 if (MD->isPure()) {
1139 Methods.push_back(MD);
1140 continue;
1141 }
1142
1143 // Otherwise, record all the overridden methods in our set.
1144 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1145 E = MD->end_overridden_methods(); I != E; ++I) {
1146 // Keep track of the overridden methods.
1147 OverriddenMethods.insert(*I);
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001148 }
1149 }
1150 }
1151
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001152 // Now go through the methods and zero out all the ones we know are
1153 // overridden.
1154 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1155 if (OverriddenMethods.count(Methods[i]))
1156 Methods[i] = 0;
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001157 }
Anders Carlsson8ff8c222009-05-17 00:00:05 +00001158
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001159 }
1160}
Douglas Gregor7ad83902008-11-05 04:29:56 +00001161
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001162
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001163bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001164 unsigned DiagID, AbstractDiagSelID SelID,
1165 const CXXRecordDecl *CurrentRD) {
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001166 if (SelID == -1)
1167 return RequireNonAbstractType(Loc, T,
1168 PDiag(DiagID), CurrentRD);
1169 else
1170 return RequireNonAbstractType(Loc, T,
1171 PDiag(DiagID) << SelID, CurrentRD);
1172}
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001173
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001174bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1175 const PartialDiagnostic &PD,
1176 const CXXRecordDecl *CurrentRD) {
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001177 if (!getLangOptions().CPlusPlus)
1178 return false;
Anders Carlsson11f21a02009-03-23 19:10:31 +00001179
1180 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001181 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001182 CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001183
Ted Kremenek6217b802009-07-29 21:53:49 +00001184 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001185 // Find the innermost pointer type.
Ted Kremenek6217b802009-07-29 21:53:49 +00001186 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001187 PT = T;
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001188
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001189 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001190 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlsson5eff73c2009-03-24 01:46:45 +00001191 }
1192
Ted Kremenek6217b802009-07-29 21:53:49 +00001193 const RecordType *RT = T->getAs<RecordType>();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001194 if (!RT)
1195 return false;
1196
1197 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1198 if (!RD)
1199 return false;
1200
Anders Carlssone65a3c82009-03-24 17:23:42 +00001201 if (CurrentRD && CurrentRD != RD)
1202 return false;
1203
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001204 if (!RD->isAbstract())
1205 return false;
1206
Anders Carlssona6ec7ad2009-08-27 00:13:57 +00001207 Diag(Loc, PD) << RD->getDeclName();
Anders Carlsson4681ebd2009-03-22 20:18:17 +00001208
1209 // Check if we've already emitted the list of pure virtual functions for this
1210 // class.
1211 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1212 return true;
1213
1214 PureVirtualMethodCollector Collector(Context, RD);
1215
1216 for (PureVirtualMethodCollector::MethodList::const_iterator I =
1217 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1218 const CXXMethodDecl *MD = *I;
1219
1220 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
1221 MD->getDeclName();
1222 }
1223
1224 if (!PureVirtualClassDiagSet)
1225 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1226 PureVirtualClassDiagSet->insert(RD);
1227
1228 return true;
1229}
1230
Anders Carlsson8211eff2009-03-24 01:19:16 +00001231namespace {
1232 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
1233 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1234 Sema &SemaRef;
1235 CXXRecordDecl *AbstractClass;
1236
Anders Carlssone65a3c82009-03-24 17:23:42 +00001237 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001238 bool Invalid = false;
1239
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001240 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1241 E = DC->decls_end(); I != E; ++I)
Anders Carlsson8211eff2009-03-24 01:19:16 +00001242 Invalid |= Visit(*I);
Anders Carlssone65a3c82009-03-24 17:23:42 +00001243
Anders Carlsson8211eff2009-03-24 01:19:16 +00001244 return Invalid;
1245 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00001246
1247 public:
1248 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1249 : SemaRef(SemaRef), AbstractClass(ac) {
1250 Visit(SemaRef.Context.getTranslationUnitDecl());
1251 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001252
Anders Carlssone65a3c82009-03-24 17:23:42 +00001253 bool VisitFunctionDecl(const FunctionDecl *FD) {
1254 if (FD->isThisDeclarationADefinition()) {
1255 // No need to do the check if we're in a definition, because it requires
1256 // that the return/param types are complete.
1257 // because that requires
1258 return VisitDeclContext(FD);
1259 }
1260
1261 // Check the return type.
1262 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
1263 bool Invalid =
1264 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1265 diag::err_abstract_type_in_decl,
1266 Sema::AbstractReturnType,
1267 AbstractClass);
1268
1269 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
1270 E = FD->param_end(); I != E; ++I) {
Anders Carlsson8211eff2009-03-24 01:19:16 +00001271 const ParmVarDecl *VD = *I;
1272 Invalid |=
1273 SemaRef.RequireNonAbstractType(VD->getLocation(),
1274 VD->getOriginalType(),
1275 diag::err_abstract_type_in_decl,
Anders Carlssone65a3c82009-03-24 17:23:42 +00001276 Sema::AbstractParamType,
1277 AbstractClass);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001278 }
1279
1280 return Invalid;
1281 }
Anders Carlssone65a3c82009-03-24 17:23:42 +00001282
1283 bool VisitDecl(const Decl* D) {
1284 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1285 return VisitDeclContext(DC);
1286
1287 return false;
1288 }
Anders Carlsson8211eff2009-03-24 01:19:16 +00001289 };
1290}
1291
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001292void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001293 DeclPtrTy TagDecl,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001294 SourceLocation LBrac,
1295 SourceLocation RBrac) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001296 if (!TagDecl)
1297 return;
1298
Douglas Gregor42af25f2009-05-11 19:58:34 +00001299 AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001300 ActOnFields(S, RLoc, TagDecl,
Chris Lattnerb28317a2009-03-28 19:18:32 +00001301 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00001302 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +00001303
Chris Lattnerb28317a2009-03-28 19:18:32 +00001304 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001305 if (!RD->isAbstract()) {
1306 // Collect all the pure virtual methods and see if this is an abstract
1307 // class after all.
1308 PureVirtualMethodCollector Collector(Context, RD);
1309 if (!Collector.empty())
1310 RD->setAbstract(true);
1311 }
1312
Anders Carlssone65a3c82009-03-24 17:23:42 +00001313 if (RD->isAbstract())
1314 AbstractClassUsageDiagnoser(*this, RD);
Anders Carlsson8211eff2009-03-24 01:19:16 +00001315
Douglas Gregor42af25f2009-05-11 19:58:34 +00001316 if (!RD->isDependentType())
Anders Carlsson67e4dd22009-03-22 01:52:17 +00001317 AddImplicitlyDeclaredMembersToClass(RD);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001318}
1319
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001320/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1321/// special functions, such as the default constructor, copy
1322/// constructor, or destructor, to the given C++ class (C++
1323/// [special]p1). This routine can only be executed just before the
1324/// definition of the class is complete.
1325void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor50d62d12009-08-05 05:36:45 +00001326 CanQualType ClassType
1327 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001328
Sebastian Redl465226e2009-05-27 22:11:52 +00001329 // FIXME: Implicit declarations have exception specifications, which are
1330 // the union of the specifications of the implicitly called functions.
1331
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001332 if (!ClassDecl->hasUserDeclaredConstructor()) {
1333 // C++ [class.ctor]p5:
1334 // A default constructor for a class X is a constructor of class X
1335 // that can be called without an argument. If there is no
1336 // user-declared constructor for class X, a default constructor is
1337 // implicitly declared. An implicitly-declared default constructor
1338 // is an inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001339 DeclarationName Name
1340 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001341 CXXConstructorDecl *DefaultCon =
1342 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001343 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001344 Context.getFunctionType(Context.VoidTy,
1345 0, 0, false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001346 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001347 /*isExplicit=*/false,
1348 /*isInline=*/true,
1349 /*isImplicitlyDeclared=*/true);
1350 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001351 DefaultCon->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001352 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001353 ClassDecl->addDecl(DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001354 }
1355
1356 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1357 // C++ [class.copy]p4:
1358 // If the class definition does not explicitly declare a copy
1359 // constructor, one is declared implicitly.
1360
1361 // C++ [class.copy]p5:
1362 // The implicitly-declared copy constructor for a class X will
1363 // have the form
1364 //
1365 // X::X(const X&)
1366 //
1367 // if
1368 bool HasConstCopyConstructor = true;
1369
1370 // -- each direct or virtual base class B of X has a copy
1371 // constructor whose first parameter is of type const B& or
1372 // const volatile B&, and
1373 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1374 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1375 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001376 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001377 HasConstCopyConstructor
1378 = BaseClassDecl->hasConstCopyConstructor(Context);
1379 }
1380
1381 // -- for all the nonstatic data members of X that are of a
1382 // class type M (or array thereof), each such class type
1383 // has a copy constructor whose first parameter is of type
1384 // const M& or const volatile M&.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001385 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1386 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001387 ++Field) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001388 QualType FieldType = (*Field)->getType();
1389 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1390 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001391 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001392 const CXXRecordDecl *FieldClassDecl
1393 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1394 HasConstCopyConstructor
1395 = FieldClassDecl->hasConstCopyConstructor(Context);
1396 }
1397 }
1398
Sebastian Redl64b45f72009-01-05 20:52:13 +00001399 // Otherwise, the implicitly declared copy constructor will have
1400 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001401 //
1402 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +00001403 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001404 if (HasConstCopyConstructor)
1405 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001406 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001407
Sebastian Redl64b45f72009-01-05 20:52:13 +00001408 // An implicitly-declared copy constructor is an inline public
1409 // member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001410 DeclarationName Name
1411 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001412 CXXConstructorDecl *CopyConstructor
1413 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001414 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001415 Context.getFunctionType(Context.VoidTy,
1416 &ArgType, 1,
1417 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001418 /*DInfo=*/0,
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001419 /*isExplicit=*/false,
1420 /*isInline=*/true,
1421 /*isImplicitlyDeclared=*/true);
1422 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001423 CopyConstructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001424 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001425
1426 // Add the parameter to the constructor.
1427 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1428 ClassDecl->getLocation(),
1429 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001430 ArgType, /*DInfo=*/0,
1431 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001432 CopyConstructor->setParams(Context, &FromParam, 1);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001433 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001434 }
1435
Sebastian Redl64b45f72009-01-05 20:52:13 +00001436 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1437 // Note: The following rules are largely analoguous to the copy
1438 // constructor rules. Note that virtual bases are not taken into account
1439 // for determining the argument type of the operator. Note also that
1440 // operators taking an object instead of a reference are allowed.
1441 //
1442 // C++ [class.copy]p10:
1443 // If the class definition does not explicitly declare a copy
1444 // assignment operator, one is declared implicitly.
1445 // The implicitly-defined copy assignment operator for a class X
1446 // will have the form
1447 //
1448 // X& X::operator=(const X&)
1449 //
1450 // if
1451 bool HasConstCopyAssignment = true;
1452
1453 // -- each direct base class B of X has a copy assignment operator
1454 // whose parameter is of type const B&, const volatile B& or B,
1455 // and
1456 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1457 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1458 const CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00001459 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001460 const CXXMethodDecl *MD = 0;
1461 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
1462 MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001463 }
1464
1465 // -- for all the nonstatic data members of X that are of a class
1466 // type M (or array thereof), each such class type has a copy
1467 // assignment operator whose parameter is of type const M&,
1468 // const volatile M& or M.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001469 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1470 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001471 ++Field) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001472 QualType FieldType = (*Field)->getType();
1473 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1474 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001475 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl64b45f72009-01-05 20:52:13 +00001476 const CXXRecordDecl *FieldClassDecl
1477 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001478 const CXXMethodDecl *MD = 0;
Sebastian Redl64b45f72009-01-05 20:52:13 +00001479 HasConstCopyAssignment
Fariborz Jahanian0270b8a2009-08-12 23:34:46 +00001480 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001481 }
1482 }
1483
1484 // Otherwise, the implicitly declared copy assignment operator will
1485 // have the form
1486 //
1487 // X& X::operator=(X&)
1488 QualType ArgType = ClassType;
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001489 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001490 if (HasConstCopyAssignment)
1491 ArgType = ArgType.withConst();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001492 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001493
1494 // An implicitly-declared copy assignment operator is an inline public
1495 // member of its class.
1496 DeclarationName Name =
1497 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1498 CXXMethodDecl *CopyAssignment =
1499 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1500 Context.getFunctionType(RetType, &ArgType, 1,
1501 false, 0),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001502 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001503 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001504 CopyAssignment->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001505 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian2198ba12009-08-12 21:14:35 +00001506 CopyAssignment->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001507
1508 // Add the parameter to the operator.
1509 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1510 ClassDecl->getLocation(),
1511 /*IdentifierInfo=*/0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00001512 ArgType, /*DInfo=*/0,
1513 VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +00001514 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001515
1516 // Don't call addedAssignmentOperator. There is no way to distinguish an
1517 // implicit from an explicit assignment operator.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001518 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001519 }
1520
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001521 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001522 // C++ [class.dtor]p2:
1523 // If a class has no user-declared destructor, a destructor is
1524 // declared implicitly. An implicitly-declared destructor is an
1525 // inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001526 DeclarationName Name
1527 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001528 CXXDestructorDecl *Destructor
1529 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +00001530 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +00001531 Context.getFunctionType(Context.VoidTy,
1532 0, 0, false, 0),
1533 /*isInline=*/true,
1534 /*isImplicitlyDeclared=*/true);
1535 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001536 Destructor->setImplicit();
Douglas Gregor1f2023a2009-07-22 18:25:24 +00001537 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001538 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001539 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001540}
1541
Douglas Gregor6569d682009-05-27 23:11:45 +00001542void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1543 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1544 if (!Template)
1545 return;
1546
1547 TemplateParameterList *Params = Template->getTemplateParameters();
1548 for (TemplateParameterList::iterator Param = Params->begin(),
1549 ParamEnd = Params->end();
1550 Param != ParamEnd; ++Param) {
1551 NamedDecl *Named = cast<NamedDecl>(*Param);
1552 if (Named->getDeclName()) {
1553 S->AddDecl(DeclPtrTy::make(Named));
1554 IdResolver.AddDecl(Named);
1555 }
1556 }
1557}
1558
Douglas Gregor72b505b2008-12-16 21:30:33 +00001559/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1560/// parsing a top-level (non-nested) C++ class, and we are now
1561/// parsing those parts of the given Method declaration that could
1562/// not be parsed earlier (C++ [class.mem]p2), such as default
1563/// arguments. This action should enter the scope of the given
1564/// Method declaration as if we had just parsed the qualified method
1565/// name. However, it should not bring the parameters into scope;
1566/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001567void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001568 if (!MethodD)
1569 return;
1570
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001571 AdjustDeclIfTemplate(MethodD);
1572
Douglas Gregor72b505b2008-12-16 21:30:33 +00001573 CXXScopeSpec SS;
Chris Lattnerb28317a2009-03-28 19:18:32 +00001574 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregorab452ba2009-03-26 23:50:42 +00001575 QualType ClassTy
1576 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1577 SS.setScopeRep(
1578 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001579 ActOnCXXEnterDeclaratorScope(S, SS);
1580}
1581
1582/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1583/// C++ method declaration. We're (re-)introducing the given
1584/// function parameter into scope for use in parsing later parts of
1585/// the method declaration. For example, we could see an
1586/// ActOnParamDefaultArgument event for this parameter.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001587void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001588 if (!ParamD)
1589 return;
1590
Chris Lattnerb28317a2009-03-28 19:18:32 +00001591 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor61366e92008-12-24 00:01:03 +00001592
1593 // If this parameter has an unparsed default argument, clear it out
1594 // to make way for the parsed default argument.
1595 if (Param->hasUnparsedDefaultArg())
1596 Param->setDefaultArg(0);
1597
Chris Lattnerb28317a2009-03-28 19:18:32 +00001598 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001599 if (Param->getDeclName())
1600 IdResolver.AddDecl(Param);
1601}
1602
1603/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1604/// processing the delayed method declaration for Method. The method
1605/// declaration is now considered finished. There may be a separate
1606/// ActOnStartOfFunctionDef action later (not necessarily
1607/// immediately!) for this method, if it was also defined inside the
1608/// class body.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001609void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor4c4f7cb2009-06-22 23:20:33 +00001610 if (!MethodD)
1611 return;
1612
Douglas Gregorefd5bda2009-08-24 11:57:43 +00001613 AdjustDeclIfTemplate(MethodD);
1614
Chris Lattnerb28317a2009-03-28 19:18:32 +00001615 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor72b505b2008-12-16 21:30:33 +00001616 CXXScopeSpec SS;
Douglas Gregorab452ba2009-03-26 23:50:42 +00001617 QualType ClassTy
1618 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1619 SS.setScopeRep(
1620 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor72b505b2008-12-16 21:30:33 +00001621 ActOnCXXExitDeclaratorScope(S, SS);
1622
1623 // Now that we have our default arguments, check the constructor
1624 // again. It could produce additional diagnostics or affect whether
1625 // the class has implicitly-declared destructors, among other
1626 // things.
Chris Lattner6e475012009-04-25 08:35:12 +00001627 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1628 CheckConstructor(Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00001629
1630 // Check the default arguments, which we may have added.
1631 if (!Method->isInvalidDecl())
1632 CheckCXXDefaultArguments(Method);
1633}
1634
Douglas Gregor42a552f2008-11-05 20:51:48 +00001635/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00001636/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00001637/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00001638/// emit diagnostics and set the invalid bit to true. In any case, the type
1639/// will be updated to reflect a well-formed type for the constructor and
1640/// returned.
1641QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1642 FunctionDecl::StorageClass &SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001643 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001644
1645 // C++ [class.ctor]p3:
1646 // A constructor shall not be virtual (10.3) or static (9.4). A
1647 // constructor can be invoked for a const, volatile or const
1648 // volatile object. A constructor shall not be declared const,
1649 // volatile, or const volatile (9.3.2).
1650 if (isVirtual) {
Chris Lattner65401802009-04-25 08:28:21 +00001651 if (!D.isInvalidType())
1652 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1653 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1654 << SourceRange(D.getIdentifierLoc());
1655 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001656 }
1657 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00001658 if (!D.isInvalidType())
1659 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1660 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1661 << SourceRange(D.getIdentifierLoc());
1662 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001663 SC = FunctionDecl::None;
1664 }
Chris Lattner65401802009-04-25 08:28:21 +00001665
1666 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1667 if (FTI.TypeQuals != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001668 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001669 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1670 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001671 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001672 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1673 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001674 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001675 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1676 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001677 }
1678
1679 // Rebuild the function type "R" without any type qualifiers (in
1680 // case any of the errors above fired) and with "void" as the
1681 // return type, since constructors don't have return types. We
1682 // *always* have to do this, because GetTypeForDeclarator will
1683 // put in a result type of "int" when none was specified.
Douglas Gregor72564e72009-02-26 23:50:07 +00001684 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattner65401802009-04-25 08:28:21 +00001685 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1686 Proto->getNumArgs(),
1687 Proto->isVariadic(), 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001688}
1689
Douglas Gregor72b505b2008-12-16 21:30:33 +00001690/// CheckConstructor - Checks a fully-formed constructor for
1691/// well-formedness, issuing any diagnostics required. Returns true if
1692/// the constructor declarator is invalid.
Chris Lattner6e475012009-04-25 08:35:12 +00001693void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Douglas Gregor33297562009-03-27 04:38:56 +00001694 CXXRecordDecl *ClassDecl
1695 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1696 if (!ClassDecl)
Chris Lattner6e475012009-04-25 08:35:12 +00001697 return Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00001698
1699 // C++ [class.copy]p3:
1700 // A declaration of a constructor for a class X is ill-formed if
1701 // its first parameter is of type (optionally cv-qualified) X and
1702 // either there are no other parameters or else all other
1703 // parameters have default arguments.
Douglas Gregor33297562009-03-27 04:38:56 +00001704 if (!Constructor->isInvalidDecl() &&
1705 ((Constructor->getNumParams() == 1) ||
1706 (Constructor->getNumParams() > 1 &&
Anders Carlssonae0b4e72009-06-06 04:14:07 +00001707 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00001708 QualType ParamType = Constructor->getParamDecl(0)->getType();
1709 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1710 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregora3a83512009-04-01 23:51:29 +00001711 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
1712 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor558cb562009-04-02 01:08:08 +00001713 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner6e475012009-04-25 08:35:12 +00001714 Constructor->setInvalidDecl();
Douglas Gregor72b505b2008-12-16 21:30:33 +00001715 }
1716 }
1717
1718 // Notify the class that we've added a constructor.
1719 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor72b505b2008-12-16 21:30:33 +00001720}
1721
Anders Carlsson7786d1c2009-04-30 23:18:11 +00001722static inline bool
1723FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
1724 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1725 FTI.ArgInfo[0].Param &&
1726 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
1727}
1728
Douglas Gregor42a552f2008-11-05 20:51:48 +00001729/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1730/// the well-formednes of the destructor declarator @p D with type @p
1731/// R. If there are any errors in the declarator, this routine will
Chris Lattner65401802009-04-25 08:28:21 +00001732/// emit diagnostics and set the declarator to invalid. Even if this happens,
1733/// will be updated to reflect a well-formed type for the destructor and
1734/// returned.
1735QualType Sema::CheckDestructorDeclarator(Declarator &D,
1736 FunctionDecl::StorageClass& SC) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001737 // C++ [class.dtor]p1:
1738 // [...] A typedef-name that names a class is a class-name
1739 // (7.1.3); however, a typedef-name that names a class shall not
1740 // be used as the identifier in the declarator for a destructor
1741 // declaration.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001742 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattner65401802009-04-25 08:28:21 +00001743 if (isa<TypedefType>(DeclaratorType)) {
1744 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001745 << DeclaratorType;
Chris Lattner65401802009-04-25 08:28:21 +00001746 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001747 }
1748
1749 // C++ [class.dtor]p2:
1750 // A destructor is used to destroy objects of its class type. A
1751 // destructor takes no parameters, and no return type can be
1752 // specified for it (not even void). The address of a destructor
1753 // shall not be taken. A destructor shall not be static. A
1754 // destructor can be invoked for a const, volatile or const
1755 // volatile object. A destructor shall not be declared const,
1756 // volatile or const volatile (9.3.2).
1757 if (SC == FunctionDecl::Static) {
Chris Lattner65401802009-04-25 08:28:21 +00001758 if (!D.isInvalidType())
1759 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1760 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1761 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001762 SC = FunctionDecl::None;
Chris Lattner65401802009-04-25 08:28:21 +00001763 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001764 }
Chris Lattner65401802009-04-25 08:28:21 +00001765 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001766 // Destructors don't have return types, but the parser will
1767 // happily parse something like:
1768 //
1769 // class X {
1770 // float ~X();
1771 // };
1772 //
1773 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001774 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1775 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1776 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001777 }
Chris Lattner65401802009-04-25 08:28:21 +00001778
1779 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1780 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001781 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001782 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1783 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001784 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001785 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1786 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001787 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001788 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1789 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattner65401802009-04-25 08:28:21 +00001790 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001791 }
1792
1793 // Make sure we don't have any parameters.
Anders Carlsson7786d1c2009-04-30 23:18:11 +00001794 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001795 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1796
1797 // Delete the parameters.
Chris Lattner65401802009-04-25 08:28:21 +00001798 FTI.freeArgs();
1799 D.setInvalidType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001800 }
1801
1802 // Make sure the destructor isn't variadic.
Chris Lattner65401802009-04-25 08:28:21 +00001803 if (FTI.isVariadic) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001804 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattner65401802009-04-25 08:28:21 +00001805 D.setInvalidType();
1806 }
Douglas Gregor42a552f2008-11-05 20:51:48 +00001807
1808 // Rebuild the function type "R" without any type qualifiers or
1809 // parameters (in case any of the errors above fired) and with
1810 // "void" as the return type, since destructors don't have return
1811 // types. We *always* have to do this, because GetTypeForDeclarator
1812 // will put in a result type of "int" when none was specified.
Chris Lattner65401802009-04-25 08:28:21 +00001813 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001814}
1815
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001816/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1817/// well-formednes of the conversion function declarator @p D with
1818/// type @p R. If there are any errors in the declarator, this routine
1819/// will emit diagnostics and return true. Otherwise, it will return
1820/// false. Either way, the type @p R will be updated to reflect a
1821/// well-formed type for the conversion operator.
Chris Lattner6e475012009-04-25 08:35:12 +00001822void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001823 FunctionDecl::StorageClass& SC) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001824 // C++ [class.conv.fct]p1:
1825 // Neither parameter types nor return type can be specified. The
Eli Friedman33a31382009-08-05 19:21:58 +00001826 // type of a conversion function (8.3.5) is "function taking no
1827 // parameter returning conversion-type-id."
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001828 if (SC == FunctionDecl::Static) {
Chris Lattner6e475012009-04-25 08:35:12 +00001829 if (!D.isInvalidType())
1830 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1831 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1832 << SourceRange(D.getIdentifierLoc());
1833 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001834 SC = FunctionDecl::None;
1835 }
Chris Lattner6e475012009-04-25 08:35:12 +00001836 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001837 // Conversion functions don't have return types, but the parser will
1838 // happily parse something like:
1839 //
1840 // class X {
1841 // float operator bool();
1842 // };
1843 //
1844 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001845 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1846 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1847 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001848 }
1849
1850 // Make sure we don't have any parameters.
Douglas Gregor72564e72009-02-26 23:50:07 +00001851 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001852 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1853
1854 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00001855 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner6e475012009-04-25 08:35:12 +00001856 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001857 }
1858
1859 // Make sure the conversion function isn't variadic.
Chris Lattner6e475012009-04-25 08:35:12 +00001860 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001861 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner6e475012009-04-25 08:35:12 +00001862 D.setInvalidType();
1863 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001864
1865 // C++ [class.conv.fct]p4:
1866 // The conversion-type-id shall not represent a function type nor
1867 // an array type.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001868 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001869 if (ConvType->isArrayType()) {
1870 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1871 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00001872 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001873 } else if (ConvType->isFunctionType()) {
1874 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1875 ConvType = Context.getPointerType(ConvType);
Chris Lattner6e475012009-04-25 08:35:12 +00001876 D.setInvalidType();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001877 }
1878
1879 // Rebuild the function type "R" without any parameters (in case any
1880 // of the errors above fired) and with the conversion type as the
1881 // return type.
1882 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor72564e72009-02-26 23:50:07 +00001883 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001884
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001885 // C++0x explicit conversion operators.
1886 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1887 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1888 diag::warn_explicit_conversion_functions)
1889 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001890}
1891
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001892/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1893/// the declaration of the given C++ conversion function. This routine
1894/// is responsible for recording the conversion function in the C++
1895/// class, if possible.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001896Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001897 assert(Conversion && "Expected to receive a conversion function declaration");
1898
Douglas Gregor9d350972008-12-12 08:25:50 +00001899 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001900
1901 // Make sure we aren't redeclaring the conversion function.
1902 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001903
1904 // C++ [class.conv.fct]p1:
1905 // [...] A conversion function is never used to convert a
1906 // (possibly cv-qualified) object to the (possibly cv-qualified)
1907 // same object type (or a reference to it), to a (possibly
1908 // cv-qualified) base class of that type (or a reference to it),
1909 // or to (possibly cv-qualified) void.
Mike Stump390b4cc2009-05-16 07:39:55 +00001910 // FIXME: Suppress this warning if the conversion function ends up being a
1911 // virtual function that overrides a virtual function in a base class.
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001912 QualType ClassType
1913 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenek6217b802009-07-29 21:53:49 +00001914 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001915 ConvType = ConvTypeRef->getPointeeType();
1916 if (ConvType->isRecordType()) {
1917 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1918 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00001919 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001920 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001921 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00001922 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001923 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001924 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00001925 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001926 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001927 }
1928
Douglas Gregor70316a02008-12-26 15:00:45 +00001929 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001930 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
1931 if (FunctionTemplateDecl *ConversionTemplate
1932 = Conversion->getDescribedFunctionTemplate())
1933 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor70316a02008-12-26 15:00:45 +00001934 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1935 for (OverloadedFunctionDecl::function_iterator
1936 Conv = Conversions->function_begin(),
1937 ConvEnd = Conversions->function_end();
1938 Conv != ConvEnd; ++Conv) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001939 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor70316a02008-12-26 15:00:45 +00001940 *Conv = Conversion;
Chris Lattnerb28317a2009-03-28 19:18:32 +00001941 return DeclPtrTy::make(Conversion);
Douglas Gregor70316a02008-12-26 15:00:45 +00001942 }
1943 }
1944 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001945 } else if (FunctionTemplateDecl *ConversionTemplate
1946 = Conversion->getDescribedFunctionTemplate())
1947 ClassDecl->addConversionFunction(Context, ConversionTemplate);
1948 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Douglas Gregor70316a02008-12-26 15:00:45 +00001949 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001950
Chris Lattnerb28317a2009-03-28 19:18:32 +00001951 return DeclPtrTy::make(Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001952}
1953
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001954//===----------------------------------------------------------------------===//
1955// Namespace Handling
1956//===----------------------------------------------------------------------===//
1957
1958/// ActOnStartNamespaceDef - This is called at the start of a namespace
1959/// definition.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001960Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1961 SourceLocation IdentLoc,
1962 IdentifierInfo *II,
1963 SourceLocation LBrace) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001964 NamespaceDecl *Namespc =
1965 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1966 Namespc->setLBracLoc(LBrace);
1967
1968 Scope *DeclRegionScope = NamespcScope->getParent();
1969
1970 if (II) {
1971 // C++ [namespace.def]p2:
1972 // The identifier in an original-namespace-definition shall not have been
1973 // previously defined in the declarative region in which the
1974 // original-namespace-definition appears. The identifier in an
1975 // original-namespace-definition is the name of the namespace. Subsequently
1976 // in that declarative region, it is treated as an original-namespace-name.
1977
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001978 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1979 true);
Douglas Gregor44b43212008-12-11 16:49:14 +00001980
1981 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1982 // This is an extended namespace definition.
1983 // Attach this namespace decl to the chain of extended namespace
1984 // definitions.
1985 OrigNS->setNextNamespace(Namespc);
1986 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001987
Douglas Gregor44b43212008-12-11 16:49:14 +00001988 // Remove the previous declaration from the scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00001989 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001990 IdResolver.RemoveDecl(OrigNS);
Chris Lattnerb28317a2009-03-28 19:18:32 +00001991 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001992 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001993 } else if (PrevDecl) {
1994 // This is an invalid name redefinition.
1995 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1996 << Namespc->getDeclName();
1997 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1998 Namespc->setInvalidDecl();
1999 // Continue on to push Namespc as current DeclContext and return it.
2000 }
2001
2002 PushOnScopeChains(Namespc, DeclRegionScope);
2003 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002004 // FIXME: Handle anonymous namespaces
2005 }
2006
2007 // Although we could have an invalid decl (i.e. the namespace name is a
2008 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stump390b4cc2009-05-16 07:39:55 +00002009 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2010 // for the namespace has the declarations that showed up in that particular
2011 // namespace definition.
Douglas Gregor44b43212008-12-11 16:49:14 +00002012 PushDeclContext(NamespcScope, Namespc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002013 return DeclPtrTy::make(Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002014}
2015
2016/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2017/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002018void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2019 Decl *Dcl = D.getAs<Decl>();
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002020 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2021 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2022 Namespc->setRBracLoc(RBrace);
2023 PopDeclContext();
2024}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002025
Chris Lattnerb28317a2009-03-28 19:18:32 +00002026Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2027 SourceLocation UsingLoc,
2028 SourceLocation NamespcLoc,
2029 const CXXScopeSpec &SS,
2030 SourceLocation IdentLoc,
2031 IdentifierInfo *NamespcName,
2032 AttributeList *AttrList) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002033 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2034 assert(NamespcName && "Invalid NamespcName.");
2035 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002036 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00002037
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002038 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00002039
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002040 // Lookup namespace name.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002041 LookupResult R = LookupParsedName(S, &SS, NamespcName,
2042 LookupNamespaceName, false);
2043 if (R.isAmbiguous()) {
2044 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002045 return DeclPtrTy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002046 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002047 if (NamedDecl *NS = R) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00002048 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002049 // C++ [namespace.udir]p1:
2050 // A using-directive specifies that the names in the nominated
2051 // namespace can be used in the scope in which the
2052 // using-directive appears after the using-directive. During
2053 // unqualified name lookup (3.4.1), the names appear as if they
2054 // were declared in the nearest enclosing namespace which
2055 // contains both the using-directive and the nominated
Eli Friedman33a31382009-08-05 19:21:58 +00002056 // namespace. [Note: in this context, "contains" means "contains
2057 // directly or indirectly". ]
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002058
2059 // Find enclosing context containing both using-directive and
2060 // nominated namespace.
2061 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2062 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2063 CommonAncestor = CommonAncestor->getParent();
2064
Douglas Gregor8419fa32009-05-30 06:31:56 +00002065 UDir = UsingDirectiveDecl::Create(Context,
2066 CurContext, UsingLoc,
2067 NamespcLoc,
2068 SS.getRange(),
2069 (NestedNameSpecifier *)SS.getScopeRep(),
2070 IdentLoc,
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002071 cast<NamespaceDecl>(NS),
2072 CommonAncestor);
2073 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00002074 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00002075 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00002076 }
2077
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002078 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00002079 delete AttrList;
Chris Lattnerb28317a2009-03-28 19:18:32 +00002080 return DeclPtrTy::make(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002081}
2082
2083void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2084 // If scope has associated entity, then using directive is at namespace
2085 // or translation unit scope. We add UsingDirectiveDecls, into
2086 // it's lookup structure.
2087 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002088 Ctx->addDecl(UDir);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00002089 else
2090 // Otherwise it is block-sope. using-directives will affect lookup
2091 // only to the end of scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002092 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregorf780abc2008-12-30 03:27:21 +00002093}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002094
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002095
2096Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002097 SourceLocation UsingLoc,
2098 const CXXScopeSpec &SS,
2099 SourceLocation IdentLoc,
2100 IdentifierInfo *TargetName,
2101 OverloadedOperatorKind Op,
2102 AttributeList *AttrList,
2103 bool IsTypeName) {
Eli Friedman5d39dee2009-06-27 05:59:59 +00002104 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002105 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Anders Carlssonc72160b2009-08-28 05:40:36 +00002106
Anders Carlsson0c6139d2009-06-27 00:27:47 +00002107 DeclarationName Name;
2108 if (TargetName)
2109 Name = TargetName;
2110 else
2111 Name = Context.DeclarationNames.getCXXOperatorName(Op);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002112
2113 NamedDecl *UD = BuildUsingDeclaration(UsingLoc, SS, IdentLoc,
2114 Name, AttrList, IsTypeName);
2115 if (UD)
2116 PushOnScopeChains(UD, S);
2117
2118 return DeclPtrTy::make(UD);
2119}
2120
2121NamedDecl *Sema::BuildUsingDeclaration(SourceLocation UsingLoc,
2122 const CXXScopeSpec &SS,
2123 SourceLocation IdentLoc,
2124 DeclarationName Name,
2125 AttributeList *AttrList,
2126 bool IsTypeName) {
2127 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2128 assert(IdentLoc.isValid() && "Invalid TargetName location.");
Eli Friedman2a16a132009-08-27 05:09:36 +00002129
Anders Carlsson550b14b2009-08-28 05:49:21 +00002130 // FIXME: We ignore attributes for now.
2131 delete AttrList;
2132
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002133 if (SS.isEmpty()) {
2134 Diag(IdentLoc, diag::err_using_requires_qualname);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002135 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002136 }
2137
2138 NestedNameSpecifier *NNS =
2139 static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2140
Anders Carlsson550b14b2009-08-28 05:49:21 +00002141 if (isUnknownSpecialization(SS)) {
2142 return UnresolvedUsingDecl::Create(Context, CurContext, UsingLoc,
2143 SS.getRange(), NNS,
2144 IdentLoc, Name, IsTypeName);
2145 }
2146
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002147 DeclContext *LookupContext = 0;
2148
2149 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
2150 // C++0x N2914 [namespace.udecl]p3:
2151 // A using-declaration used as a member-declaration shall refer to a member
2152 // of a base class of the class being defined, shall refer to a member of an
2153 // anonymous union that is a member of a base class of the class being
2154 // defined, or shall refer to an enumerator for an enumeration type that is
2155 // a member of a base class of the class being defined.
2156 const Type *Ty = NNS->getAsType();
2157 if (!Ty || !IsDerivedFrom(Context.getTagDeclType(RD), QualType(Ty, 0))) {
2158 Diag(SS.getRange().getBegin(),
2159 diag::err_using_decl_nested_name_specifier_is_not_a_base_class)
2160 << NNS << RD->getDeclName();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002161 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002162 }
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002163
2164 QualType BaseTy = Context.getCanonicalType(QualType(Ty, 0));
2165 LookupContext = BaseTy->getAs<RecordType>()->getDecl();
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002166 } else {
2167 // C++0x N2914 [namespace.udecl]p8:
2168 // A using-declaration for a class member shall be a member-declaration.
2169 if (NNS->getKind() == NestedNameSpecifier::TypeSpec) {
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002170 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_class_member)
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002171 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002172 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002173 }
2174
2175 // C++0x N2914 [namespace.udecl]p9:
2176 // In a using-declaration, a prefix :: refers to the global namespace.
2177 if (NNS->getKind() == NestedNameSpecifier::Global)
2178 LookupContext = Context.getTranslationUnitDecl();
2179 else
2180 LookupContext = NNS->getAsNamespace();
2181 }
2182
2183
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002184 // Lookup target name.
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002185 LookupResult R = LookupQualifiedName(LookupContext,
2186 Name, LookupOrdinaryName);
2187
2188 if (!R) {
2189 Diag(IdentLoc, diag::err_typecheck_no_member) << Name << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002190 return 0;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002191 }
2192
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002193 NamedDecl *ND = R.getAsDecl();
2194
2195 if (IsTypeName && !isa<TypeDecl>(ND)) {
2196 Diag(IdentLoc, diag::err_using_typename_non_type);
Anders Carlssonc72160b2009-08-28 05:40:36 +00002197 return 0;
Anders Carlssoncf9f9212009-08-28 03:16:11 +00002198 }
2199
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002200 // C++0x N2914 [namespace.udecl]p6:
2201 // A using-declaration shall not name a namespace.
2202 if (isa<NamespaceDecl>(ND)) {
2203 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
2204 << SS.getRange();
Anders Carlssonc72160b2009-08-28 05:40:36 +00002205 return 0;
Anders Carlsson73b39cf2009-08-28 03:35:18 +00002206 }
2207
Anders Carlssonc72160b2009-08-28 05:40:36 +00002208 return UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2209 ND->getLocation(), UsingLoc, ND, NNS, IsTypeName);
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002210}
2211
Anders Carlsson81c85c42009-03-28 23:53:49 +00002212/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2213/// is a namespace alias, returns the namespace it points to.
2214static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2215 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2216 return AD->getNamespace();
2217 return dyn_cast_or_null<NamespaceDecl>(D);
2218}
2219
Chris Lattnerb28317a2009-03-28 19:18:32 +00002220Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002221 SourceLocation NamespaceLoc,
Chris Lattnerb28317a2009-03-28 19:18:32 +00002222 SourceLocation AliasLoc,
2223 IdentifierInfo *Alias,
2224 const CXXScopeSpec &SS,
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002225 SourceLocation IdentLoc,
2226 IdentifierInfo *Ident) {
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002227
Anders Carlsson81c85c42009-03-28 23:53:49 +00002228 // Lookup the namespace name.
2229 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2230
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002231 // Check if we have a previous declaration with the same name.
Anders Carlssondd729fc2009-03-28 23:49:35 +00002232 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson81c85c42009-03-28 23:53:49 +00002233 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
2234 // We already have an alias with the same name that points to the same
2235 // namespace, so don't create a new one.
2236 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2237 return DeclPtrTy();
2238 }
2239
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002240 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2241 diag::err_redefinition_different_kind;
2242 Diag(AliasLoc, DiagID) << Alias;
2243 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002244 return DeclPtrTy();
Anders Carlsson8d7ba402009-03-28 06:23:46 +00002245 }
2246
Anders Carlsson5721c682009-03-28 06:42:02 +00002247 if (R.isAmbiguous()) {
Anders Carlsson03bd5a12009-03-28 22:53:22 +00002248 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattnerb28317a2009-03-28 19:18:32 +00002249 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002250 }
2251
2252 if (!R) {
2253 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00002254 return DeclPtrTy();
Anders Carlsson5721c682009-03-28 06:42:02 +00002255 }
2256
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002257 NamespaceAliasDecl *AliasDecl =
Douglas Gregor6c9c9402009-05-30 06:48:27 +00002258 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2259 Alias, SS.getRange(),
2260 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlsson68771c72009-03-28 22:58:02 +00002261 IdentLoc, R);
2262
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002263 CurContext->addDecl(AliasDecl);
Anders Carlsson68771c72009-03-28 22:58:02 +00002264 return DeclPtrTy::make(AliasDecl);
Anders Carlssondbb00942009-03-28 05:27:17 +00002265}
2266
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002267void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2268 CXXConstructorDecl *Constructor) {
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00002269 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2270 !Constructor->isUsed()) &&
2271 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002272
2273 CXXRecordDecl *ClassDecl
2274 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002275 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002276 // Before the implicitly-declared default constructor for a class is
2277 // implicitly defined, all the implicitly-declared default constructors
2278 // for its base class and its non-static data members shall have been
2279 // implicitly defined.
2280 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002281 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2282 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002283 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002284 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002285 if (!BaseClassDecl->hasTrivialConstructor()) {
2286 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002287 BaseClassDecl->getDefaultConstructor(Context))
2288 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002289 else {
2290 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002291 << Context.getTagDeclType(ClassDecl) << 1
2292 << Context.getTagDeclType(BaseClassDecl);
2293 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
2294 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002295 err = true;
2296 }
2297 }
2298 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002299 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2300 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002301 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2302 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2303 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002304 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002305 CXXRecordDecl *FieldClassDecl
2306 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands6887e632009-06-25 09:03:06 +00002307 if (!FieldClassDecl->hasTrivialConstructor()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002308 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002309 FieldClassDecl->getDefaultConstructor(Context))
2310 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002311 else {
2312 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian3da83eb2009-06-20 20:23:38 +00002313 << Context.getTagDeclType(ClassDecl) << 0 <<
2314 Context.getTagDeclType(FieldClassDecl);
2315 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
2316 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002317 err = true;
2318 }
2319 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002320 } else if (FieldType->isReferenceType()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002321 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002322 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002323 Diag((*Field)->getLocation(), diag::note_declared_at);
2324 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002325 } else if (FieldType.isConstQualified()) {
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002326 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson5eda8162009-07-09 17:37:12 +00002327 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002328 Diag((*Field)->getLocation(), diag::note_declared_at);
2329 err = true;
2330 }
2331 }
2332 if (!err)
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002333 Constructor->setUsed();
2334 else
2335 Constructor->setInvalidDecl();
Fariborz Jahanianf8dcb862009-06-19 19:55:27 +00002336}
2337
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002338void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
2339 CXXDestructorDecl *Destructor) {
2340 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2341 "DefineImplicitDestructor - call it for implicit default dtor");
2342
2343 CXXRecordDecl *ClassDecl
2344 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2345 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2346 // C++ [class.dtor] p5
2347 // Before the implicitly-declared default destructor for a class is
2348 // implicitly defined, all the implicitly-declared default destructors
2349 // for its base class and its non-static data members shall have been
2350 // implicitly defined.
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002351 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2352 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002353 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002354 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002355 if (!BaseClassDecl->hasTrivialDestructor()) {
2356 if (CXXDestructorDecl *BaseDtor =
2357 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2358 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2359 else
2360 assert(false &&
2361 "DefineImplicitDestructor - missing dtor in a base class");
2362 }
2363 }
2364
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002365 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2366 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002367 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2368 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2369 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002370 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002371 CXXRecordDecl *FieldClassDecl
2372 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2373 if (!FieldClassDecl->hasTrivialDestructor()) {
2374 if (CXXDestructorDecl *FieldDtor =
2375 const_cast<CXXDestructorDecl*>(
2376 FieldClassDecl->getDestructor(Context)))
2377 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2378 else
2379 assert(false &&
2380 "DefineImplicitDestructor - missing dtor in class of a data member");
2381 }
2382 }
2383 }
2384 Destructor->setUsed();
2385}
2386
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002387void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2388 CXXMethodDecl *MethodDecl) {
2389 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2390 MethodDecl->getOverloadedOperator() == OO_Equal &&
2391 !MethodDecl->isUsed()) &&
2392 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
2393
2394 CXXRecordDecl *ClassDecl
2395 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002396
Fariborz Jahanianc6249b92009-06-26 16:08:57 +00002397 // C++[class.copy] p12
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002398 // Before the implicitly-declared copy assignment operator for a class is
2399 // implicitly defined, all implicitly-declared copy assignment operators
2400 // for its direct base classes and its nonstatic data members shall have
2401 // been implicitly defined.
2402 bool err = false;
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002403 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2404 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002405 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002406 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002407 if (CXXMethodDecl *BaseAssignOpMethod =
2408 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2409 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2410 }
Fariborz Jahanian514b7b12009-06-30 16:36:53 +00002411 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2412 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002413 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2414 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2415 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002416 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002417 CXXRecordDecl *FieldClassDecl
2418 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2419 if (CXXMethodDecl *FieldAssignOpMethod =
2420 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2421 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002422 } else if (FieldType->isReferenceType()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002423 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002424 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2425 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002426 Diag(CurrentLocation, diag::note_first_required_here);
2427 err = true;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002428 } else if (FieldType.isConstQualified()) {
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002429 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson5e09d4c2009-07-09 17:47:25 +00002430 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2431 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00002432 Diag(CurrentLocation, diag::note_first_required_here);
2433 err = true;
2434 }
2435 }
2436 if (!err)
2437 MethodDecl->setUsed();
2438}
2439
2440CXXMethodDecl *
2441Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2442 CXXRecordDecl *ClassDecl) {
2443 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2444 QualType RHSType(LHSType);
2445 // If class's assignment operator argument is const/volatile qualified,
2446 // look for operator = (const/volatile B&). Otherwise, look for
2447 // operator = (B&).
2448 if (ParmDecl->getType().isConstQualified())
2449 RHSType.addConst();
2450 if (ParmDecl->getType().isVolatileQualified())
2451 RHSType.addVolatile();
2452 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2453 LHSType,
2454 SourceLocation()));
2455 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2456 RHSType,
2457 SourceLocation()));
2458 Expr *Args[2] = { &*LHS, &*RHS };
2459 OverloadCandidateSet CandidateSet;
2460 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
2461 CandidateSet);
2462 OverloadCandidateSet::iterator Best;
2463 if (BestViableFunction(CandidateSet,
2464 ClassDecl->getLocation(), Best) == OR_Success)
2465 return cast<CXXMethodDecl>(Best->Function);
2466 assert(false &&
2467 "getAssignOperatorMethod - copy assignment operator method not found");
2468 return 0;
2469}
2470
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002471void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2472 CXXConstructorDecl *CopyConstructor,
2473 unsigned TypeQuals) {
2474 assert((CopyConstructor->isImplicit() &&
2475 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2476 !CopyConstructor->isUsed()) &&
2477 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
2478
2479 CXXRecordDecl *ClassDecl
2480 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2481 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002482 // C++ [class.copy] p209
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002483 // Before the implicitly-declared copy constructor for a class is
2484 // implicitly defined, all the implicitly-declared copy constructors
2485 // for its base class and its non-static data members shall have been
2486 // implicitly defined.
2487 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2488 Base != ClassDecl->bases_end(); ++Base) {
2489 CXXRecordDecl *BaseClassDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00002490 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002491 if (CXXConstructorDecl *BaseCopyCtor =
2492 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002493 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002494 }
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002495 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2496 FieldEnd = ClassDecl->field_end();
2497 Field != FieldEnd; ++Field) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002498 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2499 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2500 FieldType = Array->getElementType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002501 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002502 CXXRecordDecl *FieldClassDecl
2503 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2504 if (CXXConstructorDecl *FieldCopyCtor =
2505 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanian220a0f32009-06-23 23:42:10 +00002506 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian485f0872009-06-22 23:34:40 +00002507 }
2508 }
2509 CopyConstructor->setUsed();
2510}
2511
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002512Sema::OwningExprResult
2513Sema::BuildCXXConstructExpr(QualType DeclInitType,
2514 CXXConstructorDecl *Constructor,
2515 Expr **Exprs, unsigned NumExprs) {
Anders Carlsson9abf2ae2009-08-16 05:13:48 +00002516 bool Elidable = false;
2517
2518 // [class.copy]p15:
2519 // Whenever a temporary class object is copied using a copy constructor, and
2520 // this object and the copy have the same cv-unqualified type, an
2521 // implementation is permitted to treat the original and the copy as two
2522 // different ways of referring to the same object and not perform a copy at
2523 //all, even if the class copy constructor or destructor have side effects.
2524
2525 // FIXME: Is this enough?
2526 if (Constructor->isCopyConstructor(Context) && NumExprs == 1) {
2527 Expr *E = Exprs[0];
2528 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2529 E = BE->getSubExpr();
2530
2531 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2532 Elidable = true;
2533 }
2534
2535 return BuildCXXConstructExpr(DeclInitType, Constructor, Elidable,
2536 Exprs, NumExprs);
2537}
2538
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002539/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2540/// including handling of its default argument expressions.
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002541Sema::OwningExprResult
2542Sema::BuildCXXConstructExpr(QualType DeclInitType,
2543 CXXConstructorDecl *Constructor,
2544 bool Elidable,
2545 Expr **Exprs,
2546 unsigned NumExprs) {
Anders Carlsson8644aec2009-08-25 13:07:08 +00002547 ExprOwningPtr<CXXConstructExpr> Temp(this,
2548 CXXConstructExpr::Create(Context,
2549 DeclInitType,
2550 Constructor,
2551 Elidable,
2552 Exprs,
2553 NumExprs));
Anders Carlssone7624a72009-08-27 05:08:22 +00002554 // Default arguments must be added to constructor call expression.
Fariborz Jahanian2eeed7b2009-08-05 00:26:10 +00002555 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor);
2556 unsigned NumArgsInProto = FDecl->param_size();
2557 for (unsigned j = NumExprs; j != NumArgsInProto; j++) {
Anders Carlsson8644aec2009-08-25 13:07:08 +00002558 ParmVarDecl *Param = FDecl->getParamDecl(j);
2559
2560 OwningExprResult ArgExpr =
2561 BuildCXXDefaultArgExpr(/*FIXME:*/SourceLocation(),
2562 FDecl, Param);
2563 if (ArgExpr.isInvalid())
2564 return ExprError();
2565
2566 Temp->setArg(j, ArgExpr.takeAs<Expr>());
Fariborz Jahanian2eeed7b2009-08-05 00:26:10 +00002567 }
Anders Carlsson8644aec2009-08-25 13:07:08 +00002568 return move(Temp);
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002569}
2570
Anders Carlssone7624a72009-08-27 05:08:22 +00002571Sema::OwningExprResult
2572Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
2573 QualType Ty,
2574 SourceLocation TyBeginLoc,
2575 MultiExprArg Args,
2576 SourceLocation RParenLoc) {
2577 CXXTemporaryObjectExpr *E
2578 = new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty, TyBeginLoc,
2579 (Expr **)Args.get(),
2580 Args.size(), RParenLoc);
2581
2582 ExprOwningPtr<CXXTemporaryObjectExpr> Temp(this, E);
2583
2584 // Default arguments must be added to constructor call expression.
2585 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor);
2586 unsigned NumArgsInProto = FDecl->param_size();
2587 for (unsigned j = Args.size(); j != NumArgsInProto; j++) {
2588 ParmVarDecl *Param = FDecl->getParamDecl(j);
2589
2590 OwningExprResult ArgExpr = BuildCXXDefaultArgExpr(TyBeginLoc, FDecl, Param);
2591 if (ArgExpr.isInvalid())
2592 return ExprError();
2593
2594 Temp->setArg(j, ArgExpr.takeAs<Expr>());
2595 }
2596
2597 Args.release();
2598 return move(Temp);
2599}
2600
2601
Anders Carlssonfe2de492009-08-25 05:18:00 +00002602bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanianb2c352e2009-08-05 17:03:54 +00002603 CXXConstructorDecl *Constructor,
2604 QualType DeclInitType,
2605 Expr **Exprs, unsigned NumExprs) {
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002606 OwningExprResult TempResult = BuildCXXConstructExpr(DeclInitType, Constructor,
2607 Exprs, NumExprs);
Anders Carlssonfe2de492009-08-25 05:18:00 +00002608 if (TempResult.isInvalid())
2609 return true;
Anders Carlssonda3f4e22009-08-25 05:12:04 +00002610
2611 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002612 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahaniancaa499b2009-08-05 18:17:32 +00002613 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor78d15832009-05-26 18:54:04 +00002614 VD->setInit(Context, Temp);
Anders Carlssonfe2de492009-08-25 05:18:00 +00002615
2616 return false;
Anders Carlsson930e8d02009-04-16 23:50:50 +00002617}
2618
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002619void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType)
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002620{
2621 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenek6217b802009-07-29 21:53:49 +00002622 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002623 if (!ClassDecl->hasTrivialDestructor())
2624 if (CXXDestructorDecl *Destructor =
2625 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002626 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00002627}
2628
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002629/// AddCXXDirectInitializerToDecl - This action is called immediately after
2630/// ActOnDeclarator, when a C++ direct initializer is present.
2631/// e.g: "int x(1);"
Chris Lattnerb28317a2009-03-28 19:18:32 +00002632void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2633 SourceLocation LParenLoc,
Sebastian Redlf53597f2009-03-15 17:47:39 +00002634 MultiExprArg Exprs,
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002635 SourceLocation *CommaLocs,
2636 SourceLocation RParenLoc) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00002637 unsigned NumExprs = Exprs.size();
2638 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattnerb28317a2009-03-28 19:18:32 +00002639 Decl *RealDecl = Dcl.getAs<Decl>();
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002640
2641 // If there is no declaration, there was an error parsing it. Just ignore
2642 // the initializer.
Chris Lattnerb28317a2009-03-28 19:18:32 +00002643 if (RealDecl == 0)
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002644 return;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002645
2646 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2647 if (!VDecl) {
2648 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2649 RealDecl->setInvalidDecl();
2650 return;
2651 }
2652
Douglas Gregor83ddad32009-08-26 21:14:46 +00002653 // We will represent direct-initialization similarly to copy-initialization:
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00002654 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002655 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2656 //
2657 // Clients that want to distinguish between the two forms, can check for
2658 // direct initializer using VarDecl::hasCXXDirectInitializer().
2659 // A major benefit is that clients that don't particularly care about which
2660 // exactly form was it (like the CodeGen) can handle both cases without
2661 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002662
Douglas Gregor83ddad32009-08-26 21:14:46 +00002663 // If either the declaration has a dependent type or if any of the expressions
2664 // is type-dependent, we represent the initialization via a ParenListExpr for
2665 // later use during template instantiation.
2666 if (VDecl->getType()->isDependentType() ||
2667 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
2668 // Let clients know that initialization was done with a direct initializer.
2669 VDecl->setCXXDirectInitializer(true);
2670
2671 // Store the initialization expressions as a ParenListExpr.
2672 unsigned NumExprs = Exprs.size();
2673 VDecl->setInit(Context,
2674 new (Context) ParenListExpr(Context, LParenLoc,
2675 (Expr **)Exprs.release(),
2676 NumExprs, RParenLoc));
2677 return;
2678 }
2679
2680
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002681 // C++ 8.5p11:
2682 // The form of initialization (using parentheses or '=') is generally
2683 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002684 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00002685 QualType DeclInitType = VDecl->getType();
2686 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
2687 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002688
Douglas Gregor615c5d42009-03-24 16:43:20 +00002689 // FIXME: This isn't the right place to complete the type.
2690 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2691 diag::err_typecheck_decl_incomplete_type)) {
2692 VDecl->setInvalidDecl();
2693 return;
2694 }
2695
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002696 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00002697 CXXConstructorDecl *Constructor
Sebastian Redlf53597f2009-03-15 17:47:39 +00002698 = PerformInitializationByConstructor(DeclInitType,
2699 (Expr **)Exprs.get(), NumExprs,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002700 VDecl->getLocation(),
2701 SourceRange(VDecl->getLocation(),
2702 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002703 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002704 IK_Direct);
Sebastian Redlf53597f2009-03-15 17:47:39 +00002705 if (!Constructor)
Douglas Gregor18fe5682008-11-03 20:45:27 +00002706 RealDecl->setInvalidDecl();
Anders Carlssonca29ad92009-04-15 21:48:18 +00002707 else {
Anders Carlssonca29ad92009-04-15 21:48:18 +00002708 VDecl->setCXXDirectInitializer(true);
Anders Carlssonfe2de492009-08-25 05:18:00 +00002709 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
2710 (Expr**)Exprs.release(), NumExprs))
2711 RealDecl->setInvalidDecl();
Fariborz Jahaniana83f7ed2009-08-03 19:13:25 +00002712 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlssonca29ad92009-04-15 21:48:18 +00002713 }
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00002714 return;
2715 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002716
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00002717 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002718 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
2719 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002720 RealDecl->setInvalidDecl();
2721 return;
2722 }
2723
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002724 // Let clients know that initialization was done with a direct initializer.
2725 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00002726
2727 assert(NumExprs == 1 && "Expected 1 expression");
2728 // Set the init expression, handles conversions.
Sebastian Redlf53597f2009-03-15 17:47:39 +00002729 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
2730 /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00002731}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002732
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002733/// PerformInitializationByConstructor - Perform initialization by
2734/// constructor (C++ [dcl.init]p14), which may occur as part of
2735/// direct-initialization or copy-initialization. We are initializing
2736/// an object of type @p ClassType with the given arguments @p
2737/// Args. @p Loc is the location in the source code where the
2738/// initializer occurs (e.g., a declaration, member initializer,
2739/// functional cast, etc.) while @p Range covers the whole
2740/// initialization. @p InitEntity is the entity being initialized,
2741/// which may by the name of a declaration or a type. @p Kind is the
2742/// kind of initialization we're performing, which affects whether
2743/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00002744/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002745/// when the initialization fails, emits a diagnostic and returns
2746/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00002747CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002748Sema::PerformInitializationByConstructor(QualType ClassType,
2749 Expr **Args, unsigned NumArgs,
2750 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002751 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002752 InitializationKind Kind) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002753 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor18fe5682008-11-03 20:45:27 +00002754 assert(ClassRec && "Can only initialize a class type here");
2755
2756 // C++ [dcl.init]p14:
2757 //
2758 // If the initialization is direct-initialization, or if it is
2759 // copy-initialization where the cv-unqualified version of the
2760 // source type is the same class as, or a derived class of, the
2761 // class of the destination, constructors are considered. The
2762 // applicable constructors are enumerated (13.3.1.3), and the
2763 // best one is chosen through overload resolution (13.3). The
2764 // constructor so selected is called to initialize the object,
2765 // with the initializer expression(s) as its argument(s). If no
2766 // constructor applies, or the overload resolution is ambiguous,
2767 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00002768 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
2769 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002770
2771 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002772 DeclarationName ConstructorName
2773 = Context.DeclarationNames.getCXXConstructorName(
2774 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002775 DeclContext::lookup_const_iterator Con, ConEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002776 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002777 Con != ConEnd; ++Con) {
Douglas Gregordec06662009-08-21 18:42:58 +00002778 // Find the constructor (which may be a template).
2779 CXXConstructorDecl *Constructor = 0;
2780 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
2781 if (ConstructorTmpl)
2782 Constructor
2783 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2784 else
2785 Constructor = cast<CXXConstructorDecl>(*Con);
2786
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002787 if ((Kind == IK_Direct) ||
Anders Carlssonfaccd722009-08-28 16:57:08 +00002788 (Kind == IK_Copy &&
2789 Constructor->isConvertingConstructor(/*AllowExplicit=*/false)) ||
Douglas Gregordec06662009-08-21 18:42:58 +00002790 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
2791 if (ConstructorTmpl)
2792 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
2793 Args, NumArgs, CandidateSet);
2794 else
2795 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2796 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002797 }
2798
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002799 // FIXME: When we decide not to synthesize the implicitly-declared
2800 // constructors, we'll need to make them appear here.
2801
Douglas Gregor18fe5682008-11-03 20:45:27 +00002802 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00002803 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00002804 case OR_Success:
2805 // We found a constructor. Return it.
2806 return cast<CXXConstructorDecl>(Best->Function);
2807
2808 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00002809 if (InitEntity)
2810 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00002811 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00002812 else
2813 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00002814 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00002815 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002816 return 0;
2817
2818 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00002819 if (InitEntity)
2820 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
2821 else
2822 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00002823 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2824 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002825
2826 case OR_Deleted:
2827 if (InitEntity)
2828 Diag(Loc, diag::err_ovl_deleted_init)
2829 << Best->Function->isDeleted()
2830 << InitEntity << Range;
2831 else
2832 Diag(Loc, diag::err_ovl_deleted_init)
2833 << Best->Function->isDeleted()
2834 << InitEntity << Range;
2835 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2836 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00002837 }
2838
2839 return 0;
2840}
2841
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002842/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2843/// determine whether they are reference-related,
2844/// reference-compatible, reference-compatible with added
2845/// qualification, or incompatible, for use in C++ initialization by
2846/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2847/// type, and the first type (T1) is the pointee type of the reference
2848/// type being initialized.
2849Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00002850Sema::CompareReferenceRelationship(QualType T1, QualType T2,
2851 bool& DerivedToBase) {
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002852 assert(!T1->isReferenceType() &&
2853 "T1 must be the pointee type of the reference type");
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002854 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
2855
2856 T1 = Context.getCanonicalType(T1);
2857 T2 = Context.getCanonicalType(T2);
2858 QualType UnqualT1 = T1.getUnqualifiedType();
2859 QualType UnqualT2 = T2.getUnqualifiedType();
2860
2861 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00002862 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2863 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002864 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002865 if (UnqualT1 == UnqualT2)
2866 DerivedToBase = false;
2867 else if (IsDerivedFrom(UnqualT2, UnqualT1))
2868 DerivedToBase = true;
2869 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002870 return Ref_Incompatible;
2871
2872 // At this point, we know that T1 and T2 are reference-related (at
2873 // least).
2874
2875 // C++ [dcl.init.ref]p4:
Eli Friedman33a31382009-08-05 19:21:58 +00002876 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002877 // reference-related to T2 and cv1 is the same cv-qualification
2878 // as, or greater cv-qualification than, cv2. For purposes of
2879 // overload resolution, cases for which cv1 is greater
2880 // cv-qualification than cv2 are identified as
2881 // reference-compatible with added qualification (see 13.3.3.2).
2882 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2883 return Ref_Compatible;
2884 else if (T1.isMoreQualifiedThan(T2))
2885 return Ref_Compatible_With_Added_Qualification;
2886 else
2887 return Ref_Related;
2888}
2889
2890/// CheckReferenceInit - Check the initialization of a reference
2891/// variable with the given initializer (C++ [dcl.init.ref]). Init is
2892/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00002893/// list), and DeclType is the type of the declaration. When ICS is
2894/// non-null, this routine will compute the implicit conversion
2895/// sequence according to C++ [over.ics.ref] and will not produce any
2896/// diagnostics; when ICS is null, it will emit diagnostics when any
2897/// errors are found. Either way, a return value of true indicates
2898/// that there was a failure, a return value of false indicates that
2899/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00002900///
2901/// When @p SuppressUserConversions, user-defined conversions are
2902/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002903/// When @p AllowExplicit, we also permit explicit user-defined
2904/// conversion functions.
Sebastian Redle2b68332009-04-12 17:16:29 +00002905/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002906bool
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002907Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002908 bool SuppressUserConversions,
Anders Carlsson2de3ace2009-08-27 17:30:43 +00002909 bool AllowExplicit, bool ForceRValue,
2910 ImplicitConversionSequence *ICS) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002911 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2912
Ted Kremenek6217b802009-07-29 21:53:49 +00002913 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002914 QualType T2 = Init->getType();
2915
Douglas Gregor904eed32008-11-10 20:40:00 +00002916 // If the initializer is the address of an overloaded function, try
2917 // to resolve the overloaded function. If all goes well, T2 is the
2918 // type of the resulting function.
Douglas Gregor063daf62009-03-13 18:40:31 +00002919 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Douglas Gregor904eed32008-11-10 20:40:00 +00002920 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
2921 ICS != 0);
2922 if (Fn) {
2923 // Since we're performing this reference-initialization for
2924 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002925 if (!ICS) {
2926 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
2927 return true;
2928
Douglas Gregor904eed32008-11-10 20:40:00 +00002929 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002930 }
Douglas Gregor904eed32008-11-10 20:40:00 +00002931
2932 T2 = Fn->getType();
2933 }
2934 }
2935
Douglas Gregor15da57e2008-10-29 02:00:59 +00002936 // Compute some basic properties of the types and the initializer.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00002937 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor15da57e2008-10-29 02:00:59 +00002938 bool DerivedToBase = false;
Sebastian Redle2b68332009-04-12 17:16:29 +00002939 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2940 Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00002941 ReferenceCompareResult RefRelationship
2942 = CompareReferenceRelationship(T1, T2, DerivedToBase);
2943
2944 // Most paths end in a failed conversion.
2945 if (ICS)
2946 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002947
2948 // C++ [dcl.init.ref]p5:
Eli Friedman33a31382009-08-05 19:21:58 +00002949 // A reference to type "cv1 T1" is initialized by an expression
2950 // of type "cv2 T2" as follows:
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002951
2952 // -- If the initializer expression
2953
Sebastian Redla9845802009-03-29 15:27:50 +00002954 // Rvalue references cannot bind to lvalues (N2812).
2955 // There is absolutely no situation where they can. In particular, note that
2956 // this is ill-formed, even if B has a user-defined conversion to A&&:
2957 // B b;
2958 // A&& r = b;
2959 if (isRValRef && InitLvalue == Expr::LV_Valid) {
2960 if (!ICS)
2961 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
2962 << Init->getSourceRange();
2963 return true;
2964 }
2965
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002966 bool BindsDirectly = false;
Eli Friedman33a31382009-08-05 19:21:58 +00002967 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2968 // reference-compatible with "cv2 T2," or
Douglas Gregor15da57e2008-10-29 02:00:59 +00002969 //
2970 // Note that the bit-field check is skipped if we are just computing
2971 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002972 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00002973 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002974 BindsDirectly = true;
2975
Douglas Gregor15da57e2008-10-29 02:00:59 +00002976 if (ICS) {
2977 // C++ [over.ics.ref]p1:
2978 // When a parameter of reference type binds directly (8.5.3)
2979 // to an argument expression, the implicit conversion sequence
2980 // is the identity conversion, unless the argument expression
2981 // has a type that is a derived class of the parameter type,
2982 // in which case the implicit conversion sequence is a
2983 // derived-to-base Conversion (13.3.3.1).
2984 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2985 ICS->Standard.First = ICK_Identity;
2986 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2987 ICS->Standard.Third = ICK_Identity;
2988 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2989 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002990 ICS->Standard.ReferenceBinding = true;
2991 ICS->Standard.DirectBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00002992 ICS->Standard.RRefBinding = false;
Sebastian Redl76458502009-04-17 16:30:52 +00002993 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00002994
2995 // Nothing more to do: the inaccessibility/ambiguity check for
2996 // derived-to-base conversions is suppressed when we're
2997 // computing the implicit conversion sequence (C++
2998 // [over.best.ics]p2).
2999 return false;
3000 } else {
3001 // Perform the conversion.
Mike Stump390b4cc2009-05-16 07:39:55 +00003002 // FIXME: Binding to a subobject of the lvalue 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=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003005 }
3006 }
3007
3008 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedman33a31382009-08-05 19:21:58 +00003009 // implicitly converted to an lvalue of type "cv3 T3,"
3010 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003011 // 92) (this conversion is selected by enumerating the
3012 // applicable conversion functions (13.3.1.6) and choosing
3013 // the best one through overload resolution (13.3)),
Douglas Gregor5842ba92009-08-24 15:23:48 +00003014 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
3015 !RequireCompleteType(SourceLocation(), T2, 0)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003016 // FIXME: Look for conversions in base classes!
3017 CXXRecordDecl *T2RecordDecl
Ted Kremenek6217b802009-07-29 21:53:49 +00003018 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003019
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003020 OverloadCandidateSet CandidateSet;
3021 OverloadedFunctionDecl *Conversions
3022 = T2RecordDecl->getConversionFunctions();
3023 for (OverloadedFunctionDecl::function_iterator Func
3024 = Conversions->function_begin();
3025 Func != Conversions->function_end(); ++Func) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003026 FunctionTemplateDecl *ConvTemplate
3027 = dyn_cast<FunctionTemplateDecl>(*Func);
3028 CXXConversionDecl *Conv;
3029 if (ConvTemplate)
3030 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3031 else
3032 Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redldfe292d2009-03-22 21:28:55 +00003033
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003034 // If the conversion function doesn't return a reference type,
3035 // it can't be considered for this conversion.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003036 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003037 (AllowExplicit || !Conv->isExplicit())) {
3038 if (ConvTemplate)
3039 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
3040 CandidateSet);
3041 else
3042 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
3043 }
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003044 }
3045
3046 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00003047 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003048 case OR_Success:
3049 // This is a direct binding.
3050 BindsDirectly = true;
3051
3052 if (ICS) {
3053 // C++ [over.ics.ref]p1:
3054 //
3055 // [...] If the parameter binds directly to the result of
3056 // applying a conversion function to the argument
3057 // expression, the implicit conversion sequence is a
3058 // user-defined conversion sequence (13.3.3.1.2), with the
3059 // second standard conversion sequence either an identity
3060 // conversion or, if the conversion function returns an
3061 // entity of a type that is a derived class of the parameter
3062 // type, a derived-to-base Conversion.
3063 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
3064 ICS->UserDefined.Before = Best->Conversions[0].Standard;
3065 ICS->UserDefined.After = Best->FinalConversion;
3066 ICS->UserDefined.ConversionFunction = Best->Function;
3067 assert(ICS->UserDefined.After.ReferenceBinding &&
3068 ICS->UserDefined.After.DirectBinding &&
3069 "Expected a direct reference binding!");
3070 return false;
3071 } else {
3072 // Perform the conversion.
Mike Stump390b4cc2009-05-16 07:39:55 +00003073 // FIXME: Binding to a subobject of the lvalue is going to require more
3074 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00003075 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003076 }
3077 break;
3078
3079 case OR_Ambiguous:
3080 assert(false && "Ambiguous reference binding conversions not implemented.");
3081 return true;
3082
3083 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003084 case OR_Deleted:
3085 // There was no suitable conversion, or we found a deleted
3086 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00003087 break;
3088 }
3089 }
3090
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003091 if (BindsDirectly) {
3092 // C++ [dcl.init.ref]p4:
3093 // [...] In all cases where the reference-related or
3094 // reference-compatible relationship of two types is used to
3095 // establish the validity of a reference binding, and T1 is a
3096 // base class of T2, a program that necessitates such a binding
3097 // is ill-formed if T1 is an inaccessible (clause 11) or
3098 // ambiguous (10.2) base class of T2.
3099 //
3100 // Note that we only check this condition when we're allowed to
3101 // complain about errors, because we should not be checking for
3102 // ambiguity (or inaccessibility) unless the reference binding
3103 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003104 if (DerivedToBase)
3105 return CheckDerivedToBaseConversion(T2, T1,
3106 Init->getSourceRange().getBegin(),
3107 Init->getSourceRange());
3108 else
3109 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003110 }
3111
3112 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redla9845802009-03-29 15:27:50 +00003113 // type (i.e., cv1 shall be const), or the reference shall be an
3114 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00003115 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00003116 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003117 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003118 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00003119 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3120 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003121 return true;
3122 }
3123
3124 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedman33a31382009-08-05 19:21:58 +00003125 // class type, and "cv1 T1" is reference-compatible with
3126 // "cv2 T2," the reference is bound in one of the
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003127 // following ways (the choice is implementation-defined):
3128 //
3129 // -- The reference is bound to the object represented by
3130 // the rvalue (see 3.10) or to a sub-object within that
3131 // object.
3132 //
Eli Friedman33a31382009-08-05 19:21:58 +00003133 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003134 // a constructor is called to copy the entire rvalue
3135 // object into the temporary. The reference is bound to
3136 // the temporary or to a sub-object within the
3137 // temporary.
3138 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003139 // The constructor that would be used to make the copy
3140 // shall be callable whether or not the copy is actually
3141 // done.
3142 //
Sebastian Redla9845802009-03-29 15:27:50 +00003143 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003144 // freedom, so we will always take the first option and never build
3145 // a temporary in this case. FIXME: We will, however, have to check
3146 // for the presence of a copy constructor in C++98/03 mode.
3147 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00003148 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3149 if (ICS) {
3150 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3151 ICS->Standard.First = ICK_Identity;
3152 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3153 ICS->Standard.Third = ICK_Identity;
3154 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3155 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003156 ICS->Standard.ReferenceBinding = true;
Sebastian Redla9845802009-03-29 15:27:50 +00003157 ICS->Standard.DirectBinding = false;
3158 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redl76458502009-04-17 16:30:52 +00003159 ICS->Standard.CopyConstructor = 0;
Douglas Gregor15da57e2008-10-29 02:00:59 +00003160 } else {
Mike Stump390b4cc2009-05-16 07:39:55 +00003161 // FIXME: Binding to a subobject of the rvalue is going to require more
3162 // AST annotation than this.
Anders Carlsson3503d042009-07-31 01:23:52 +00003163 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/false);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003164 }
3165 return false;
3166 }
3167
Eli Friedman33a31382009-08-05 19:21:58 +00003168 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003169 // initialized from the initializer expression using the
3170 // rules for a non-reference copy initialization (8.5). The
3171 // reference is then bound to the temporary. If T1 is
3172 // reference-related to T2, cv1 must be the same
3173 // cv-qualification as, or greater cv-qualification than,
3174 // cv2; otherwise, the program is ill-formed.
3175 if (RefRelationship == Ref_Related) {
3176 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3177 // we would be reference-compatible or reference-compatible with
3178 // added qualification. But that wasn't the case, so the reference
3179 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003180 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003181 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003182 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00003183 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3184 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003185 return true;
3186 }
3187
Douglas Gregor734d9862009-01-30 23:27:23 +00003188 // If at least one of the types is a class type, the types are not
3189 // related, and we aren't allowed any user conversions, the
3190 // reference binding fails. This case is important for breaking
3191 // recursion, since TryImplicitConversion below will attempt to
3192 // create a temporary through the use of a copy constructor.
3193 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3194 (T1->isRecordType() || T2->isRecordType())) {
3195 if (!ICS)
3196 Diag(Init->getSourceRange().getBegin(),
3197 diag::err_typecheck_convert_incompatible)
3198 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3199 return true;
3200 }
3201
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003202 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003203 if (ICS) {
Sebastian Redla9845802009-03-29 15:27:50 +00003204 // C++ [over.ics.ref]p2:
3205 //
3206 // When a parameter of reference type is not bound directly to
3207 // an argument expression, the conversion sequence is the one
3208 // required to convert the argument expression to the
3209 // underlying type of the reference according to
3210 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3211 // to copy-initializing a temporary of the underlying type with
3212 // the argument expression. Any difference in top-level
3213 // cv-qualification is subsumed by the initialization itself
3214 // and does not constitute a conversion.
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003215 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions,
3216 /*AllowExplicit=*/false,
Anders Carlsson08972922009-08-28 15:33:32 +00003217 /*ForceRValue=*/false,
3218 /*InOverloadResolution=*/false);
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003219
Sebastian Redla9845802009-03-29 15:27:50 +00003220 // Of course, that's still a reference binding.
3221 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3222 ICS->Standard.ReferenceBinding = true;
3223 ICS->Standard.RRefBinding = isRValRef;
3224 } else if(ICS->ConversionKind ==
3225 ImplicitConversionSequence::UserDefinedConversion) {
3226 ICS->UserDefined.After.ReferenceBinding = true;
3227 ICS->UserDefined.After.RRefBinding = isRValRef;
3228 }
Douglas Gregor15da57e2008-10-29 02:00:59 +00003229 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3230 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00003231 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00003232 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003233}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003234
3235/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3236/// of this overloaded operator is well-formed. If so, returns false;
3237/// otherwise, emits appropriate diagnostics and returns true.
3238bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003239 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003240 "Expected an overloaded operator declaration");
3241
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003242 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3243
3244 // C++ [over.oper]p5:
3245 // The allocation and deallocation functions, operator new,
3246 // operator new[], operator delete and operator delete[], are
3247 // described completely in 3.7.3. The attributes and restrictions
3248 // found in the rest of this subclause do not apply to them unless
3249 // explicitly stated in 3.7.3.
Mike Stump390b4cc2009-05-16 07:39:55 +00003250 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003251 if (Op == OO_New || Op == OO_Array_New ||
3252 Op == OO_Delete || Op == OO_Array_Delete)
3253 return false;
3254
3255 // C++ [over.oper]p6:
3256 // An operator function shall either be a non-static member
3257 // function or be a non-member function and have at least one
3258 // parameter whose type is a class, a reference to a class, an
3259 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003260 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3261 if (MethodDecl->isStatic())
3262 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003263 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003264 } else {
3265 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003266 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3267 ParamEnd = FnDecl->param_end();
3268 Param != ParamEnd; ++Param) {
3269 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedman5d39dee2009-06-27 05:59:59 +00003270 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3271 ParamType->isEnumeralType()) {
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003272 ClassOrEnumParam = true;
3273 break;
3274 }
3275 }
3276
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003277 if (!ClassOrEnumParam)
3278 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003279 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003280 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003281 }
3282
3283 // C++ [over.oper]p8:
3284 // An operator function cannot have default arguments (8.3.6),
3285 // except where explicitly stated below.
3286 //
3287 // Only the function-call operator allows default arguments
3288 // (C++ [over.call]p1).
3289 if (Op != OO_Call) {
3290 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3291 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00003292 if ((*Param)->hasUnparsedDefaultArg())
3293 return Diag((*Param)->getLocation(),
3294 diag::err_operator_overload_default_arg)
3295 << FnDecl->getDeclName();
3296 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003297 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003298 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003299 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003300 }
3301 }
3302
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003303 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3304 { false, false, false }
3305#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3306 , { Unary, Binary, MemberOnly }
3307#include "clang/Basic/OperatorKinds.def"
3308 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003309
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003310 bool CanBeUnaryOperator = OperatorUses[Op][0];
3311 bool CanBeBinaryOperator = OperatorUses[Op][1];
3312 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003313
3314 // C++ [over.oper]p8:
3315 // [...] Operator functions cannot have more or fewer parameters
3316 // than the number required for the corresponding operator, as
3317 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003318 unsigned NumParams = FnDecl->getNumParams()
3319 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003320 if (Op != OO_Call &&
3321 ((NumParams == 1 && !CanBeUnaryOperator) ||
3322 (NumParams == 2 && !CanBeBinaryOperator) ||
3323 (NumParams < 1) || (NumParams > 2))) {
3324 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00003325 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003326 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003327 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003328 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00003329 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003330 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003331 assert(CanBeBinaryOperator &&
3332 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00003333 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00003334 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003335
Chris Lattner416e46f2008-11-21 07:57:12 +00003336 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003337 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003338 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003339
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003340 // Overloaded operators other than operator() cannot be variadic.
3341 if (Op != OO_Call &&
Douglas Gregor72564e72009-02-26 23:50:07 +00003342 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003343 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003344 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003345 }
3346
3347 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003348 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3349 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003350 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003351 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003352 }
3353
3354 // C++ [over.inc]p1:
3355 // The user-defined function called operator++ implements the
3356 // prefix and postfix ++ operator. If this function is a member
3357 // function with no parameters, or a non-member function with one
3358 // parameter of class or enumeration type, it defines the prefix
3359 // increment operator ++ for objects of that type. If the function
3360 // is a member function with one parameter (which shall be of type
3361 // int) or a non-member function with two parameters (the second
3362 // of which shall be of type int), it defines the postfix
3363 // increment operator ++ for objects of that type.
3364 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3365 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3366 bool ParamIsInt = false;
3367 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
3368 ParamIsInt = BT->getKind() == BuiltinType::Int;
3369
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00003370 if (!ParamIsInt)
3371 return Diag(LastParam->getLocation(),
3372 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00003373 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003374 }
3375
Sebastian Redl64b45f72009-01-05 20:52:13 +00003376 // Notify the class if it got an assignment operator.
3377 if (Op == OO_Equal) {
3378 // Would have returned earlier otherwise.
3379 assert(isa<CXXMethodDecl>(FnDecl) &&
3380 "Overloaded = not member, but not filtered.");
3381 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanianad258832009-08-13 21:09:41 +00003382 Method->setCopyAssignment(true);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003383 Method->getParent()->addedAssignmentOperator(Context, Method);
3384 }
3385
Douglas Gregor43c7bad2008-11-17 16:14:12 +00003386 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00003387}
Chris Lattner5a003a42008-12-17 07:09:26 +00003388
Douglas Gregor074149e2009-01-05 19:45:36 +00003389/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3390/// linkage specification, including the language and (if present)
3391/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3392/// the location of the language string literal, which is provided
3393/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3394/// the '{' brace. Otherwise, this linkage specification does not
3395/// have any braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003396Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3397 SourceLocation ExternLoc,
3398 SourceLocation LangLoc,
3399 const char *Lang,
3400 unsigned StrSize,
3401 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00003402 LinkageSpecDecl::LanguageIDs Language;
3403 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3404 Language = LinkageSpecDecl::lang_c;
3405 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3406 Language = LinkageSpecDecl::lang_cxx;
3407 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00003408 Diag(LangLoc, diag::err_bad_language);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003409 return DeclPtrTy();
Chris Lattnercc98eac2008-12-17 07:13:27 +00003410 }
3411
3412 // FIXME: Add all the various semantics of linkage specifications
3413
Douglas Gregor074149e2009-01-05 19:45:36 +00003414 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
3415 LangLoc, Language,
3416 LBraceLoc.isValid());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003417 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00003418 PushDeclContext(S, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003419 return DeclPtrTy::make(D);
Chris Lattnercc98eac2008-12-17 07:13:27 +00003420}
3421
Douglas Gregor074149e2009-01-05 19:45:36 +00003422/// ActOnFinishLinkageSpecification - Completely the definition of
3423/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3424/// valid, it's the position of the closing '}' brace in a linkage
3425/// specification that uses braces.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003426Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3427 DeclPtrTy LinkageSpec,
3428 SourceLocation RBraceLoc) {
Douglas Gregor074149e2009-01-05 19:45:36 +00003429 if (LinkageSpec)
3430 PopDeclContext();
3431 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00003432}
3433
Douglas Gregord308e622009-05-18 20:51:54 +00003434/// \brief Perform semantic analysis for the variable declaration that
3435/// occurs within a C++ catch clause, returning the newly-created
3436/// variable.
3437VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003438 DeclaratorInfo *DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003439 IdentifierInfo *Name,
3440 SourceLocation Loc,
3441 SourceRange Range) {
3442 bool Invalid = false;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003443
3444 // Arrays and functions decay.
3445 if (ExDeclType->isArrayType())
3446 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3447 else if (ExDeclType->isFunctionType())
3448 ExDeclType = Context.getPointerType(ExDeclType);
3449
3450 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3451 // The exception-declaration shall not denote a pointer or reference to an
3452 // incomplete type, other than [cv] void*.
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003453 // N2844 forbids rvalue references.
Douglas Gregor2f2433f2009-05-18 21:08:14 +00003454 if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregord308e622009-05-18 20:51:54 +00003455 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003456 Invalid = true;
3457 }
Douglas Gregord308e622009-05-18 20:51:54 +00003458
Sebastian Redl4b07b292008-12-22 19:15:10 +00003459 QualType BaseType = ExDeclType;
3460 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003461 unsigned DK = diag::err_catch_incomplete;
Ted Kremenek6217b802009-07-29 21:53:49 +00003462 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003463 BaseType = Ptr->getPointeeType();
3464 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003465 DK = diag::err_catch_incomplete_ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00003466 } else if(const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003467 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003468 BaseType = Ref->getPointeeType();
3469 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003470 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003471 }
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003472 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregord308e622009-05-18 20:51:54 +00003473 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00003474 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003475
Douglas Gregord308e622009-05-18 20:51:54 +00003476 if (!Invalid && !ExDeclType->isDependentType() &&
3477 RequireNonAbstractType(Loc, ExDeclType,
3478 diag::err_abstract_type_in_decl,
3479 AbstractVariableType))
Sebastian Redlfef9f592009-04-27 21:03:30 +00003480 Invalid = true;
3481
Douglas Gregord308e622009-05-18 20:51:54 +00003482 // FIXME: Need to test for ability to copy-construct and destroy the
3483 // exception variable.
3484
Sebastian Redl8351da02008-12-22 21:35:02 +00003485 // FIXME: Need to check for abstract classes.
3486
Douglas Gregord308e622009-05-18 20:51:54 +00003487 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +00003488 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregord308e622009-05-18 20:51:54 +00003489
3490 if (Invalid)
3491 ExDecl->setInvalidDecl();
3492
3493 return ExDecl;
3494}
3495
3496/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3497/// handler.
3498Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003499 DeclaratorInfo *DInfo = 0;
3500 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregord308e622009-05-18 20:51:54 +00003501
3502 bool Invalid = D.isInvalidType();
Sebastian Redl4b07b292008-12-22 19:15:10 +00003503 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003504 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003505 // The scope should be freshly made just for us. There is just no way
3506 // it contains any previous declaration.
Chris Lattnerb28317a2009-03-28 19:18:32 +00003507 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl4b07b292008-12-22 19:15:10 +00003508 if (PrevDecl->isTemplateParameter()) {
3509 // Maybe we will complain about the shadowed template parameter.
3510 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003511 }
3512 }
3513
Chris Lattnereaaebc72009-04-25 08:06:05 +00003514 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00003515 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3516 << D.getCXXScopeSpec().getRange();
Chris Lattnereaaebc72009-04-25 08:06:05 +00003517 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00003518 }
3519
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003520 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregord308e622009-05-18 20:51:54 +00003521 D.getIdentifier(),
3522 D.getIdentifierLoc(),
3523 D.getDeclSpec().getSourceRange());
3524
Chris Lattnereaaebc72009-04-25 08:06:05 +00003525 if (Invalid)
3526 ExDecl->setInvalidDecl();
3527
Sebastian Redl4b07b292008-12-22 19:15:10 +00003528 // Add the exception declaration into this scope.
Sebastian Redl4b07b292008-12-22 19:15:10 +00003529 if (II)
Douglas Gregord308e622009-05-18 20:51:54 +00003530 PushOnScopeChains(ExDecl, S);
3531 else
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003532 CurContext->addDecl(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003533
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003534 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003535 return DeclPtrTy::make(ExDecl);
Sebastian Redl4b07b292008-12-22 19:15:10 +00003536}
Anders Carlssonfb311762009-03-14 00:25:26 +00003537
Chris Lattnerb28317a2009-03-28 19:18:32 +00003538Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
3539 ExprArg assertexpr,
3540 ExprArg assertmessageexpr) {
Anders Carlssonfb311762009-03-14 00:25:26 +00003541 Expr *AssertExpr = (Expr *)assertexpr.get();
3542 StringLiteral *AssertMessage =
3543 cast<StringLiteral>((Expr *)assertmessageexpr.get());
3544
Anders Carlssonc3082412009-03-14 00:33:21 +00003545 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3546 llvm::APSInt Value(32);
3547 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3548 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3549 AssertExpr->getSourceRange();
Chris Lattnerb28317a2009-03-28 19:18:32 +00003550 return DeclPtrTy();
Anders Carlssonc3082412009-03-14 00:33:21 +00003551 }
Anders Carlssonfb311762009-03-14 00:25:26 +00003552
Anders Carlssonc3082412009-03-14 00:33:21 +00003553 if (Value == 0) {
3554 std::string str(AssertMessage->getStrData(),
3555 AssertMessage->getByteLength());
Anders Carlsson94b15fb2009-03-15 18:44:04 +00003556 Diag(AssertLoc, diag::err_static_assert_failed)
3557 << str << AssertExpr->getSourceRange();
Anders Carlssonc3082412009-03-14 00:33:21 +00003558 }
3559 }
3560
Anders Carlsson77d81422009-03-15 17:35:16 +00003561 assertexpr.release();
3562 assertmessageexpr.release();
Anders Carlssonfb311762009-03-14 00:25:26 +00003563 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
3564 AssertExpr, AssertMessage);
Anders Carlssonfb311762009-03-14 00:25:26 +00003565
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003566 CurContext->addDecl(Decl);
Chris Lattnerb28317a2009-03-28 19:18:32 +00003567 return DeclPtrTy::make(Decl);
Anders Carlssonfb311762009-03-14 00:25:26 +00003568}
Sebastian Redl50de12f2009-03-24 22:27:57 +00003569
John McCall67d1a672009-08-06 02:15:43 +00003570Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S,
John McCall3f9a8a62009-08-11 06:59:38 +00003571 llvm::PointerUnion<const DeclSpec*,Declarator*> DU,
3572 bool IsDefinition) {
John McCall02cace72009-08-28 07:59:38 +00003573 if (DU.is<Declarator*>())
3574 return ActOnFriendFunctionDecl(S, *DU.get<Declarator*>(), IsDefinition);
3575 else
3576 return ActOnFriendTypeDecl(S, *DU.get<const DeclSpec*>(), IsDefinition);
3577}
3578
3579Sema::DeclPtrTy Sema::ActOnFriendTypeDecl(Scope *S,
3580 const DeclSpec &DS,
3581 bool IsDefinition) {
3582 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall67d1a672009-08-06 02:15:43 +00003583
3584 assert(DS.isFriendSpecified());
3585 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
3586
John McCall02cace72009-08-28 07:59:38 +00003587 // Check to see if the decl spec was syntactically like "struct foo".
3588 RecordDecl *RD = NULL;
John McCall67d1a672009-08-06 02:15:43 +00003589
John McCall02cace72009-08-28 07:59:38 +00003590 switch (DS.getTypeSpecType()) {
3591 case DeclSpec::TST_class:
3592 case DeclSpec::TST_struct:
3593 case DeclSpec::TST_union:
3594 RD = dyn_cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
3595 if (!RD) return DeclPtrTy();
John McCall67d1a672009-08-06 02:15:43 +00003596
John McCall02cace72009-08-28 07:59:38 +00003597 // The parser doesn't quite handle
3598 // friend class A {}
3599 // as we'd like, because it might have been the (valid) prefix of
3600 // friend class A {} foo();
3601 // So even in C++0x mode we don't want to
3602 IsDefinition |= RD->isDefinition();
3603 break;
John McCall67d1a672009-08-06 02:15:43 +00003604
John McCall02cace72009-08-28 07:59:38 +00003605 default: break;
Anders Carlsson00338362009-05-11 22:55:49 +00003606 }
John McCall67d1a672009-08-06 02:15:43 +00003607
John McCall02cace72009-08-28 07:59:38 +00003608 FriendDecl::FriendUnion FU = RD;
John McCall67d1a672009-08-06 02:15:43 +00003609
John McCall02cace72009-08-28 07:59:38 +00003610 // C++ [class.friend]p2:
3611 // An elaborated-type-specifier shall be used in a friend declaration
3612 // for a class.*
3613 // * The class-key of the elaborated-type-specifier is required.
3614 // So if we didn't get a record decl above, we're invalid in C++98 mode.
3615 if (!RD) {
3616 bool invalid = false;
3617 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
3618 if (invalid) return DeclPtrTy();
3619
3620 if (const RecordType *RT = T->getAs<RecordType>()) {
3621 FU = RD = cast<CXXRecordDecl>(RT->getDecl());
3622
3623 // Untagged typenames are invalid prior to C++0x, but we can
3624 // suggest an easy fix which should work.
3625 if (!getLangOptions().CPlusPlus0x) {
3626 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
3627 << (RD->isUnion())
3628 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
3629 RD->isUnion() ? " union" : " class");
3630 return DeclPtrTy();
3631 }
3632 }else if (!getLangOptions().CPlusPlus0x) {
3633 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
3634 << DS.getSourceRange();
3635 return DeclPtrTy();
3636 }else {
3637 FU = T.getTypePtr();
3638 }
3639 }
3640
3641 assert(FU && "should have a friend decl/type by here!");
3642
3643 // C++ [class.friend]p2: A class shall not be defined inside
3644 // a friend declaration.
3645 if (IsDefinition) {
3646 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
3647 << DS.getSourceRange();
3648 return DeclPtrTy();
3649 }
3650
3651 // C++98 [class.friend]p1: A friend of a class is a function
3652 // or class that is not a member of the class . . .
3653 // But that's a silly restriction which nobody implements for
3654 // inner classes, and C++0x removes it anyway, so we only report
3655 // this (as a warning) if we're being pedantic.
3656 if (!getLangOptions().CPlusPlus0x) {
3657 assert(RD && "must have a record decl in C++98 mode");
3658 if (RD->getDeclContext() == CurContext)
3659 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
3660 }
3661
3662 FriendDecl *FD = FriendDecl::Create(Context, CurContext, Loc, FU,
3663 DS.getFriendSpecLoc());
3664 CurContext->addDecl(FD);
3665
3666 return DeclPtrTy::make(FD);
3667}
3668
3669Sema::DeclPtrTy Sema::ActOnFriendFunctionDecl(Scope *S,
3670 Declarator &D,
3671 bool IsDefinition) {
3672 const DeclSpec &DS = D.getDeclSpec();
3673
3674 assert(DS.isFriendSpecified());
3675 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
3676
3677 SourceLocation Loc = D.getIdentifierLoc();
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00003678 DeclaratorInfo *DInfo = 0;
John McCall02cace72009-08-28 07:59:38 +00003679 QualType T = GetTypeForDeclarator(D, S, &DInfo);
John McCall67d1a672009-08-06 02:15:43 +00003680
3681 // C++ [class.friend]p1
3682 // A friend of a class is a function or class....
3683 // Note that this sees through typedefs, which is intended.
John McCall02cace72009-08-28 07:59:38 +00003684 // It *doesn't* see through dependent types, which is correct
3685 // according to [temp.arg.type]p3:
3686 // If a declaration acquires a function type through a
3687 // type dependent on a template-parameter and this causes
3688 // a declaration that does not use the syntactic form of a
3689 // function declarator to have a function type, the program
3690 // is ill-formed.
John McCall67d1a672009-08-06 02:15:43 +00003691 if (!T->isFunctionType()) {
3692 Diag(Loc, diag::err_unexpected_friend);
3693
3694 // It might be worthwhile to try to recover by creating an
3695 // appropriate declaration.
3696 return DeclPtrTy();
3697 }
3698
3699 // C++ [namespace.memdef]p3
3700 // - If a friend declaration in a non-local class first declares a
3701 // class or function, the friend class or function is a member
3702 // of the innermost enclosing namespace.
3703 // - The name of the friend is not found by simple name lookup
3704 // until a matching declaration is provided in that namespace
3705 // scope (either before or after the class declaration granting
3706 // friendship).
3707 // - If a friend function is called, its name may be found by the
3708 // name lookup that considers functions from namespaces and
3709 // classes associated with the types of the function arguments.
3710 // - When looking for a prior declaration of a class or a function
3711 // declared as a friend, scopes outside the innermost enclosing
3712 // namespace scope are not considered.
3713
John McCall02cace72009-08-28 07:59:38 +00003714 CXXScopeSpec &ScopeQual = D.getCXXScopeSpec();
3715 DeclarationName Name = GetNameForDeclarator(D);
John McCall67d1a672009-08-06 02:15:43 +00003716 assert(Name);
3717
3718 // The existing declaration we found.
3719 FunctionDecl *FD = NULL;
3720
3721 // The context we found the declaration in, or in which we should
3722 // create the declaration.
3723 DeclContext *DC;
3724
3725 // FIXME: handle local classes
3726
3727 // Recover from invalid scope qualifiers as if they just weren't there.
3728 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
3729 DC = computeDeclContext(ScopeQual);
3730
3731 // FIXME: handle dependent contexts
3732 if (!DC) return DeclPtrTy();
3733
3734 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3735
3736 // If searching in that context implicitly found a declaration in
3737 // a different context, treat it like it wasn't found at all.
3738 // TODO: better diagnostics for this case. Suggesting the right
3739 // qualified scope would be nice...
3740 if (!Dec || Dec->getDeclContext() != DC) {
John McCall02cace72009-08-28 07:59:38 +00003741 D.setInvalidType();
John McCall67d1a672009-08-06 02:15:43 +00003742 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
3743 return DeclPtrTy();
3744 }
3745
3746 // C++ [class.friend]p1: A friend of a class is a function or
3747 // class that is not a member of the class . . .
3748 if (DC == CurContext)
3749 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
3750
3751 FD = cast<FunctionDecl>(Dec);
3752
3753 // Otherwise walk out to the nearest namespace scope looking for matches.
3754 } else {
3755 // TODO: handle local class contexts.
3756
3757 DC = CurContext;
3758 while (true) {
3759 // Skip class contexts. If someone can cite chapter and verse
3760 // for this behavior, that would be nice --- it's what GCC and
3761 // EDG do, and it seems like a reasonable intent, but the spec
3762 // really only says that checks for unqualified existing
3763 // declarations should stop at the nearest enclosing namespace,
3764 // not that they should only consider the nearest enclosing
3765 // namespace.
3766 while (DC->isRecord()) DC = DC->getParent();
3767
3768 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3769
3770 // TODO: decide what we think about using declarations.
3771 if (Dec) {
3772 FD = cast<FunctionDecl>(Dec);
3773 break;
3774 }
3775 if (DC->isFileContext()) break;
3776 DC = DC->getParent();
3777 }
3778
3779 // C++ [class.friend]p1: A friend of a class is a function or
3780 // class that is not a member of the class . . .
John McCall7f27d922009-08-06 20:49:32 +00003781 // C++0x changes this for both friend types and functions.
3782 // Most C++ 98 compilers do seem to give an error here, so
3783 // we do, too.
3784 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall67d1a672009-08-06 02:15:43 +00003785 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
3786 }
3787
John McCall3f9a8a62009-08-11 06:59:38 +00003788 bool Redeclaration = (FD != 0);
3789
3790 // If we found a match, create a friend function declaration with
3791 // that function as the previous declaration.
3792 if (Redeclaration) {
3793 // Create it in the semantic context of the original declaration.
3794 DC = FD->getDeclContext();
3795
John McCall67d1a672009-08-06 02:15:43 +00003796 // If we didn't find something matching the type exactly, create
3797 // a declaration. This declaration should only be findable via
3798 // argument-dependent lookup.
John McCall3f9a8a62009-08-11 06:59:38 +00003799 } else {
John McCall67d1a672009-08-06 02:15:43 +00003800 assert(DC->isFileContext());
3801
3802 // This implies that it has to be an operator or function.
John McCall02cace72009-08-28 07:59:38 +00003803 if (D.getKind() == Declarator::DK_Constructor ||
3804 D.getKind() == Declarator::DK_Destructor ||
3805 D.getKind() == Declarator::DK_Conversion) {
John McCall67d1a672009-08-06 02:15:43 +00003806 Diag(Loc, diag::err_introducing_special_friend) <<
John McCall02cace72009-08-28 07:59:38 +00003807 (D.getKind() == Declarator::DK_Constructor ? 0 :
3808 D.getKind() == Declarator::DK_Destructor ? 1 : 2);
John McCall67d1a672009-08-06 02:15:43 +00003809 return DeclPtrTy();
3810 }
John McCall67d1a672009-08-06 02:15:43 +00003811 }
3812
John McCall02cace72009-08-28 07:59:38 +00003813 NamedDecl *ND = ActOnFunctionDeclarator(S, D, DC, T, DInfo,
John McCall3f9a8a62009-08-11 06:59:38 +00003814 /* PrevDecl = */ FD,
3815 MultiTemplateParamsArg(*this),
3816 IsDefinition,
3817 Redeclaration);
John McCall02cace72009-08-28 07:59:38 +00003818 if (!ND) return DeclPtrTy();
3819 FD = cast<FunctionDecl>(ND);
John McCall3f9a8a62009-08-11 06:59:38 +00003820
John McCall88232aa2009-08-18 00:00:49 +00003821 assert(FD->getDeclContext() == DC);
3822 assert(FD->getLexicalDeclContext() == CurContext);
3823
John McCall02cace72009-08-28 07:59:38 +00003824 // We only add the function declaration to the lookup tables, not
3825 // the decl list, and only if the context isn't dependent.
3826 if (!CurContext->isDependentContext())
3827 DC->makeDeclVisibleInContext(FD);
3828
3829 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
3830 D.getIdentifierLoc(), FD,
3831 DS.getFriendSpecLoc());
3832 CurContext->addDecl(FrD);
John McCall67d1a672009-08-06 02:15:43 +00003833
3834 return DeclPtrTy::make(FD);
Anders Carlsson00338362009-05-11 22:55:49 +00003835}
3836
Chris Lattnerb28317a2009-03-28 19:18:32 +00003837void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003838 AdjustDeclIfTemplate(dcl);
3839
Chris Lattnerb28317a2009-03-28 19:18:32 +00003840 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redl50de12f2009-03-24 22:27:57 +00003841 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
3842 if (!Fn) {
3843 Diag(DelLoc, diag::err_deleted_non_function);
3844 return;
3845 }
3846 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
3847 Diag(DelLoc, diag::err_deleted_decl_not_first);
3848 Diag(Prev->getLocation(), diag::note_previous_declaration);
3849 // If the declaration wasn't the first, we delete the function anyway for
3850 // recovery.
3851 }
3852 Fn->setDeleted();
3853}
Sebastian Redl13e88542009-04-27 21:33:24 +00003854
3855static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
3856 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
3857 ++CI) {
3858 Stmt *SubStmt = *CI;
3859 if (!SubStmt)
3860 continue;
3861 if (isa<ReturnStmt>(SubStmt))
3862 Self.Diag(SubStmt->getSourceRange().getBegin(),
3863 diag::err_return_in_constructor_handler);
3864 if (!isa<Expr>(SubStmt))
3865 SearchForReturnInStmt(Self, SubStmt);
3866 }
3867}
3868
3869void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
3870 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
3871 CXXCatchStmt *Handler = TryBlock->getHandler(I);
3872 SearchForReturnInStmt(*this, Handler);
3873 }
3874}
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003875
3876bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3877 const CXXMethodDecl *Old) {
3878 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
3879 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
3880
3881 QualType CNewTy = Context.getCanonicalType(NewTy);
3882 QualType COldTy = Context.getCanonicalType(OldTy);
3883
3884 if (CNewTy == COldTy &&
3885 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
3886 return false;
3887
Anders Carlssonc3a68b22009-05-14 19:52:19 +00003888 // Check if the return types are covariant
3889 QualType NewClassTy, OldClassTy;
3890
3891 /// Both types must be pointers or references to classes.
3892 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
3893 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
3894 NewClassTy = NewPT->getPointeeType();
3895 OldClassTy = OldPT->getPointeeType();
3896 }
3897 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
3898 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
3899 NewClassTy = NewRT->getPointeeType();
3900 OldClassTy = OldRT->getPointeeType();
3901 }
3902 }
3903
3904 // The return types aren't either both pointers or references to a class type.
3905 if (NewClassTy.isNull()) {
3906 Diag(New->getLocation(),
3907 diag::err_different_return_type_for_overriding_virtual_function)
3908 << New->getDeclName() << NewTy << OldTy;
3909 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3910
3911 return true;
3912 }
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003913
Anders Carlssonc3a68b22009-05-14 19:52:19 +00003914 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
3915 // Check if the new class derives from the old class.
3916 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
3917 Diag(New->getLocation(),
3918 diag::err_covariant_return_not_derived)
3919 << New->getDeclName() << NewTy << OldTy;
3920 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3921 return true;
3922 }
3923
3924 // Check if we the conversion from derived to base is valid.
3925 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
3926 diag::err_covariant_return_inaccessible_base,
3927 diag::err_covariant_return_ambiguous_derived_to_base_conv,
3928 // FIXME: Should this point to the return type?
3929 New->getLocation(), SourceRange(), New->getDeclName())) {
3930 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3931 return true;
3932 }
3933 }
3934
3935 // The qualifiers of the return types must be the same.
3936 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
3937 Diag(New->getLocation(),
3938 diag::err_covariant_return_type_different_qualifications)
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003939 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonc3a68b22009-05-14 19:52:19 +00003940 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3941 return true;
3942 };
3943
3944
3945 // The new class type must have the same or less qualifiers as the old type.
3946 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
3947 Diag(New->getLocation(),
3948 diag::err_covariant_return_type_class_type_more_qualified)
3949 << New->getDeclName() << NewTy << OldTy;
3950 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3951 return true;
3952 };
3953
3954 return false;
Anders Carlssond7ba27d2009-05-14 01:09:04 +00003955}
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003956
Sebastian Redl23c7d062009-07-07 20:29:57 +00003957bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
3958 const CXXMethodDecl *Old)
3959{
3960 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
3961 diag::note_overridden_virtual_function,
3962 Old->getType()->getAsFunctionProtoType(),
3963 Old->getLocation(),
3964 New->getType()->getAsFunctionProtoType(),
3965 New->getLocation());
3966}
3967
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003968/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3969/// initializer for the declaration 'Dcl'.
3970/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3971/// static data member of class X, names should be looked up in the scope of
3972/// class X.
3973void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003974 AdjustDeclIfTemplate(Dcl);
3975
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003976 Decl *D = Dcl.getAs<Decl>();
3977 // If there is no declaration, there was an error parsing it.
3978 if (D == 0)
3979 return;
3980
3981 // Check whether it is a declaration with a nested name specifier like
3982 // int foo::bar;
3983 if (!D->isOutOfLine())
3984 return;
3985
3986 // C++ [basic.lookup.unqual]p13
3987 //
3988 // A name used in the definition of a static data member of class X
3989 // (after the qualified-id of the static member) is looked up as if the name
3990 // was used in a member function of X.
3991
3992 // Change current context into the context of the initializing declaration.
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00003993 EnterDeclaratorContext(S, D->getDeclContext());
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00003994}
3995
3996/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3997/// initializer for the declaration 'Dcl'.
3998void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregorefd5bda2009-08-24 11:57:43 +00003999 AdjustDeclIfTemplate(Dcl);
4000
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004001 Decl *D = Dcl.getAs<Decl>();
4002 // If there is no declaration, there was an error parsing it.
4003 if (D == 0)
4004 return;
4005
4006 // Check whether it is a declaration with a nested name specifier like
4007 // int foo::bar;
4008 if (!D->isOutOfLine())
4009 return;
4010
4011 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argyrios Kyrtzidis1d175532009-06-17 23:15:40 +00004012 ExitDeclaratorContext(S);
Argyrios Kyrtzidis0ffd9ff2009-06-17 22:50:06 +00004013}