blob: a18dc46fe7f6db44be071f7c832f9621034f7525 [file] [log] [blame]
Chris Lattnerac7b83a2008-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 Gregora65e8dd2008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Anders Carlsson412c3402009-03-24 01:19:16 +000018#include "clang/AST/DeclVisitor.h"
Douglas Gregor05904022008-10-22 21:13:31 +000019#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000020#include "clang/AST/StmtVisitor.h"
Anders Carlssona21e7872009-08-26 23:45:07 +000021#include "clang/Basic/PartialDiagnostic.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000022#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000023#include "clang/Parse/DeclSpec.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Chris Lattner97316c02008-04-10 02:22:51 +000025#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000026#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000027#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000028
29using namespace clang;
30
Chris Lattner97316c02008-04-10 02:22:51 +000031//===----------------------------------------------------------------------===//
32// CheckDefaultArgumentVisitor
33//===----------------------------------------------------------------------===//
34
Chris Lattnerb1856db2008-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 Lattnerd5a56aa2008-07-26 22:17:49 +000042 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000043 Expr *DefaultArg;
44 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000045
Chris Lattnerb1856db2008-04-12 23:52:44 +000046 public:
47 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
48 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000049
Chris Lattnerb1856db2008-04-12 23:52:44 +000050 bool VisitExpr(Expr *Node);
51 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000052 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000053 };
Chris Lattner97316c02008-04-10 02:22:51 +000054
Chris Lattnerb1856db2008-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 Lattnerd5a56aa2008-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 Lattnerb1856db2008-04-12 23:52:44 +000061 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000062 }
63
Chris Lattnerb1856db2008-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 Gregord2baafd2008-10-21 16:13:35 +000068 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-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 Lattner8ba580c2008-11-19 05:08:23 +000079 diag::err_param_default_argument_references_param)
Chris Lattnerb1753422008-11-23 21:45:46 +000080 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff72a6ebc2008-04-15 22:42:06 +000081 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000082 // C++ [dcl.fct.default]p7
83 // Local variables shall not be used in default argument
84 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000085 if (VDecl->isBlockVarDecl())
86 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000087 diag::err_param_default_argument_references_local)
Chris Lattnerb1753422008-11-23 21:45:46 +000088 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +000089 }
Chris Lattner97316c02008-04-10 02:22:51 +000090
Douglas Gregor3c246952008-11-04 13:41:56 +000091 return false;
92 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000093
Douglas Gregora5b022a2008-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 Lattner8ba580c2008-11-19 05:08:23 +0000100 diag::err_param_default_argument_references_this)
101 << ThisE->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +0000102 }
Chris Lattner97316c02008-04-10 02:22:51 +0000103}
104
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000105bool
106Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
107 SourceLocation EqualLoc)
108{
109 QualType ParamType = Param->getType();
110
Anders Carlssonec926872009-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 Carlsson60eb3be2009-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 Carlsson92936c42009-08-25 03:18:48 +0000127 return true;
Anders Carlsson60eb3be2009-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 Carlsson92936c42009-08-25 03:18:48 +0000136 return false;
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000137}
138
Chris Lattner97316c02008-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 Lattnerac7b83a2008-04-08 05:04:30 +0000142void
Chris Lattner5261d0c2009-03-28 19:18:32 +0000143Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000144 ExprArg defarg) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000145 if (!param || !defarg.get())
146 return;
147
Chris Lattner5261d0c2009-03-28 19:18:32 +0000148 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlssona116e6e2009-06-12 16:51:40 +0000149 UnparsedDefaultArgLocs.erase(Param);
150
Anders Carlssonc154a722009-05-01 19:30:39 +0000151 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000152 QualType ParamType = Param->getType();
153
154 // Default arguments are only permitted in C++
155 if (!getLangOptions().CPlusPlus) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000156 Diag(EqualLoc, diag::err_param_default_argument)
157 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000158 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000159 return;
160 }
161
Anders Carlssone0498192009-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 Carlsson60eb3be2009-08-25 02:29:20 +0000169 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000170}
171
Douglas Gregor62ae25a2008-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 Lattner5261d0c2009-03-28 19:18:32 +0000176void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlssona116e6e2009-06-12 16:51:40 +0000177 SourceLocation EqualLoc,
178 SourceLocation ArgLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000179 if (!param)
180 return;
181
Chris Lattner5261d0c2009-03-28 19:18:32 +0000182 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000183 if (Param)
184 Param->setUnparsedDefaultArg();
Anders Carlssona116e6e2009-06-12 16:51:40 +0000185
186 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000187}
188
Douglas Gregor605de8d2008-12-16 21:30:33 +0000189/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
190/// the default argument for the parameter param failed.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000191void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000192 if (!param)
193 return;
194
Anders Carlssona116e6e2009-06-12 16:51:40 +0000195 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
196
197 Param->setInvalidDecl();
198
199 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000200}
201
Douglas Gregor2b9422f2008-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 Lattner5261d0c2009-03-28 19:18:32 +0000215 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000216 DeclaratorChunk &chunk = D.getTypeObject(i);
217 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner5261d0c2009-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 Gregor62ae25a2008-12-24 00:01:03 +0000221 if (Param->hasUnparsedDefaultArg()) {
222 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor605de8d2008-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 Gregor62ae25a2008-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 Gregor2b9422f2008-05-07 04:49:29 +0000231 }
232 }
233 }
234 }
235}
236
Chris Lattnerac7b83a2008-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 Gregor083c23e2009-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 Lattnerac7b83a2008-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 Lattner8ba580c2008-11-19 05:08:23 +0000263 diag::err_param_default_argument_redefinition)
264 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000265 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregor083c23e2009-02-16 17:45:42 +0000266 Invalid = true;
Chris Lattnerac7b83a2008-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 Redl5e1e0a02009-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 Gregor083c23e2009-02-16 17:45:42 +0000279 return Invalid;
Chris Lattnerac7b83a2008-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 Carlsson73af5192009-08-25 01:23:32 +0000292 if (Param->hasDefaultArg())
Chris Lattnerac7b83a2008-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 Carlsson73af5192009-08-25 01:23:32 +0000305 if (!Param->hasDefaultArg()) {
Douglas Gregor605de8d2008-12-16 21:30:33 +0000306 if (Param->isInvalidDecl())
307 /* We already complained about this parameter. */;
308 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000309 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000310 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000311 << Param->getIdentifier();
Chris Lattnerac7b83a2008-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 Carlssona116e6e2009-06-12 16:51:40 +0000327 if (Param->hasDefaultArg()) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000328 if (!Param->hasUnparsedDefaultArg())
329 Param->getDefaultArg()->Destroy(Context);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000330 Param->setDefaultArg(0);
331 }
332 }
333 }
334}
Douglas Gregorec93f442008-04-13 21:30:24 +0000335
Douglas Gregorf15ac4b2008-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.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000340bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
341 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000342 CXXRecordDecl *CurDecl;
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000343 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregor0c3c9d02009-08-21 22:16:40 +0000344 DeclContext *DC = computeDeclContext(*SS, true);
Argiris Kirtzidis054a2632008-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 Gregorf15ac4b2008-10-31 09:07:45 +0000350 return &II == CurDecl->getIdentifier();
351 else
352 return false;
353}
354
Douglas Gregored3a3982009-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 Jahanian1373b6f2009-07-22 17:41:53 +0000374 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregored3a3982009-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 Carlssona21e7872009-08-26 23:45:07 +0000394 if (RequireCompleteType(BaseLoc, BaseType,
395 PDiag(diag::err_incomplete_base_class)
396 << SpecifierRange))
Douglas Gregored3a3982009-03-03 04:44:36 +0000397 return 0;
398
Eli Friedman10747ff2009-08-15 21:55:26 +0000399 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000400 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregored3a3982009-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 Friedman10747ff2009-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 Gregored3a3982009-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 Carlssonc6363712009-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 Gregorf73c8512009-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 Friedman10747ff2009-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 Carlssonc6363712009-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 Gregorf73c8512009-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 Carlssonc6363712009-04-16 00:08:20 +0000452 }
Anders Carlsson39a10db2009-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 Gregorf73c8512009-07-22 18:25:24 +0000457 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
458 Class->setHasTrivialDestructor(false);
Anders Carlssonc6363712009-04-16 00:08:20 +0000459
Douglas Gregored3a3982009-03-03 04:44:36 +0000460 // Create the base specifier.
461 // FIXME: Allocate via ASTContext?
Fariborz Jahanian1373b6f2009-07-22 17:41:53 +0000462 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregored3a3982009-03-03 04:44:36 +0000463 Class->getTagKind() == RecordDecl::TK_class,
464 Access, BaseType);
465}
466
Douglas Gregorec93f442008-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 Gregorabed2172008-10-22 17:49:05 +0000472Sema::BaseResult
Chris Lattner5261d0c2009-03-28 19:18:32 +0000473Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorabed2172008-10-22 17:49:05 +0000474 bool Virtual, AccessSpecifier Access,
475 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000476 if (!classdecl)
477 return true;
478
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000479 AdjustDeclIfTemplate(classdecl);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000480 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000481 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregored3a3982009-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 Gregorabed2172008-10-22 17:49:05 +0000488}
Douglas Gregorec93f442008-04-13 21:30:24 +0000489
Douglas Gregored3a3982009-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 Gregorabed2172008-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 Gregor4fd85902008-10-23 18:13:27 +0000499 // that the key is always the unqualified canonical type of the base
500 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000501 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
502
503 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000504 unsigned NumGoodBases = 0;
Douglas Gregored3a3982009-03-03 04:44:36 +0000505 bool Invalid = false;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000506 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000507 QualType NewBaseType
Douglas Gregored3a3982009-03-03 04:44:36 +0000508 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor4fd85902008-10-23 18:13:27 +0000509 NewBaseType = NewBaseType.getUnqualifiedType();
510
Douglas Gregorabed2172008-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 Gregored3a3982009-03-03 04:44:36 +0000515 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000516 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000517 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregored3a3982009-03-03 04:44:36 +0000518 << Bases[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000519
520 // Delete the duplicate base class specifier; we're going to
521 // overwrite its pointer later.
Douglas Gregorf2fedc62009-07-22 20:55:49 +0000522 Context.Deallocate(Bases[idx]);
Douglas Gregored3a3982009-03-03 04:44:36 +0000523
524 Invalid = true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000525 } else {
526 // Okay, add this new base class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000527 KnownBaseTypes[NewBaseType] = Bases[idx];
528 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000529 }
530 }
531
532 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9cd0a3c2009-07-02 18:26:15 +0000533 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor4fd85902008-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 Gregorf2fedc62009-07-22 20:55:49 +0000538 Context.Deallocate(Bases[idx]);
Douglas Gregored3a3982009-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 Lattner5261d0c2009-03-28 19:18:32 +0000546void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregored3a3982009-03-03 04:44:36 +0000547 unsigned NumBases) {
548 if (!ClassDecl || !Bases || !NumBases)
549 return;
550
551 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000552 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregored3a3982009-03-03 04:44:36 +0000553 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregorec93f442008-04-13 21:30:24 +0000554}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000555
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000556//===----------------------------------------------------------------------===//
557// C++ class member Handling
558//===----------------------------------------------------------------------===//
559
Argiris Kirtzidis38f16712008-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 Lattnerd6c78092009-04-12 22:37:57 +0000563/// any.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000564Sema::DeclPtrTy
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000565Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor398a8012009-08-20 22:52:58 +0000566 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redla55834a2009-04-12 17:16:29 +0000567 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000568 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000569 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-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 Redl9f5337b2008-11-14 23:42:31 +0000574 bool isFunc = D.isFunctionDeclarator();
575
John McCall140607b2009-08-06 02:15:43 +0000576 assert(!DS.isFriendSpecified());
577
Argiris Kirtzidis38f16712008-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 Redl9f5337b2008-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.
Argiris Kirtzidis38f16712008-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 Redl9f5337b2008-11-14 23:42:31 +0000589 case DeclSpec::SCS_mutable:
590 if (isFunc) {
591 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000592 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000593 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000594 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
595
Sebastian Redl6a2b7fd2008-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 Redl9f5337b2008-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 Redl6a2b7fd2008-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 Redl9f5337b2008-11-14 23:42:31 +0000613 D.getMutableDeclSpec().ClearStorageClassSpecs();
614 }
615 }
616 break;
Argiris Kirtzidis38f16712008-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
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000626 if (!isFunc &&
Douglas Gregora60c62e2009-02-09 15:09:02 +0000627 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000628 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000629 // Check also for this case:
630 //
631 // typedef int f();
632 // f a;
633 //
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000634 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregora60c62e2009-02-09 15:09:02 +0000635 isFunc = TDType->isFunctionType();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000636 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000637
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000638 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
639 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000640 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000641
642 Decl *Member;
Chris Lattner9cffefc2009-03-05 22:45:59 +0000643 if (isInstField) {
Douglas Gregor398a8012009-08-20 22:52:58 +0000644 // FIXME: Check for template parameters!
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000645 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
646 AS);
Chris Lattnere384c182009-03-05 23:03:49 +0000647 assert(Member && "HandleField never returns null");
Chris Lattner9cffefc2009-03-05 22:45:59 +0000648 } else {
Douglas Gregor398a8012009-08-20 22:52:58 +0000649 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
650 .getAs<Decl>();
Chris Lattnere384c182009-03-05 23:03:49 +0000651 if (!Member) {
652 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattnera17991f2009-03-29 16:50:03 +0000653 return DeclPtrTy();
Chris Lattnere384c182009-03-05 23:03:49 +0000654 }
Chris Lattner432780c2009-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 Gregor00660582009-03-11 20:22:50 +0000660 } else if (isa<VarDecl>(Member)) {
Chris Lattner432780c2009-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 Gregor0e518af2009-03-11 18:59:21 +0000673 << Name << cast<ValueDecl>(Member)->getType()
674 << BitWidth->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000675 }
676
677 DeleteExpr(BitWidth);
678 BitWidth = 0;
679 Member->setInvalidDecl();
680 }
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000681
682 Member->setAccess(AS);
Douglas Gregor398a8012009-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 Lattner9cffefc2009-03-05 22:45:59 +0000688 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000689
Douglas Gregor6704b312008-11-17 22:58:34 +0000690 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000691
Douglas Gregor8f53bb72009-03-11 23:00:04 +0000692 if (Init)
Chris Lattner5261d0c2009-03-28 19:18:32 +0000693 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redla55834a2009-04-12 17:16:29 +0000694 if (Deleted) // FIXME: Source location is not very good.
695 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000696
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000697 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000698 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattnera17991f2009-03-29 16:50:03 +0000699 return DeclPtrTy();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000700 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000701 return DeclPtrTy::make(Member);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000702}
703
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000704/// ActOnMemInitializer - Handle a C++ member initializer.
705Sema::MemInitResult
Chris Lattner5261d0c2009-03-28 19:18:32 +0000706Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000707 Scope *S,
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000708 const CXXScopeSpec &SS,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000709 IdentifierInfo *MemberOrBase,
Fariborz Jahanian2b2b7362009-07-01 19:21:19 +0000710 TypeTy *TemplateTypeTy,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000711 SourceLocation IdLoc,
712 SourceLocation LParenLoc,
713 ExprTy **Args, unsigned NumArgs,
714 SourceLocation *CommaLocs,
715 SourceLocation RParenLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000716 if (!ConstructorD)
717 return true;
718
Douglas Gregor84164f02009-08-24 11:57:43 +0000719 AdjustDeclIfTemplate(ConstructorD);
720
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000721 CXXConstructorDecl *Constructor
Chris Lattner5261d0c2009-03-28 19:18:32 +0000722 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregora65e8dd2008-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 Jahanian2b2b7362009-07-01 19:21:19 +0000743 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianc37d3062009-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 Gregora65e8dd2008-11-05 04:29:56 +0000750
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000751 // FIXME: Handle members of an anonymous union.
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000752
Eli Friedman724478c2009-07-29 19:44:27 +0000753 if (Member)
754 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
755 RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000756 }
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000757 // It didn't name a member, so see if it names a class.
Fariborz Jahanian2b2b7362009-07-01 19:21:19 +0000758 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
759 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000760 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000761 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
762 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000763
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000764 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000765
Eli Friedman724478c2009-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 Kremenekd00cd9e2009-07-29 21:53:49 +0000784 } else if (FieldType->getAs<RecordType>()) {
Eli Friedman724478c2009-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 Gregora65e8dd2008-11-05 04:29:56 +0000797 }
Eli Friedman724478c2009-07-29 19:44:27 +0000798 // FIXME: Perform direct initialization of the member.
799 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
800 NumArgs, C, IdLoc);
801}
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 Gregora65e8dd2008-11-05 04:29:56 +0000852 }
853 }
854 }
Eli Friedman724478c2009-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 Gregora65e8dd2008-11-05 04:29:56 +0000871 }
872
Fariborz Jahanian898f5742009-07-23 00:42:24 +0000873 CXXConstructorDecl *C = 0;
Eli Friedman724478c2009-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,
Fariborz Jahanian898f5742009-07-23 00:42:24 +0000883 NumArgs, C, IdLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000884}
885
Fariborz Jahanian7c1771c2009-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 Friedman16a1ca72009-07-21 19:28:10 +0000906static void *GetKeyForTopLevelField(FieldDecl *Field) {
907 // For anonymous unions, use the class declaration as the key.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000908 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman16a1ca72009-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 Jahanianfef75cb2009-08-11 18:49:54 +0000915static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
916 bool MemberMaybeAnon=false) {
Eli Friedman16a1ca72009-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 Jahanianfef75cb2009-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 Friedman16a1ca72009-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 Lattner5261d0c2009-03-28 19:18:32 +0000935void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssonc7f87202009-03-25 02:58:17 +0000936 SourceLocation ColonLoc,
937 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000938 if (!ConstructorDecl)
939 return;
Douglas Gregor84164f02009-08-24 11:57:43 +0000940
941 AdjustDeclIfTemplate(ConstructorDecl);
Douglas Gregorac77dd62009-06-22 23:20:33 +0000942
943 CXXConstructorDecl *Constructor
944 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Anders Carlssonc7f87202009-03-25 02:58:17 +0000945
946 if (!Constructor) {
947 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
948 return;
949 }
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000950 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
Fariborz Jahanianbb70eb32009-07-01 23:35:25 +0000951 bool err = false;
Fariborz Jahanian4e0aba82009-06-29 22:33:26 +0000952 for (unsigned i = 0; i < NumMemInits; i++) {
953 CXXBaseOrMemberInitializer *Member =
954 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
Eli Friedman16a1ca72009-07-21 19:28:10 +0000955 void *KeyToMember = GetKeyForMember(Member);
Fariborz Jahanianf75b9d52009-06-30 21:52:59 +0000956 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000957 if (!PrevMember) {
Fariborz Jahanian89f61bd2009-06-30 00:02:17 +0000958 PrevMember = Member;
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000959 continue;
Fariborz Jahanian4e0aba82009-06-29 22:33:26 +0000960 }
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000961 if (FieldDecl *Field = Member->getMember())
962 Diag(Member->getSourceLocation(),
963 diag::error_multiple_mem_initialization)
964 << Field->getNameAsString();
965 else {
966 Type *BaseClass = Member->getBaseClass();
967 assert(BaseClass && "ActOnMemInitializers - neither field or base");
968 Diag(Member->getSourceLocation(),
969 diag::error_multiple_base_initialization)
970 << BaseClass->getDesugaredType(true);
971 }
972 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
973 << 0;
Fariborz Jahanianbb70eb32009-07-01 23:35:25 +0000974 err = true;
Fariborz Jahanian4e0aba82009-06-29 22:33:26 +0000975 }
Fariborz Jahanian7c1771c2009-07-23 23:32:59 +0000976 if (!err)
977 BuildBaseOrMemberInitializers(Context, Constructor,
978 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
979 NumMemInits);
980
Eli Friedman16a1ca72009-07-21 19:28:10 +0000981 if (!err && (Diags.getDiagnosticLevel(diag::warn_base_initialized)
982 != Diagnostic::Ignored ||
983 Diags.getDiagnosticLevel(diag::warn_field_initialized)
984 != Diagnostic::Ignored)) {
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +0000985 // Also issue warning if order of ctor-initializer list does not match order
986 // of 1) base class declarations and 2) order of non-static data members.
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +0000987 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
988
989 CXXRecordDecl *ClassDecl
990 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanianc1ce61b2009-07-10 20:13:23 +0000991 // Push virtual bases before others.
992 for (CXXRecordDecl::base_class_iterator VBase =
993 ClassDecl->vbases_begin(),
994 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000995 AllBaseOrMembers.push_back(VBase->getType()->getAs<RecordType>());
Fariborz Jahanianc1ce61b2009-07-10 20:13:23 +0000996
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +0000997 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
Fariborz Jahanianc1ce61b2009-07-10 20:13:23 +0000998 E = ClassDecl->bases_end(); Base != E; ++Base) {
999 // Virtuals are alread in the virtual base list and are constructed
1000 // first.
1001 if (Base->isVirtual())
1002 continue;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001003 AllBaseOrMembers.push_back(Base->getType()->getAs<RecordType>());
Fariborz Jahanianc1ce61b2009-07-10 20:13:23 +00001004 }
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001005
1006 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1007 E = ClassDecl->field_end(); Field != E; ++Field)
Eli Friedman16a1ca72009-07-21 19:28:10 +00001008 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001009
1010 int Last = AllBaseOrMembers.size();
1011 int curIndex = 0;
1012 CXXBaseOrMemberInitializer *PrevMember = 0;
1013 for (unsigned i = 0; i < NumMemInits; i++) {
1014 CXXBaseOrMemberInitializer *Member =
1015 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001016 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman16a1ca72009-07-21 19:28:10 +00001017
1018 for (; curIndex < Last; curIndex++)
1019 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001020 break;
Eli Friedman16a1ca72009-07-21 19:28:10 +00001021 if (curIndex == Last) {
1022 assert(PrevMember && "Member not in member list?!");
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001023 // Initializer as specified in ctor-initializer list is out of order.
1024 // Issue a warning diagnostic.
1025 if (PrevMember->isBaseInitializer()) {
1026 // Diagnostics is for an initialized base class.
1027 Type *BaseClass = PrevMember->getBaseClass();
1028 Diag(PrevMember->getSourceLocation(),
1029 diag::warn_base_initialized)
1030 << BaseClass->getDesugaredType(true);
Mike Stump90fc78e2009-08-04 21:02:39 +00001031 } else {
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001032 FieldDecl *Field = PrevMember->getMember();
1033 Diag(PrevMember->getSourceLocation(),
1034 diag::warn_field_initialized)
1035 << Field->getNameAsString();
1036 }
1037 // Also the note!
1038 if (FieldDecl *Field = Member->getMember())
1039 Diag(Member->getSourceLocation(),
1040 diag::note_fieldorbase_initialized_here) << 0
1041 << Field->getNameAsString();
1042 else {
1043 Type *BaseClass = Member->getBaseClass();
1044 Diag(Member->getSourceLocation(),
1045 diag::note_fieldorbase_initialized_here) << 1
1046 << BaseClass->getDesugaredType(true);
1047 }
Eli Friedman16a1ca72009-07-21 19:28:10 +00001048 for (curIndex = 0; curIndex < Last; curIndex++)
1049 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1050 break;
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001051 }
1052 PrevMember = Member;
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001053 }
1054 }
Anders Carlssonc7f87202009-03-25 02:58:17 +00001055}
1056
Fariborz Jahanian4e127232009-07-21 22:36:06 +00001057void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian21e25e72009-07-15 22:34:08 +00001058 if (!CDtorDecl)
Fariborz Jahanian9294d192009-07-14 18:24:21 +00001059 return;
1060
Douglas Gregor84164f02009-08-24 11:57:43 +00001061 AdjustDeclIfTemplate(CDtorDecl);
1062
Fariborz Jahanian9294d192009-07-14 18:24:21 +00001063 if (CXXConstructorDecl *Constructor
Fariborz Jahanian21e25e72009-07-15 22:34:08 +00001064 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian7c1771c2009-07-23 23:32:59 +00001065 BuildBaseOrMemberInitializers(Context,
1066 Constructor,
1067 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahanian9294d192009-07-14 18:24:21 +00001068}
1069
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001070namespace {
1071 /// PureVirtualMethodCollector - traverses a class and its superclasses
1072 /// and determines if it has any pure virtual methods.
1073 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1074 ASTContext &Context;
1075
Sebastian Redl16ac38f2009-03-22 21:28:55 +00001076 public:
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001077 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redl16ac38f2009-03-22 21:28:55 +00001078
1079 private:
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001080 MethodList Methods;
1081
1082 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
1083
1084 public:
1085 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
1086 : Context(Ctx) {
1087
1088 MethodList List;
1089 Collect(RD, List);
1090
1091 // Copy the temporary list to methods, and make sure to ignore any
1092 // null entries.
1093 for (size_t i = 0, e = List.size(); i != e; ++i) {
1094 if (List[i])
1095 Methods.push_back(List[i]);
1096 }
1097 }
1098
Anders Carlssone1299b32009-03-22 20:18:17 +00001099 bool empty() const { return Methods.empty(); }
1100
1101 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1102 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001103 };
1104
1105 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
1106 MethodList& Methods) {
1107 // First, collect the pure virtual methods for the base classes.
1108 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1109 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001110 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner330a05b2009-03-29 05:01:10 +00001111 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001112 if (BaseDecl && BaseDecl->isAbstract())
1113 Collect(BaseDecl, Methods);
1114 }
1115 }
1116
1117 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001118 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
1119
1120 MethodSetTy OverriddenMethods;
1121 size_t MethodsSize = Methods.size();
1122
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001123 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001124 i != e; ++i) {
1125 // Traverse the record, looking for methods.
1126 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl953d12a2009-07-07 20:29:57 +00001127 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001128 if (MD->isPure()) {
1129 Methods.push_back(MD);
1130 continue;
1131 }
1132
1133 // Otherwise, record all the overridden methods in our set.
1134 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1135 E = MD->end_overridden_methods(); I != E; ++I) {
1136 // Keep track of the overridden methods.
1137 OverriddenMethods.insert(*I);
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001138 }
1139 }
1140 }
1141
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001142 // Now go through the methods and zero out all the ones we know are
1143 // overridden.
1144 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1145 if (OverriddenMethods.count(Methods[i]))
1146 Methods[i] = 0;
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001147 }
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001148
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001149 }
1150}
Douglas Gregora65e8dd2008-11-05 04:29:56 +00001151
Anders Carlsson62ce5832009-08-27 00:13:57 +00001152
Anders Carlssone1299b32009-03-22 20:18:17 +00001153bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonde9e7892009-03-24 17:23:42 +00001154 unsigned DiagID, AbstractDiagSelID SelID,
1155 const CXXRecordDecl *CurrentRD) {
Anders Carlsson62ce5832009-08-27 00:13:57 +00001156 if (SelID == -1)
1157 return RequireNonAbstractType(Loc, T,
1158 PDiag(DiagID), CurrentRD);
1159 else
1160 return RequireNonAbstractType(Loc, T,
1161 PDiag(DiagID) << SelID, CurrentRD);
1162}
Anders Carlssone1299b32009-03-22 20:18:17 +00001163
Anders Carlsson62ce5832009-08-27 00:13:57 +00001164bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
1165 const PartialDiagnostic &PD,
1166 const CXXRecordDecl *CurrentRD) {
Anders Carlssone1299b32009-03-22 20:18:17 +00001167 if (!getLangOptions().CPlusPlus)
1168 return false;
Anders Carlssonc263c9b2009-03-23 19:10:31 +00001169
1170 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlsson62ce5832009-08-27 00:13:57 +00001171 return RequireNonAbstractType(Loc, AT->getElementType(), PD,
Anders Carlssonde9e7892009-03-24 17:23:42 +00001172 CurrentRD);
Anders Carlssonce9240e2009-03-24 01:46:45 +00001173
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001174 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlssonce9240e2009-03-24 01:46:45 +00001175 // Find the innermost pointer type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001176 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlssonce9240e2009-03-24 01:46:45 +00001177 PT = T;
Anders Carlssone1299b32009-03-22 20:18:17 +00001178
Anders Carlssonce9240e2009-03-24 01:46:45 +00001179 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlsson62ce5832009-08-27 00:13:57 +00001180 return RequireNonAbstractType(Loc, AT->getElementType(), PD, CurrentRD);
Anders Carlssonce9240e2009-03-24 01:46:45 +00001181 }
1182
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001183 const RecordType *RT = T->getAs<RecordType>();
Anders Carlssone1299b32009-03-22 20:18:17 +00001184 if (!RT)
1185 return false;
1186
1187 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1188 if (!RD)
1189 return false;
1190
Anders Carlssonde9e7892009-03-24 17:23:42 +00001191 if (CurrentRD && CurrentRD != RD)
1192 return false;
1193
Anders Carlssone1299b32009-03-22 20:18:17 +00001194 if (!RD->isAbstract())
1195 return false;
1196
Anders Carlsson62ce5832009-08-27 00:13:57 +00001197 Diag(Loc, PD) << RD->getDeclName();
Anders Carlssone1299b32009-03-22 20:18:17 +00001198
1199 // Check if we've already emitted the list of pure virtual functions for this
1200 // class.
1201 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1202 return true;
1203
1204 PureVirtualMethodCollector Collector(Context, RD);
1205
1206 for (PureVirtualMethodCollector::MethodList::const_iterator I =
1207 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1208 const CXXMethodDecl *MD = *I;
1209
1210 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
1211 MD->getDeclName();
1212 }
1213
1214 if (!PureVirtualClassDiagSet)
1215 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1216 PureVirtualClassDiagSet->insert(RD);
1217
1218 return true;
1219}
1220
Anders Carlsson412c3402009-03-24 01:19:16 +00001221namespace {
1222 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
1223 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1224 Sema &SemaRef;
1225 CXXRecordDecl *AbstractClass;
1226
Anders Carlssonde9e7892009-03-24 17:23:42 +00001227 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson412c3402009-03-24 01:19:16 +00001228 bool Invalid = false;
1229
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001230 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1231 E = DC->decls_end(); I != E; ++I)
Anders Carlsson412c3402009-03-24 01:19:16 +00001232 Invalid |= Visit(*I);
Anders Carlssonde9e7892009-03-24 17:23:42 +00001233
Anders Carlsson412c3402009-03-24 01:19:16 +00001234 return Invalid;
1235 }
Anders Carlssonde9e7892009-03-24 17:23:42 +00001236
1237 public:
1238 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1239 : SemaRef(SemaRef), AbstractClass(ac) {
1240 Visit(SemaRef.Context.getTranslationUnitDecl());
1241 }
Anders Carlsson412c3402009-03-24 01:19:16 +00001242
Anders Carlssonde9e7892009-03-24 17:23:42 +00001243 bool VisitFunctionDecl(const FunctionDecl *FD) {
1244 if (FD->isThisDeclarationADefinition()) {
1245 // No need to do the check if we're in a definition, because it requires
1246 // that the return/param types are complete.
1247 // because that requires
1248 return VisitDeclContext(FD);
1249 }
1250
1251 // Check the return type.
1252 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
1253 bool Invalid =
1254 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1255 diag::err_abstract_type_in_decl,
1256 Sema::AbstractReturnType,
1257 AbstractClass);
1258
1259 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
1260 E = FD->param_end(); I != E; ++I) {
Anders Carlsson412c3402009-03-24 01:19:16 +00001261 const ParmVarDecl *VD = *I;
1262 Invalid |=
1263 SemaRef.RequireNonAbstractType(VD->getLocation(),
1264 VD->getOriginalType(),
1265 diag::err_abstract_type_in_decl,
Anders Carlssonde9e7892009-03-24 17:23:42 +00001266 Sema::AbstractParamType,
1267 AbstractClass);
Anders Carlsson412c3402009-03-24 01:19:16 +00001268 }
1269
1270 return Invalid;
1271 }
Anders Carlssonde9e7892009-03-24 17:23:42 +00001272
1273 bool VisitDecl(const Decl* D) {
1274 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1275 return VisitDeclContext(DC);
1276
1277 return false;
1278 }
Anders Carlsson412c3402009-03-24 01:19:16 +00001279 };
1280}
1281
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001282void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001283 DeclPtrTy TagDecl,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001284 SourceLocation LBrac,
1285 SourceLocation RBrac) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001286 if (!TagDecl)
1287 return;
1288
Douglas Gregor3eb20702009-05-11 19:58:34 +00001289 AdjustDeclIfTemplate(TagDecl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001290 ActOnFields(S, RLoc, TagDecl,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001291 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +00001292 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregored3a3982009-03-03 04:44:36 +00001293
Chris Lattner5261d0c2009-03-28 19:18:32 +00001294 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001295 if (!RD->isAbstract()) {
1296 // Collect all the pure virtual methods and see if this is an abstract
1297 // class after all.
1298 PureVirtualMethodCollector Collector(Context, RD);
1299 if (!Collector.empty())
1300 RD->setAbstract(true);
1301 }
1302
Anders Carlssonde9e7892009-03-24 17:23:42 +00001303 if (RD->isAbstract())
1304 AbstractClassUsageDiagnoser(*this, RD);
Anders Carlsson412c3402009-03-24 01:19:16 +00001305
Douglas Gregor3eb20702009-05-11 19:58:34 +00001306 if (!RD->isDependentType())
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001307 AddImplicitlyDeclaredMembersToClass(RD);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001308}
1309
Douglas Gregore640ab62008-11-03 17:51:48 +00001310/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1311/// special functions, such as the default constructor, copy
1312/// constructor, or destructor, to the given C++ class (C++
1313/// [special]p1). This routine can only be executed just before the
1314/// definition of the class is complete.
1315void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregorcfe6ae52009-08-05 05:36:45 +00001316 CanQualType ClassType
1317 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001318
Sebastian Redl2767d882009-05-27 22:11:52 +00001319 // FIXME: Implicit declarations have exception specifications, which are
1320 // the union of the specifications of the implicitly called functions.
1321
Douglas Gregore640ab62008-11-03 17:51:48 +00001322 if (!ClassDecl->hasUserDeclaredConstructor()) {
1323 // C++ [class.ctor]p5:
1324 // A default constructor for a class X is a constructor of class X
1325 // that can be called without an argument. If there is no
1326 // user-declared constructor for class X, a default constructor is
1327 // implicitly declared. An implicitly-declared default constructor
1328 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001329 DeclarationName Name
1330 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001331 CXXConstructorDecl *DefaultCon =
1332 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001333 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +00001334 Context.getFunctionType(Context.VoidTy,
1335 0, 0, false, 0),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001336 /*DInfo=*/0,
Douglas Gregore640ab62008-11-03 17:51:48 +00001337 /*isExplicit=*/false,
1338 /*isInline=*/true,
1339 /*isImplicitlyDeclared=*/true);
1340 DefaultCon->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001341 DefaultCon->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001342 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001343 ClassDecl->addDecl(DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +00001344 }
1345
1346 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1347 // C++ [class.copy]p4:
1348 // If the class definition does not explicitly declare a copy
1349 // constructor, one is declared implicitly.
1350
1351 // C++ [class.copy]p5:
1352 // The implicitly-declared copy constructor for a class X will
1353 // have the form
1354 //
1355 // X::X(const X&)
1356 //
1357 // if
1358 bool HasConstCopyConstructor = true;
1359
1360 // -- each direct or virtual base class B of X has a copy
1361 // constructor whose first parameter is of type const B& or
1362 // const volatile B&, and
1363 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1364 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1365 const CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001366 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregore640ab62008-11-03 17:51:48 +00001367 HasConstCopyConstructor
1368 = BaseClassDecl->hasConstCopyConstructor(Context);
1369 }
1370
1371 // -- for all the nonstatic data members of X that are of a
1372 // class type M (or array thereof), each such class type
1373 // has a copy constructor whose first parameter is of type
1374 // const M& or const volatile M&.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001375 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1376 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001377 ++Field) {
Douglas Gregore640ab62008-11-03 17:51:48 +00001378 QualType FieldType = (*Field)->getType();
1379 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1380 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001381 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregore640ab62008-11-03 17:51:48 +00001382 const CXXRecordDecl *FieldClassDecl
1383 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1384 HasConstCopyConstructor
1385 = FieldClassDecl->hasConstCopyConstructor(Context);
1386 }
1387 }
1388
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001389 // Otherwise, the implicitly declared copy constructor will have
1390 // the form
Douglas Gregore640ab62008-11-03 17:51:48 +00001391 //
1392 // X::X(X&)
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001393 QualType ArgType = ClassType;
Douglas Gregore640ab62008-11-03 17:51:48 +00001394 if (HasConstCopyConstructor)
1395 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +00001396 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001397
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001398 // An implicitly-declared copy constructor is an inline public
1399 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001400 DeclarationName Name
1401 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001402 CXXConstructorDecl *CopyConstructor
1403 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001404 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +00001405 Context.getFunctionType(Context.VoidTy,
1406 &ArgType, 1,
1407 false, 0),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001408 /*DInfo=*/0,
Douglas Gregore640ab62008-11-03 17:51:48 +00001409 /*isExplicit=*/false,
1410 /*isInline=*/true,
1411 /*isImplicitlyDeclared=*/true);
1412 CopyConstructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001413 CopyConstructor->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001414 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregore640ab62008-11-03 17:51:48 +00001415
1416 // Add the parameter to the constructor.
1417 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1418 ClassDecl->getLocation(),
1419 /*IdentifierInfo=*/0,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001420 ArgType, /*DInfo=*/0,
1421 VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001422 CopyConstructor->setParams(Context, &FromParam, 1);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001423 ClassDecl->addDecl(CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +00001424 }
1425
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001426 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1427 // Note: The following rules are largely analoguous to the copy
1428 // constructor rules. Note that virtual bases are not taken into account
1429 // for determining the argument type of the operator. Note also that
1430 // operators taking an object instead of a reference are allowed.
1431 //
1432 // C++ [class.copy]p10:
1433 // If the class definition does not explicitly declare a copy
1434 // assignment operator, one is declared implicitly.
1435 // The implicitly-defined copy assignment operator for a class X
1436 // will have the form
1437 //
1438 // X& X::operator=(const X&)
1439 //
1440 // if
1441 bool HasConstCopyAssignment = true;
1442
1443 // -- each direct base class B of X has a copy assignment operator
1444 // whose parameter is of type const B&, const volatile B& or B,
1445 // and
1446 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1447 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1448 const CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001449 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian04500242009-08-12 23:34:46 +00001450 const CXXMethodDecl *MD = 0;
1451 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
1452 MD);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001453 }
1454
1455 // -- for all the nonstatic data members of X that are of a class
1456 // type M (or array thereof), each such class type has a copy
1457 // assignment operator whose parameter is of type const M&,
1458 // const volatile M& or M.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001459 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1460 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001461 ++Field) {
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001462 QualType FieldType = (*Field)->getType();
1463 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1464 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001465 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001466 const CXXRecordDecl *FieldClassDecl
1467 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian04500242009-08-12 23:34:46 +00001468 const CXXMethodDecl *MD = 0;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001469 HasConstCopyAssignment
Fariborz Jahanian04500242009-08-12 23:34:46 +00001470 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001471 }
1472 }
1473
1474 // Otherwise, the implicitly declared copy assignment operator will
1475 // have the form
1476 //
1477 // X& X::operator=(X&)
1478 QualType ArgType = ClassType;
Sebastian Redlce6fff02009-03-16 23:22:08 +00001479 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001480 if (HasConstCopyAssignment)
1481 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +00001482 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001483
1484 // An implicitly-declared copy assignment operator is an inline public
1485 // member of its class.
1486 DeclarationName Name =
1487 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1488 CXXMethodDecl *CopyAssignment =
1489 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1490 Context.getFunctionType(RetType, &ArgType, 1,
1491 false, 0),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001492 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001493 CopyAssignment->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001494 CopyAssignment->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001495 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001496 CopyAssignment->setCopyAssignment(true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001497
1498 // Add the parameter to the operator.
1499 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1500 ClassDecl->getLocation(),
1501 /*IdentifierInfo=*/0,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001502 ArgType, /*DInfo=*/0,
1503 VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001504 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001505
1506 // Don't call addedAssignmentOperator. There is no way to distinguish an
1507 // implicit from an explicit assignment operator.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001508 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001509 }
1510
Douglas Gregorb9213832008-12-15 21:24:18 +00001511 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001512 // C++ [class.dtor]p2:
1513 // If a class has no user-declared destructor, a destructor is
1514 // declared implicitly. An implicitly-declared destructor is an
1515 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001516 DeclarationName Name
1517 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001518 CXXDestructorDecl *Destructor
1519 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001520 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001521 Context.getFunctionType(Context.VoidTy,
1522 0, 0, false, 0),
1523 /*isInline=*/true,
1524 /*isImplicitlyDeclared=*/true);
1525 Destructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001526 Destructor->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001527 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001528 ClassDecl->addDecl(Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001529 }
Douglas Gregore640ab62008-11-03 17:51:48 +00001530}
1531
Douglas Gregora376cbd2009-05-27 23:11:45 +00001532void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1533 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1534 if (!Template)
1535 return;
1536
1537 TemplateParameterList *Params = Template->getTemplateParameters();
1538 for (TemplateParameterList::iterator Param = Params->begin(),
1539 ParamEnd = Params->end();
1540 Param != ParamEnd; ++Param) {
1541 NamedDecl *Named = cast<NamedDecl>(*Param);
1542 if (Named->getDeclName()) {
1543 S->AddDecl(DeclPtrTy::make(Named));
1544 IdResolver.AddDecl(Named);
1545 }
1546 }
1547}
1548
Douglas Gregor605de8d2008-12-16 21:30:33 +00001549/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1550/// parsing a top-level (non-nested) C++ class, and we are now
1551/// parsing those parts of the given Method declaration that could
1552/// not be parsed earlier (C++ [class.mem]p2), such as default
1553/// arguments. This action should enter the scope of the given
1554/// Method declaration as if we had just parsed the qualified method
1555/// name. However, it should not bring the parameters into scope;
1556/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001557void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001558 if (!MethodD)
1559 return;
1560
Douglas Gregor84164f02009-08-24 11:57:43 +00001561 AdjustDeclIfTemplate(MethodD);
1562
Douglas Gregor605de8d2008-12-16 21:30:33 +00001563 CXXScopeSpec SS;
Chris Lattner5261d0c2009-03-28 19:18:32 +00001564 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001565 QualType ClassTy
1566 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1567 SS.setScopeRep(
1568 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001569 ActOnCXXEnterDeclaratorScope(S, SS);
1570}
1571
1572/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1573/// C++ method declaration. We're (re-)introducing the given
1574/// function parameter into scope for use in parsing later parts of
1575/// the method declaration. For example, we could see an
1576/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001577void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001578 if (!ParamD)
1579 return;
1580
Chris Lattner5261d0c2009-03-28 19:18:32 +00001581 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001582
1583 // If this parameter has an unparsed default argument, clear it out
1584 // to make way for the parsed default argument.
1585 if (Param->hasUnparsedDefaultArg())
1586 Param->setDefaultArg(0);
1587
Chris Lattner5261d0c2009-03-28 19:18:32 +00001588 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001589 if (Param->getDeclName())
1590 IdResolver.AddDecl(Param);
1591}
1592
1593/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1594/// processing the delayed method declaration for Method. The method
1595/// declaration is now considered finished. There may be a separate
1596/// ActOnStartOfFunctionDef action later (not necessarily
1597/// immediately!) for this method, if it was also defined inside the
1598/// class body.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001599void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001600 if (!MethodD)
1601 return;
1602
Douglas Gregor84164f02009-08-24 11:57:43 +00001603 AdjustDeclIfTemplate(MethodD);
1604
Chris Lattner5261d0c2009-03-28 19:18:32 +00001605 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor605de8d2008-12-16 21:30:33 +00001606 CXXScopeSpec SS;
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001607 QualType ClassTy
1608 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1609 SS.setScopeRep(
1610 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001611 ActOnCXXExitDeclaratorScope(S, SS);
1612
1613 // Now that we have our default arguments, check the constructor
1614 // again. It could produce additional diagnostics or affect whether
1615 // the class has implicitly-declared destructors, among other
1616 // things.
Chris Lattner08da4772009-04-25 08:35:12 +00001617 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1618 CheckConstructor(Constructor);
Douglas Gregor605de8d2008-12-16 21:30:33 +00001619
1620 // Check the default arguments, which we may have added.
1621 if (!Method->isInvalidDecl())
1622 CheckCXXDefaultArguments(Method);
1623}
1624
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001625/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +00001626/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001627/// R. If there are any errors in the declarator, this routine will
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001628/// emit diagnostics and set the invalid bit to true. In any case, the type
1629/// will be updated to reflect a well-formed type for the constructor and
1630/// returned.
1631QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1632 FunctionDecl::StorageClass &SC) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001633 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001634
1635 // C++ [class.ctor]p3:
1636 // A constructor shall not be virtual (10.3) or static (9.4). A
1637 // constructor can be invoked for a const, volatile or const
1638 // volatile object. A constructor shall not be declared const,
1639 // volatile, or const volatile (9.3.2).
1640 if (isVirtual) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001641 if (!D.isInvalidType())
1642 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1643 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1644 << SourceRange(D.getIdentifierLoc());
1645 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001646 }
1647 if (SC == FunctionDecl::Static) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001648 if (!D.isInvalidType())
1649 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1650 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1651 << SourceRange(D.getIdentifierLoc());
1652 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001653 SC = FunctionDecl::None;
1654 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001655
1656 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1657 if (FTI.TypeQuals != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001658 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001659 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1660 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001661 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001662 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1663 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001664 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001665 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1666 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001667 }
1668
1669 // Rebuild the function type "R" without any type qualifiers (in
1670 // case any of the errors above fired) and with "void" as the
1671 // return type, since constructors don't have return types. We
1672 // *always* have to do this, because GetTypeForDeclarator will
1673 // put in a result type of "int" when none was specified.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001674 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001675 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1676 Proto->getNumArgs(),
1677 Proto->isVariadic(), 0);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001678}
1679
Douglas Gregor605de8d2008-12-16 21:30:33 +00001680/// CheckConstructor - Checks a fully-formed constructor for
1681/// well-formedness, issuing any diagnostics required. Returns true if
1682/// the constructor declarator is invalid.
Chris Lattner08da4772009-04-25 08:35:12 +00001683void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Douglas Gregor869cabf2009-03-27 04:38:56 +00001684 CXXRecordDecl *ClassDecl
1685 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1686 if (!ClassDecl)
Chris Lattner08da4772009-04-25 08:35:12 +00001687 return Constructor->setInvalidDecl();
Douglas Gregor605de8d2008-12-16 21:30:33 +00001688
1689 // C++ [class.copy]p3:
1690 // A declaration of a constructor for a class X is ill-formed if
1691 // its first parameter is of type (optionally cv-qualified) X and
1692 // either there are no other parameters or else all other
1693 // parameters have default arguments.
Douglas Gregor869cabf2009-03-27 04:38:56 +00001694 if (!Constructor->isInvalidDecl() &&
1695 ((Constructor->getNumParams() == 1) ||
1696 (Constructor->getNumParams() > 1 &&
Anders Carlssond2e57d92009-06-06 04:14:07 +00001697 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00001698 QualType ParamType = Constructor->getParamDecl(0)->getType();
1699 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1700 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00001701 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
1702 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor133d2552009-04-02 01:08:08 +00001703 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner08da4772009-04-25 08:35:12 +00001704 Constructor->setInvalidDecl();
Douglas Gregor605de8d2008-12-16 21:30:33 +00001705 }
1706 }
1707
1708 // Notify the class that we've added a constructor.
1709 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor605de8d2008-12-16 21:30:33 +00001710}
1711
Anders Carlssonfcfa2442009-04-30 23:18:11 +00001712static inline bool
1713FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
1714 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1715 FTI.ArgInfo[0].Param &&
1716 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
1717}
1718
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001719/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1720/// the well-formednes of the destructor declarator @p D with type @p
1721/// R. If there are any errors in the declarator, this routine will
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001722/// emit diagnostics and set the declarator to invalid. Even if this happens,
1723/// will be updated to reflect a well-formed type for the destructor and
1724/// returned.
1725QualType Sema::CheckDestructorDeclarator(Declarator &D,
1726 FunctionDecl::StorageClass& SC) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001727 // C++ [class.dtor]p1:
1728 // [...] A typedef-name that names a class is a class-name
1729 // (7.1.3); however, a typedef-name that names a class shall not
1730 // be used as the identifier in the declarator for a destructor
1731 // declaration.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001732 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001733 if (isa<TypedefType>(DeclaratorType)) {
1734 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregora60c62e2009-02-09 15:09:02 +00001735 << DeclaratorType;
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001736 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001737 }
1738
1739 // C++ [class.dtor]p2:
1740 // A destructor is used to destroy objects of its class type. A
1741 // destructor takes no parameters, and no return type can be
1742 // specified for it (not even void). The address of a destructor
1743 // shall not be taken. A destructor shall not be static. A
1744 // destructor can be invoked for a const, volatile or const
1745 // volatile object. A destructor shall not be declared const,
1746 // volatile or const volatile (9.3.2).
1747 if (SC == FunctionDecl::Static) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001748 if (!D.isInvalidType())
1749 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1750 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1751 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001752 SC = FunctionDecl::None;
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001753 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001754 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001755 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001756 // Destructors don't have return types, but the parser will
1757 // happily parse something like:
1758 //
1759 // class X {
1760 // float ~X();
1761 // };
1762 //
1763 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001764 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1765 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1766 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001767 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001768
1769 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1770 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001771 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001772 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1773 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001774 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001775 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1776 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001777 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001778 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1779 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001780 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001781 }
1782
1783 // Make sure we don't have any parameters.
Anders Carlssonfcfa2442009-04-30 23:18:11 +00001784 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001785 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1786
1787 // Delete the parameters.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001788 FTI.freeArgs();
1789 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001790 }
1791
1792 // Make sure the destructor isn't variadic.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001793 if (FTI.isVariadic) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001794 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001795 D.setInvalidType();
1796 }
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001797
1798 // Rebuild the function type "R" without any type qualifiers or
1799 // parameters (in case any of the errors above fired) and with
1800 // "void" as the return type, since destructors don't have return
1801 // types. We *always* have to do this, because GetTypeForDeclarator
1802 // will put in a result type of "int" when none was specified.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001803 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001804}
1805
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001806/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1807/// well-formednes of the conversion function declarator @p D with
1808/// type @p R. If there are any errors in the declarator, this routine
1809/// will emit diagnostics and return true. Otherwise, it will return
1810/// false. Either way, the type @p R will be updated to reflect a
1811/// well-formed type for the conversion operator.
Chris Lattner08da4772009-04-25 08:35:12 +00001812void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001813 FunctionDecl::StorageClass& SC) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001814 // C++ [class.conv.fct]p1:
1815 // Neither parameter types nor return type can be specified. The
Eli Friedmand5a72f02009-08-05 19:21:58 +00001816 // type of a conversion function (8.3.5) is "function taking no
1817 // parameter returning conversion-type-id."
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001818 if (SC == FunctionDecl::Static) {
Chris Lattner08da4772009-04-25 08:35:12 +00001819 if (!D.isInvalidType())
1820 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1821 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1822 << SourceRange(D.getIdentifierLoc());
1823 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001824 SC = FunctionDecl::None;
1825 }
Chris Lattner08da4772009-04-25 08:35:12 +00001826 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001827 // Conversion functions don't have return types, but the parser will
1828 // happily parse something like:
1829 //
1830 // class X {
1831 // float operator bool();
1832 // };
1833 //
1834 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001835 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1836 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1837 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001838 }
1839
1840 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001841 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001842 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1843
1844 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001845 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner08da4772009-04-25 08:35:12 +00001846 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001847 }
1848
1849 // Make sure the conversion function isn't variadic.
Chris Lattner08da4772009-04-25 08:35:12 +00001850 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001851 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner08da4772009-04-25 08:35:12 +00001852 D.setInvalidType();
1853 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001854
1855 // C++ [class.conv.fct]p4:
1856 // The conversion-type-id shall not represent a function type nor
1857 // an array type.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001858 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001859 if (ConvType->isArrayType()) {
1860 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1861 ConvType = Context.getPointerType(ConvType);
Chris Lattner08da4772009-04-25 08:35:12 +00001862 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001863 } else if (ConvType->isFunctionType()) {
1864 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1865 ConvType = Context.getPointerType(ConvType);
Chris Lattner08da4772009-04-25 08:35:12 +00001866 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001867 }
1868
1869 // Rebuild the function type "R" without any parameters (in case any
1870 // of the errors above fired) and with the conversion type as the
1871 // return type.
1872 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001873 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001874
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001875 // C++0x explicit conversion operators.
1876 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1877 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1878 diag::warn_explicit_conversion_functions)
1879 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001880}
1881
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001882/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1883/// the declaration of the given C++ conversion function. This routine
1884/// is responsible for recording the conversion function in the C++
1885/// class, if possible.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001886Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001887 assert(Conversion && "Expected to receive a conversion function declaration");
1888
Douglas Gregor98341042008-12-12 08:25:50 +00001889 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001890
1891 // Make sure we aren't redeclaring the conversion function.
1892 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001893
1894 // C++ [class.conv.fct]p1:
1895 // [...] A conversion function is never used to convert a
1896 // (possibly cv-qualified) object to the (possibly cv-qualified)
1897 // same object type (or a reference to it), to a (possibly
1898 // cv-qualified) base class of that type (or a reference to it),
1899 // or to (possibly cv-qualified) void.
Mike Stumpe127ae32009-05-16 07:39:55 +00001900 // FIXME: Suppress this warning if the conversion function ends up being a
1901 // virtual function that overrides a virtual function in a base class.
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001902 QualType ClassType
1903 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001904 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001905 ConvType = ConvTypeRef->getPointeeType();
1906 if (ConvType->isRecordType()) {
1907 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1908 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001909 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001910 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001911 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001912 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001913 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001914 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001915 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001916 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001917 }
1918
Douglas Gregor853dd392008-12-26 15:00:45 +00001919 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001920 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
1921 if (FunctionTemplateDecl *ConversionTemplate
1922 = Conversion->getDescribedFunctionTemplate())
1923 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor853dd392008-12-26 15:00:45 +00001924 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1925 for (OverloadedFunctionDecl::function_iterator
1926 Conv = Conversions->function_begin(),
1927 ConvEnd = Conversions->function_end();
1928 Conv != ConvEnd; ++Conv) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001929 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor853dd392008-12-26 15:00:45 +00001930 *Conv = Conversion;
Chris Lattner5261d0c2009-03-28 19:18:32 +00001931 return DeclPtrTy::make(Conversion);
Douglas Gregor853dd392008-12-26 15:00:45 +00001932 }
1933 }
1934 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Douglas Gregor8c860df2009-08-21 23:19:43 +00001935 } else if (FunctionTemplateDecl *ConversionTemplate
1936 = Conversion->getDescribedFunctionTemplate())
1937 ClassDecl->addConversionFunction(Context, ConversionTemplate);
1938 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Douglas Gregor853dd392008-12-26 15:00:45 +00001939 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001940
Chris Lattner5261d0c2009-03-28 19:18:32 +00001941 return DeclPtrTy::make(Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001942}
1943
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001944//===----------------------------------------------------------------------===//
1945// Namespace Handling
1946//===----------------------------------------------------------------------===//
1947
1948/// ActOnStartNamespaceDef - This is called at the start of a namespace
1949/// definition.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001950Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1951 SourceLocation IdentLoc,
1952 IdentifierInfo *II,
1953 SourceLocation LBrace) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001954 NamespaceDecl *Namespc =
1955 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1956 Namespc->setLBracLoc(LBrace);
1957
1958 Scope *DeclRegionScope = NamespcScope->getParent();
1959
1960 if (II) {
1961 // C++ [namespace.def]p2:
1962 // The identifier in an original-namespace-definition shall not have been
1963 // previously defined in the declarative region in which the
1964 // original-namespace-definition appears. The identifier in an
1965 // original-namespace-definition is the name of the namespace. Subsequently
1966 // in that declarative region, it is treated as an original-namespace-name.
1967
Douglas Gregor09be81b2009-02-04 17:27:36 +00001968 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1969 true);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001970
1971 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1972 // This is an extended namespace definition.
1973 // Attach this namespace decl to the chain of extended namespace
1974 // definitions.
1975 OrigNS->setNextNamespace(Namespc);
1976 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001977
Douglas Gregor8acb7272008-12-11 16:49:14 +00001978 // Remove the previous declaration from the scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001979 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor39677622008-12-11 20:41:00 +00001980 IdResolver.RemoveDecl(OrigNS);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001981 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001982 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001983 } else if (PrevDecl) {
1984 // This is an invalid name redefinition.
1985 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1986 << Namespc->getDeclName();
1987 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1988 Namespc->setInvalidDecl();
1989 // Continue on to push Namespc as current DeclContext and return it.
1990 }
1991
1992 PushOnScopeChains(Namespc, DeclRegionScope);
1993 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001994 // FIXME: Handle anonymous namespaces
1995 }
1996
1997 // Although we could have an invalid decl (i.e. the namespace name is a
1998 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stumpe127ae32009-05-16 07:39:55 +00001999 // FIXME: We should be able to push Namespc here, so that the each DeclContext
2000 // for the namespace has the declarations that showed up in that particular
2001 // namespace definition.
Douglas Gregor8acb7272008-12-11 16:49:14 +00002002 PushDeclContext(NamespcScope, Namespc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002003 return DeclPtrTy::make(Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002004}
2005
2006/// ActOnFinishNamespaceDef - This callback is called after a namespace is
2007/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002008void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
2009 Decl *Dcl = D.getAs<Decl>();
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002010 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
2011 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2012 Namespc->setRBracLoc(RBrace);
2013 PopDeclContext();
2014}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002015
Chris Lattner5261d0c2009-03-28 19:18:32 +00002016Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2017 SourceLocation UsingLoc,
2018 SourceLocation NamespcLoc,
2019 const CXXScopeSpec &SS,
2020 SourceLocation IdentLoc,
2021 IdentifierInfo *NamespcName,
2022 AttributeList *AttrList) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002023 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2024 assert(NamespcName && "Invalid NamespcName.");
2025 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor7a7be652009-02-03 19:21:40 +00002026 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002027
Douglas Gregor7a7be652009-02-03 19:21:40 +00002028 UsingDirectiveDecl *UDir = 0;
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002029
Douglas Gregor78d70132009-01-14 22:20:51 +00002030 // Lookup namespace name.
Douglas Gregor7a7be652009-02-03 19:21:40 +00002031 LookupResult R = LookupParsedName(S, &SS, NamespcName,
2032 LookupNamespaceName, false);
2033 if (R.isAmbiguous()) {
2034 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002035 return DeclPtrTy();
Douglas Gregor7a7be652009-02-03 19:21:40 +00002036 }
Douglas Gregor09be81b2009-02-04 17:27:36 +00002037 if (NamedDecl *NS = R) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002038 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor7a7be652009-02-03 19:21:40 +00002039 // C++ [namespace.udir]p1:
2040 // A using-directive specifies that the names in the nominated
2041 // namespace can be used in the scope in which the
2042 // using-directive appears after the using-directive. During
2043 // unqualified name lookup (3.4.1), the names appear as if they
2044 // were declared in the nearest enclosing namespace which
2045 // contains both the using-directive and the nominated
Eli Friedmand5a72f02009-08-05 19:21:58 +00002046 // namespace. [Note: in this context, "contains" means "contains
2047 // directly or indirectly". ]
Douglas Gregor7a7be652009-02-03 19:21:40 +00002048
2049 // Find enclosing context containing both using-directive and
2050 // nominated namespace.
2051 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2052 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2053 CommonAncestor = CommonAncestor->getParent();
2054
Douglas Gregor1d27d692009-05-30 06:31:56 +00002055 UDir = UsingDirectiveDecl::Create(Context,
2056 CurContext, UsingLoc,
2057 NamespcLoc,
2058 SS.getRange(),
2059 (NestedNameSpecifier *)SS.getScopeRep(),
2060 IdentLoc,
Douglas Gregor7a7be652009-02-03 19:21:40 +00002061 cast<NamespaceDecl>(NS),
2062 CommonAncestor);
2063 PushUsingDirective(S, UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002064 } else {
Chris Lattner954381a2009-01-06 07:24:29 +00002065 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002066 }
2067
Douglas Gregor7a7be652009-02-03 19:21:40 +00002068 // FIXME: We ignore attributes for now.
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002069 delete AttrList;
Chris Lattner5261d0c2009-03-28 19:18:32 +00002070 return DeclPtrTy::make(UDir);
Douglas Gregor7a7be652009-02-03 19:21:40 +00002071}
2072
2073void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2074 // If scope has associated entity, then using directive is at namespace
2075 // or translation unit scope. We add UsingDirectiveDecls, into
2076 // it's lookup structure.
2077 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002078 Ctx->addDecl(UDir);
Douglas Gregor7a7be652009-02-03 19:21:40 +00002079 else
2080 // Otherwise it is block-sope. using-directives will affect lookup
2081 // only to the end of scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002082 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002083}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002084
Douglas Gregor683a1142009-06-20 00:51:54 +00002085
2086Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
2087 SourceLocation UsingLoc,
2088 const CXXScopeSpec &SS,
2089 SourceLocation IdentLoc,
2090 IdentifierInfo *TargetName,
Anders Carlssone8c36f22009-06-27 00:27:47 +00002091 OverloadedOperatorKind Op,
Douglas Gregor683a1142009-06-20 00:51:54 +00002092 AttributeList *AttrList,
2093 bool IsTypeName) {
2094 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Eli Friedmana73d6b12009-06-27 05:59:59 +00002095 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor683a1142009-06-20 00:51:54 +00002096 assert(IdentLoc.isValid() && "Invalid TargetName location.");
2097 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2098
2099 UsingDecl *UsingAlias = 0;
2100
Anders Carlssone8c36f22009-06-27 00:27:47 +00002101 DeclarationName Name;
2102 if (TargetName)
2103 Name = TargetName;
2104 else
2105 Name = Context.DeclarationNames.getCXXOperatorName(Op);
Eli Friedmanb30f1c82009-08-27 05:09:36 +00002106
2107 // FIXME: Implement this properly!
2108 if (isUnknownSpecialization(SS)) {
2109 Diag(IdentLoc, diag::err_using_dependent_unsupported);
2110 delete AttrList;
2111 return DeclPtrTy::make((UsingDecl*)0);
2112 }
2113
Douglas Gregor683a1142009-06-20 00:51:54 +00002114 // Lookup target name.
Anders Carlssone8c36f22009-06-27 00:27:47 +00002115 LookupResult R = LookupParsedName(S, &SS, Name, LookupOrdinaryName, false);
Douglas Gregor683a1142009-06-20 00:51:54 +00002116
2117 if (NamedDecl *NS = R) {
2118 if (IsTypeName && !isa<TypeDecl>(NS)) {
2119 Diag(IdentLoc, diag::err_using_typename_non_type);
2120 }
2121 UsingAlias = UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2122 NS->getLocation(), UsingLoc, NS,
2123 static_cast<NestedNameSpecifier *>(SS.getScopeRep()),
2124 IsTypeName);
2125 PushOnScopeChains(UsingAlias, S);
2126 } else {
2127 Diag(IdentLoc, diag::err_using_requires_qualname) << SS.getRange();
2128 }
2129
2130 // FIXME: We ignore attributes for now.
2131 delete AttrList;
2132 return DeclPtrTy::make(UsingAlias);
2133}
2134
Anders Carlsson7c1c5482009-03-28 23:53:49 +00002135/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2136/// is a namespace alias, returns the namespace it points to.
2137static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2138 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2139 return AD->getNamespace();
2140 return dyn_cast_or_null<NamespaceDecl>(D);
2141}
2142
Chris Lattner5261d0c2009-03-28 19:18:32 +00002143Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson26de7882009-03-28 22:53:22 +00002144 SourceLocation NamespaceLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +00002145 SourceLocation AliasLoc,
2146 IdentifierInfo *Alias,
2147 const CXXScopeSpec &SS,
Anders Carlsson26de7882009-03-28 22:53:22 +00002148 SourceLocation IdentLoc,
2149 IdentifierInfo *Ident) {
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002150
Anders Carlsson7c1c5482009-03-28 23:53:49 +00002151 // Lookup the namespace name.
2152 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2153
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002154 // Check if we have a previous declaration with the same name.
Anders Carlsson1cd05f52009-03-28 23:49:35 +00002155 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson7c1c5482009-03-28 23:53:49 +00002156 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
2157 // We already have an alias with the same name that points to the same
2158 // namespace, so don't create a new one.
2159 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2160 return DeclPtrTy();
2161 }
2162
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002163 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2164 diag::err_redefinition_different_kind;
2165 Diag(AliasLoc, DiagID) << Alias;
2166 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002167 return DeclPtrTy();
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002168 }
2169
Anders Carlsson279ebc42009-03-28 06:42:02 +00002170 if (R.isAmbiguous()) {
Anders Carlsson26de7882009-03-28 22:53:22 +00002171 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002172 return DeclPtrTy();
Anders Carlsson279ebc42009-03-28 06:42:02 +00002173 }
2174
2175 if (!R) {
2176 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner5261d0c2009-03-28 19:18:32 +00002177 return DeclPtrTy();
Anders Carlsson279ebc42009-03-28 06:42:02 +00002178 }
2179
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002180 NamespaceAliasDecl *AliasDecl =
Douglas Gregor8d8ddca2009-05-30 06:48:27 +00002181 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2182 Alias, SS.getRange(),
2183 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlssonddb1d8b2009-03-28 22:58:02 +00002184 IdentLoc, R);
2185
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002186 CurContext->addDecl(AliasDecl);
Anders Carlssonddb1d8b2009-03-28 22:58:02 +00002187 return DeclPtrTy::make(AliasDecl);
Anders Carlsson8cffcd62009-03-28 05:27:17 +00002188}
2189
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002190void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2191 CXXConstructorDecl *Constructor) {
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00002192 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2193 !Constructor->isUsed()) &&
2194 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002195
2196 CXXRecordDecl *ClassDecl
2197 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002198 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002199 // Before the implicitly-declared default constructor for a class is
2200 // implicitly defined, all the implicitly-declared default constructors
2201 // for its base class and its non-static data members shall have been
2202 // implicitly defined.
2203 bool err = false;
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002204 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2205 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002206 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002207 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002208 if (!BaseClassDecl->hasTrivialConstructor()) {
2209 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002210 BaseClassDecl->getDefaultConstructor(Context))
2211 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002212 else {
2213 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian16443602009-06-20 20:23:38 +00002214 << Context.getTagDeclType(ClassDecl) << 1
2215 << Context.getTagDeclType(BaseClassDecl);
2216 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
2217 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002218 err = true;
2219 }
2220 }
2221 }
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002222 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2223 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002224 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2225 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2226 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002227 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002228 CXXRecordDecl *FieldClassDecl
2229 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands78146712009-06-25 09:03:06 +00002230 if (!FieldClassDecl->hasTrivialConstructor()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002231 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002232 FieldClassDecl->getDefaultConstructor(Context))
2233 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002234 else {
2235 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian16443602009-06-20 20:23:38 +00002236 << Context.getTagDeclType(ClassDecl) << 0 <<
2237 Context.getTagDeclType(FieldClassDecl);
2238 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
2239 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002240 err = true;
2241 }
2242 }
Mike Stump90fc78e2009-08-04 21:02:39 +00002243 } else if (FieldType->isReferenceType()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002244 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson6a661262009-07-09 17:37:12 +00002245 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002246 Diag((*Field)->getLocation(), diag::note_declared_at);
2247 err = true;
Mike Stump90fc78e2009-08-04 21:02:39 +00002248 } else if (FieldType.isConstQualified()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002249 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson6a661262009-07-09 17:37:12 +00002250 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002251 Diag((*Field)->getLocation(), diag::note_declared_at);
2252 err = true;
2253 }
2254 }
2255 if (!err)
Fariborz Jahanian2c313fb2009-06-26 16:08:57 +00002256 Constructor->setUsed();
2257 else
2258 Constructor->setInvalidDecl();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002259}
2260
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002261void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
2262 CXXDestructorDecl *Destructor) {
2263 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2264 "DefineImplicitDestructor - call it for implicit default dtor");
2265
2266 CXXRecordDecl *ClassDecl
2267 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2268 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2269 // C++ [class.dtor] p5
2270 // Before the implicitly-declared default destructor for a class is
2271 // implicitly defined, all the implicitly-declared default destructors
2272 // for its base class and its non-static data members shall have been
2273 // implicitly defined.
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002274 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2275 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002276 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002277 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002278 if (!BaseClassDecl->hasTrivialDestructor()) {
2279 if (CXXDestructorDecl *BaseDtor =
2280 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2281 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2282 else
2283 assert(false &&
2284 "DefineImplicitDestructor - missing dtor in a base class");
2285 }
2286 }
2287
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002288 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2289 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002290 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2291 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2292 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002293 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002294 CXXRecordDecl *FieldClassDecl
2295 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2296 if (!FieldClassDecl->hasTrivialDestructor()) {
2297 if (CXXDestructorDecl *FieldDtor =
2298 const_cast<CXXDestructorDecl*>(
2299 FieldClassDecl->getDestructor(Context)))
2300 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2301 else
2302 assert(false &&
2303 "DefineImplicitDestructor - missing dtor in class of a data member");
2304 }
2305 }
2306 }
2307 Destructor->setUsed();
2308}
2309
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002310void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2311 CXXMethodDecl *MethodDecl) {
2312 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2313 MethodDecl->getOverloadedOperator() == OO_Equal &&
2314 !MethodDecl->isUsed()) &&
2315 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
2316
2317 CXXRecordDecl *ClassDecl
2318 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002319
Fariborz Jahanian2c313fb2009-06-26 16:08:57 +00002320 // C++[class.copy] p12
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002321 // Before the implicitly-declared copy assignment operator for a class is
2322 // implicitly defined, all implicitly-declared copy assignment operators
2323 // for its direct base classes and its nonstatic data members shall have
2324 // been implicitly defined.
2325 bool err = false;
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002326 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2327 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002328 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002329 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002330 if (CXXMethodDecl *BaseAssignOpMethod =
2331 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2332 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2333 }
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002334 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2335 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002336 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2337 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2338 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002339 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002340 CXXRecordDecl *FieldClassDecl
2341 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2342 if (CXXMethodDecl *FieldAssignOpMethod =
2343 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2344 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump90fc78e2009-08-04 21:02:39 +00002345 } else if (FieldType->isReferenceType()) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002346 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson1c0c52c2009-07-09 17:47:25 +00002347 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2348 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002349 Diag(CurrentLocation, diag::note_first_required_here);
2350 err = true;
Mike Stump90fc78e2009-08-04 21:02:39 +00002351 } else if (FieldType.isConstQualified()) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002352 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson1c0c52c2009-07-09 17:47:25 +00002353 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2354 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002355 Diag(CurrentLocation, diag::note_first_required_here);
2356 err = true;
2357 }
2358 }
2359 if (!err)
2360 MethodDecl->setUsed();
2361}
2362
2363CXXMethodDecl *
2364Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2365 CXXRecordDecl *ClassDecl) {
2366 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2367 QualType RHSType(LHSType);
2368 // If class's assignment operator argument is const/volatile qualified,
2369 // look for operator = (const/volatile B&). Otherwise, look for
2370 // operator = (B&).
2371 if (ParmDecl->getType().isConstQualified())
2372 RHSType.addConst();
2373 if (ParmDecl->getType().isVolatileQualified())
2374 RHSType.addVolatile();
2375 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2376 LHSType,
2377 SourceLocation()));
2378 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2379 RHSType,
2380 SourceLocation()));
2381 Expr *Args[2] = { &*LHS, &*RHS };
2382 OverloadCandidateSet CandidateSet;
2383 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
2384 CandidateSet);
2385 OverloadCandidateSet::iterator Best;
2386 if (BestViableFunction(CandidateSet,
2387 ClassDecl->getLocation(), Best) == OR_Success)
2388 return cast<CXXMethodDecl>(Best->Function);
2389 assert(false &&
2390 "getAssignOperatorMethod - copy assignment operator method not found");
2391 return 0;
2392}
2393
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002394void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2395 CXXConstructorDecl *CopyConstructor,
2396 unsigned TypeQuals) {
2397 assert((CopyConstructor->isImplicit() &&
2398 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2399 !CopyConstructor->isUsed()) &&
2400 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
2401
2402 CXXRecordDecl *ClassDecl
2403 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2404 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002405 // C++ [class.copy] p209
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002406 // Before the implicitly-declared copy constructor for a class is
2407 // implicitly defined, all the implicitly-declared copy constructors
2408 // for its base class and its non-static data members shall have been
2409 // implicitly defined.
2410 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2411 Base != ClassDecl->bases_end(); ++Base) {
2412 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002413 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002414 if (CXXConstructorDecl *BaseCopyCtor =
2415 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002416 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002417 }
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002418 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2419 FieldEnd = ClassDecl->field_end();
2420 Field != FieldEnd; ++Field) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002421 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2422 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2423 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002424 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002425 CXXRecordDecl *FieldClassDecl
2426 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2427 if (CXXConstructorDecl *FieldCopyCtor =
2428 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002429 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002430 }
2431 }
2432 CopyConstructor->setUsed();
2433}
2434
Anders Carlsson665e4692009-08-25 05:12:04 +00002435Sema::OwningExprResult
2436Sema::BuildCXXConstructExpr(QualType DeclInitType,
2437 CXXConstructorDecl *Constructor,
2438 Expr **Exprs, unsigned NumExprs) {
Anders Carlssonbd9f51a2009-08-16 05:13:48 +00002439 bool Elidable = false;
2440
2441 // [class.copy]p15:
2442 // Whenever a temporary class object is copied using a copy constructor, and
2443 // this object and the copy have the same cv-unqualified type, an
2444 // implementation is permitted to treat the original and the copy as two
2445 // different ways of referring to the same object and not perform a copy at
2446 //all, even if the class copy constructor or destructor have side effects.
2447
2448 // FIXME: Is this enough?
2449 if (Constructor->isCopyConstructor(Context) && NumExprs == 1) {
2450 Expr *E = Exprs[0];
2451 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2452 E = BE->getSubExpr();
2453
2454 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2455 Elidable = true;
2456 }
2457
2458 return BuildCXXConstructExpr(DeclInitType, Constructor, Elidable,
2459 Exprs, NumExprs);
2460}
2461
Fariborz Jahanian1c30f262009-08-05 17:03:54 +00002462/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2463/// including handling of its default argument expressions.
Anders Carlsson665e4692009-08-25 05:12:04 +00002464Sema::OwningExprResult
2465Sema::BuildCXXConstructExpr(QualType DeclInitType,
2466 CXXConstructorDecl *Constructor,
2467 bool Elidable,
2468 Expr **Exprs,
2469 unsigned NumExprs) {
Anders Carlsson3e03d832009-08-25 13:07:08 +00002470 ExprOwningPtr<CXXConstructExpr> Temp(this,
2471 CXXConstructExpr::Create(Context,
2472 DeclInitType,
2473 Constructor,
2474 Elidable,
2475 Exprs,
2476 NumExprs));
Anders Carlssonef8fd082009-08-27 05:08:22 +00002477 // Default arguments must be added to constructor call expression.
Fariborz Jahanianbeb68c42009-08-05 00:26:10 +00002478 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor);
2479 unsigned NumArgsInProto = FDecl->param_size();
2480 for (unsigned j = NumExprs; j != NumArgsInProto; j++) {
Anders Carlsson3e03d832009-08-25 13:07:08 +00002481 ParmVarDecl *Param = FDecl->getParamDecl(j);
2482
2483 OwningExprResult ArgExpr =
2484 BuildCXXDefaultArgExpr(/*FIXME:*/SourceLocation(),
2485 FDecl, Param);
2486 if (ArgExpr.isInvalid())
2487 return ExprError();
2488
2489 Temp->setArg(j, ArgExpr.takeAs<Expr>());
Fariborz Jahanianbeb68c42009-08-05 00:26:10 +00002490 }
Anders Carlsson3e03d832009-08-25 13:07:08 +00002491 return move(Temp);
Fariborz Jahanian1c30f262009-08-05 17:03:54 +00002492}
2493
Anders Carlssonef8fd082009-08-27 05:08:22 +00002494Sema::OwningExprResult
2495Sema::BuildCXXTemporaryObjectExpr(CXXConstructorDecl *Constructor,
2496 QualType Ty,
2497 SourceLocation TyBeginLoc,
2498 MultiExprArg Args,
2499 SourceLocation RParenLoc) {
2500 CXXTemporaryObjectExpr *E
2501 = new (Context) CXXTemporaryObjectExpr(Context, Constructor, Ty, TyBeginLoc,
2502 (Expr **)Args.get(),
2503 Args.size(), RParenLoc);
2504
2505 ExprOwningPtr<CXXTemporaryObjectExpr> Temp(this, E);
2506
2507 // Default arguments must be added to constructor call expression.
2508 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor);
2509 unsigned NumArgsInProto = FDecl->param_size();
2510 for (unsigned j = Args.size(); j != NumArgsInProto; j++) {
2511 ParmVarDecl *Param = FDecl->getParamDecl(j);
2512
2513 OwningExprResult ArgExpr = BuildCXXDefaultArgExpr(TyBeginLoc, FDecl, Param);
2514 if (ArgExpr.isInvalid())
2515 return ExprError();
2516
2517 Temp->setArg(j, ArgExpr.takeAs<Expr>());
2518 }
2519
2520 Args.release();
2521 return move(Temp);
2522}
2523
2524
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002525bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanian1c30f262009-08-05 17:03:54 +00002526 CXXConstructorDecl *Constructor,
2527 QualType DeclInitType,
2528 Expr **Exprs, unsigned NumExprs) {
Anders Carlsson665e4692009-08-25 05:12:04 +00002529 OwningExprResult TempResult = BuildCXXConstructExpr(DeclInitType, Constructor,
2530 Exprs, NumExprs);
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002531 if (TempResult.isInvalid())
2532 return true;
Anders Carlsson665e4692009-08-25 05:12:04 +00002533
2534 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregorcad27f62009-06-22 23:06:13 +00002535 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahanian88e09cc2009-08-05 18:17:32 +00002536 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor4833ff02009-05-26 18:54:04 +00002537 VD->setInit(Context, Temp);
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002538
2539 return false;
Anders Carlsson05e59652009-04-16 23:50:50 +00002540}
2541
Fariborz Jahaniancd208112009-08-03 19:13:25 +00002542void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType)
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002543{
2544 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002545 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002546 if (!ClassDecl->hasTrivialDestructor())
2547 if (CXXDestructorDecl *Destructor =
2548 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniancd208112009-08-03 19:13:25 +00002549 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002550}
2551
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002552/// AddCXXDirectInitializerToDecl - This action is called immediately after
2553/// ActOnDeclarator, when a C++ direct initializer is present.
2554/// e.g: "int x(1);"
Chris Lattner5261d0c2009-03-28 19:18:32 +00002555void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2556 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002557 MultiExprArg Exprs,
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002558 SourceLocation *CommaLocs,
2559 SourceLocation RParenLoc) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002560 unsigned NumExprs = Exprs.size();
2561 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner5261d0c2009-03-28 19:18:32 +00002562 Decl *RealDecl = Dcl.getAs<Decl>();
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002563
2564 // If there is no declaration, there was an error parsing it. Just ignore
2565 // the initializer.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002566 if (RealDecl == 0)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002567 return;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002568
2569 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2570 if (!VDecl) {
2571 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2572 RealDecl->setInvalidDecl();
2573 return;
2574 }
2575
Douglas Gregor52be1ca2009-08-26 21:14:46 +00002576 // We will represent direct-initialization similarly to copy-initialization:
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002577 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002578 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2579 //
2580 // Clients that want to distinguish between the two forms, can check for
2581 // direct initializer using VarDecl::hasCXXDirectInitializer().
2582 // A major benefit is that clients that don't particularly care about which
2583 // exactly form was it (like the CodeGen) can handle both cases without
2584 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002585
Douglas Gregor52be1ca2009-08-26 21:14:46 +00002586 // If either the declaration has a dependent type or if any of the expressions
2587 // is type-dependent, we represent the initialization via a ParenListExpr for
2588 // later use during template instantiation.
2589 if (VDecl->getType()->isDependentType() ||
2590 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
2591 // Let clients know that initialization was done with a direct initializer.
2592 VDecl->setCXXDirectInitializer(true);
2593
2594 // Store the initialization expressions as a ParenListExpr.
2595 unsigned NumExprs = Exprs.size();
2596 VDecl->setInit(Context,
2597 new (Context) ParenListExpr(Context, LParenLoc,
2598 (Expr **)Exprs.release(),
2599 NumExprs, RParenLoc));
2600 return;
2601 }
2602
2603
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002604 // C++ 8.5p11:
2605 // The form of initialization (using parentheses or '=') is generally
2606 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002607 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00002608 QualType DeclInitType = VDecl->getType();
2609 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
2610 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002611
Douglas Gregorad7d1812009-03-24 16:43:20 +00002612 // FIXME: This isn't the right place to complete the type.
2613 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2614 diag::err_typecheck_decl_incomplete_type)) {
2615 VDecl->setInvalidDecl();
2616 return;
2617 }
2618
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002619 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00002620 CXXConstructorDecl *Constructor
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002621 = PerformInitializationByConstructor(DeclInitType,
2622 (Expr **)Exprs.get(), NumExprs,
Douglas Gregor6428e762008-11-05 15:29:30 +00002623 VDecl->getLocation(),
2624 SourceRange(VDecl->getLocation(),
2625 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00002626 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002627 IK_Direct);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002628 if (!Constructor)
Douglas Gregor5870a952008-11-03 20:45:27 +00002629 RealDecl->setInvalidDecl();
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002630 else {
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002631 VDecl->setCXXDirectInitializer(true);
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002632 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
2633 (Expr**)Exprs.release(), NumExprs))
2634 RealDecl->setInvalidDecl();
Fariborz Jahaniancd208112009-08-03 19:13:25 +00002635 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002636 }
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002637 return;
2638 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002639
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002640 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002641 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
2642 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002643 RealDecl->setInvalidDecl();
2644 return;
2645 }
2646
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002647 // Let clients know that initialization was done with a direct initializer.
2648 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002649
2650 assert(NumExprs == 1 && "Expected 1 expression");
2651 // Set the init expression, handles conversions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002652 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
2653 /*DirectInit=*/true);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002654}
Douglas Gregor81c29152008-10-29 00:13:59 +00002655
Douglas Gregor6428e762008-11-05 15:29:30 +00002656/// PerformInitializationByConstructor - Perform initialization by
2657/// constructor (C++ [dcl.init]p14), which may occur as part of
2658/// direct-initialization or copy-initialization. We are initializing
2659/// an object of type @p ClassType with the given arguments @p
2660/// Args. @p Loc is the location in the source code where the
2661/// initializer occurs (e.g., a declaration, member initializer,
2662/// functional cast, etc.) while @p Range covers the whole
2663/// initialization. @p InitEntity is the entity being initialized,
2664/// which may by the name of a declaration or a type. @p Kind is the
2665/// kind of initialization we're performing, which affects whether
2666/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00002667/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00002668/// when the initialization fails, emits a diagnostic and returns
2669/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00002670CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00002671Sema::PerformInitializationByConstructor(QualType ClassType,
2672 Expr **Args, unsigned NumArgs,
2673 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00002674 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00002675 InitializationKind Kind) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002676 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor5870a952008-11-03 20:45:27 +00002677 assert(ClassRec && "Can only initialize a class type here");
2678
2679 // C++ [dcl.init]p14:
2680 //
2681 // If the initialization is direct-initialization, or if it is
2682 // copy-initialization where the cv-unqualified version of the
2683 // source type is the same class as, or a derived class of, the
2684 // class of the destination, constructors are considered. The
2685 // applicable constructors are enumerated (13.3.1.3), and the
2686 // best one is chosen through overload resolution (13.3). The
2687 // constructor so selected is called to initialize the object,
2688 // with the initializer expression(s) as its argument(s). If no
2689 // constructor applies, or the overload resolution is ambiguous,
2690 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00002691 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
2692 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00002693
2694 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00002695 DeclarationName ConstructorName
2696 = Context.DeclarationNames.getCXXConstructorName(
2697 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002698 DeclContext::lookup_const_iterator Con, ConEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002699 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002700 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00002701 // Find the constructor (which may be a template).
2702 CXXConstructorDecl *Constructor = 0;
2703 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
2704 if (ConstructorTmpl)
2705 Constructor
2706 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2707 else
2708 Constructor = cast<CXXConstructorDecl>(*Con);
2709
Douglas Gregor6428e762008-11-05 15:29:30 +00002710 if ((Kind == IK_Direct) ||
2711 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
Douglas Gregor050cabf2009-08-21 18:42:58 +00002712 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
2713 if (ConstructorTmpl)
2714 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
2715 Args, NumArgs, CandidateSet);
2716 else
2717 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2718 }
Douglas Gregor6428e762008-11-05 15:29:30 +00002719 }
2720
Douglas Gregorb9213832008-12-15 21:24:18 +00002721 // FIXME: When we decide not to synthesize the implicitly-declared
2722 // constructors, we'll need to make them appear here.
2723
Douglas Gregor5870a952008-11-03 20:45:27 +00002724 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00002725 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor5870a952008-11-03 20:45:27 +00002726 case OR_Success:
2727 // We found a constructor. Return it.
2728 return cast<CXXConstructorDecl>(Best->Function);
2729
2730 case OR_No_Viable_Function:
Douglas Gregor538a4c22009-02-02 17:43:21 +00002731 if (InitEntity)
2732 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00002733 << InitEntity << Range;
Douglas Gregor538a4c22009-02-02 17:43:21 +00002734 else
2735 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00002736 << ClassType << Range;
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00002737 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00002738 return 0;
2739
2740 case OR_Ambiguous:
Douglas Gregor538a4c22009-02-02 17:43:21 +00002741 if (InitEntity)
2742 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
2743 else
2744 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00002745 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2746 return 0;
Douglas Gregoraa57e862009-02-18 21:56:37 +00002747
2748 case OR_Deleted:
2749 if (InitEntity)
2750 Diag(Loc, diag::err_ovl_deleted_init)
2751 << Best->Function->isDeleted()
2752 << InitEntity << Range;
2753 else
2754 Diag(Loc, diag::err_ovl_deleted_init)
2755 << Best->Function->isDeleted()
2756 << InitEntity << Range;
2757 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2758 return 0;
Douglas Gregor5870a952008-11-03 20:45:27 +00002759 }
2760
2761 return 0;
2762}
2763
Douglas Gregor81c29152008-10-29 00:13:59 +00002764/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2765/// determine whether they are reference-related,
2766/// reference-compatible, reference-compatible with added
2767/// qualification, or incompatible, for use in C++ initialization by
2768/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2769/// type, and the first type (T1) is the pointee type of the reference
2770/// type being initialized.
2771Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002772Sema::CompareReferenceRelationship(QualType T1, QualType T2,
2773 bool& DerivedToBase) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002774 assert(!T1->isReferenceType() &&
2775 "T1 must be the pointee type of the reference type");
Douglas Gregor81c29152008-10-29 00:13:59 +00002776 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
2777
2778 T1 = Context.getCanonicalType(T1);
2779 T2 = Context.getCanonicalType(T2);
2780 QualType UnqualT1 = T1.getUnqualifiedType();
2781 QualType UnqualT2 = T2.getUnqualifiedType();
2782
2783 // C++ [dcl.init.ref]p4:
Eli Friedmand5a72f02009-08-05 19:21:58 +00002784 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2785 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor81c29152008-10-29 00:13:59 +00002786 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002787 if (UnqualT1 == UnqualT2)
2788 DerivedToBase = false;
2789 else if (IsDerivedFrom(UnqualT2, UnqualT1))
2790 DerivedToBase = true;
2791 else
Douglas Gregor81c29152008-10-29 00:13:59 +00002792 return Ref_Incompatible;
2793
2794 // At this point, we know that T1 and T2 are reference-related (at
2795 // least).
2796
2797 // C++ [dcl.init.ref]p4:
Eli Friedmand5a72f02009-08-05 19:21:58 +00002798 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor81c29152008-10-29 00:13:59 +00002799 // reference-related to T2 and cv1 is the same cv-qualification
2800 // as, or greater cv-qualification than, cv2. For purposes of
2801 // overload resolution, cases for which cv1 is greater
2802 // cv-qualification than cv2 are identified as
2803 // reference-compatible with added qualification (see 13.3.3.2).
2804 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2805 return Ref_Compatible;
2806 else if (T1.isMoreQualifiedThan(T2))
2807 return Ref_Compatible_With_Added_Qualification;
2808 else
2809 return Ref_Related;
2810}
2811
2812/// CheckReferenceInit - Check the initialization of a reference
2813/// variable with the given initializer (C++ [dcl.init.ref]). Init is
2814/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00002815/// list), and DeclType is the type of the declaration. When ICS is
2816/// non-null, this routine will compute the implicit conversion
2817/// sequence according to C++ [over.ics.ref] and will not produce any
2818/// diagnostics; when ICS is null, it will emit diagnostics when any
2819/// errors are found. Either way, a return value of true indicates
2820/// that there was a failure, a return value of false indicates that
2821/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002822///
2823/// When @p SuppressUserConversions, user-defined conversions are
2824/// suppressed.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002825/// When @p AllowExplicit, we also permit explicit user-defined
2826/// conversion functions.
Sebastian Redla55834a2009-04-12 17:16:29 +00002827/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002828bool
Sebastian Redlbd261962009-04-16 17:51:27 +00002829Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002830 ImplicitConversionSequence *ICS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002831 bool SuppressUserConversions,
Sebastian Redla55834a2009-04-12 17:16:29 +00002832 bool AllowExplicit, bool ForceRValue) {
Douglas Gregor81c29152008-10-29 00:13:59 +00002833 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2834
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002835 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor81c29152008-10-29 00:13:59 +00002836 QualType T2 = Init->getType();
2837
Douglas Gregor45014fd2008-11-10 20:40:00 +00002838 // If the initializer is the address of an overloaded function, try
2839 // to resolve the overloaded function. If all goes well, T2 is the
2840 // type of the resulting function.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002841 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00002842 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
2843 ICS != 0);
2844 if (Fn) {
2845 // Since we're performing this reference-initialization for
2846 // real, update the initializer with the resulting function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00002847 if (!ICS) {
2848 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
2849 return true;
2850
Douglas Gregor45014fd2008-11-10 20:40:00 +00002851 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregoraa57e862009-02-18 21:56:37 +00002852 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002853
2854 T2 = Fn->getType();
2855 }
2856 }
2857
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002858 // Compute some basic properties of the types and the initializer.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002859 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002860 bool DerivedToBase = false;
Sebastian Redla55834a2009-04-12 17:16:29 +00002861 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2862 Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002863 ReferenceCompareResult RefRelationship
2864 = CompareReferenceRelationship(T1, T2, DerivedToBase);
2865
2866 // Most paths end in a failed conversion.
2867 if (ICS)
2868 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00002869
2870 // C++ [dcl.init.ref]p5:
Eli Friedmand5a72f02009-08-05 19:21:58 +00002871 // A reference to type "cv1 T1" is initialized by an expression
2872 // of type "cv2 T2" as follows:
Douglas Gregor81c29152008-10-29 00:13:59 +00002873
2874 // -- If the initializer expression
2875
Sebastian Redldfc30332009-03-29 15:27:50 +00002876 // Rvalue references cannot bind to lvalues (N2812).
2877 // There is absolutely no situation where they can. In particular, note that
2878 // this is ill-formed, even if B has a user-defined conversion to A&&:
2879 // B b;
2880 // A&& r = b;
2881 if (isRValRef && InitLvalue == Expr::LV_Valid) {
2882 if (!ICS)
2883 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
2884 << Init->getSourceRange();
2885 return true;
2886 }
2887
Douglas Gregor81c29152008-10-29 00:13:59 +00002888 bool BindsDirectly = false;
Eli Friedmand5a72f02009-08-05 19:21:58 +00002889 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2890 // reference-compatible with "cv2 T2," or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002891 //
2892 // Note that the bit-field check is skipped if we are just computing
2893 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor531434b2009-05-02 02:18:30 +00002894 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002895 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00002896 BindsDirectly = true;
2897
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002898 if (ICS) {
2899 // C++ [over.ics.ref]p1:
2900 // When a parameter of reference type binds directly (8.5.3)
2901 // to an argument expression, the implicit conversion sequence
2902 // is the identity conversion, unless the argument expression
2903 // has a type that is a derived class of the parameter type,
2904 // in which case the implicit conversion sequence is a
2905 // derived-to-base Conversion (13.3.3.1).
2906 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2907 ICS->Standard.First = ICK_Identity;
2908 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2909 ICS->Standard.Third = ICK_Identity;
2910 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2911 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00002912 ICS->Standard.ReferenceBinding = true;
2913 ICS->Standard.DirectBinding = true;
Sebastian Redldfc30332009-03-29 15:27:50 +00002914 ICS->Standard.RRefBinding = false;
Sebastian Redld3169132009-04-17 16:30:52 +00002915 ICS->Standard.CopyConstructor = 0;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002916
2917 // Nothing more to do: the inaccessibility/ambiguity check for
2918 // derived-to-base conversions is suppressed when we're
2919 // computing the implicit conversion sequence (C++
2920 // [over.best.ics]p2).
2921 return false;
2922 } else {
2923 // Perform the conversion.
Mike Stumpe127ae32009-05-16 07:39:55 +00002924 // FIXME: Binding to a subobject of the lvalue is going to require more
2925 // AST annotation than this.
Anders Carlsson85186942009-07-31 01:23:52 +00002926 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00002927 }
2928 }
2929
2930 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedmand5a72f02009-08-05 19:21:58 +00002931 // implicitly converted to an lvalue of type "cv3 T3,"
2932 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor81c29152008-10-29 00:13:59 +00002933 // 92) (this conversion is selected by enumerating the
2934 // applicable conversion functions (13.3.1.6) and choosing
2935 // the best one through overload resolution (13.3)),
Douglas Gregorb35c7992009-08-24 15:23:48 +00002936 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2937 !RequireCompleteType(SourceLocation(), T2, 0)) {
Douglas Gregore6985fe2008-11-10 16:14:15 +00002938 // FIXME: Look for conversions in base classes!
2939 CXXRecordDecl *T2RecordDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002940 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00002941
Douglas Gregore6985fe2008-11-10 16:14:15 +00002942 OverloadCandidateSet CandidateSet;
2943 OverloadedFunctionDecl *Conversions
2944 = T2RecordDecl->getConversionFunctions();
2945 for (OverloadedFunctionDecl::function_iterator Func
2946 = Conversions->function_begin();
2947 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002948 FunctionTemplateDecl *ConvTemplate
2949 = dyn_cast<FunctionTemplateDecl>(*Func);
2950 CXXConversionDecl *Conv;
2951 if (ConvTemplate)
2952 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2953 else
2954 Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redl16ac38f2009-03-22 21:28:55 +00002955
Douglas Gregore6985fe2008-11-10 16:14:15 +00002956 // If the conversion function doesn't return a reference type,
2957 // it can't be considered for this conversion.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002958 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor8c860df2009-08-21 23:19:43 +00002959 (AllowExplicit || !Conv->isExplicit())) {
2960 if (ConvTemplate)
2961 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
2962 CandidateSet);
2963 else
2964 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
2965 }
Douglas Gregore6985fe2008-11-10 16:14:15 +00002966 }
2967
2968 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00002969 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregore6985fe2008-11-10 16:14:15 +00002970 case OR_Success:
2971 // This is a direct binding.
2972 BindsDirectly = true;
2973
2974 if (ICS) {
2975 // C++ [over.ics.ref]p1:
2976 //
2977 // [...] If the parameter binds directly to the result of
2978 // applying a conversion function to the argument
2979 // expression, the implicit conversion sequence is a
2980 // user-defined conversion sequence (13.3.3.1.2), with the
2981 // second standard conversion sequence either an identity
2982 // conversion or, if the conversion function returns an
2983 // entity of a type that is a derived class of the parameter
2984 // type, a derived-to-base Conversion.
2985 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
2986 ICS->UserDefined.Before = Best->Conversions[0].Standard;
2987 ICS->UserDefined.After = Best->FinalConversion;
2988 ICS->UserDefined.ConversionFunction = Best->Function;
2989 assert(ICS->UserDefined.After.ReferenceBinding &&
2990 ICS->UserDefined.After.DirectBinding &&
2991 "Expected a direct reference binding!");
2992 return false;
2993 } else {
2994 // Perform the conversion.
Mike Stumpe127ae32009-05-16 07:39:55 +00002995 // FIXME: Binding to a subobject of the lvalue is going to require more
2996 // AST annotation than this.
Anders Carlsson85186942009-07-31 01:23:52 +00002997 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00002998 }
2999 break;
3000
3001 case OR_Ambiguous:
3002 assert(false && "Ambiguous reference binding conversions not implemented.");
3003 return true;
3004
3005 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00003006 case OR_Deleted:
3007 // There was no suitable conversion, or we found a deleted
3008 // conversion; continue with other checks.
Douglas Gregore6985fe2008-11-10 16:14:15 +00003009 break;
3010 }
3011 }
3012
Douglas Gregor81c29152008-10-29 00:13:59 +00003013 if (BindsDirectly) {
3014 // C++ [dcl.init.ref]p4:
3015 // [...] In all cases where the reference-related or
3016 // reference-compatible relationship of two types is used to
3017 // establish the validity of a reference binding, and T1 is a
3018 // base class of T2, a program that necessitates such a binding
3019 // is ill-formed if T1 is an inaccessible (clause 11) or
3020 // ambiguous (10.2) base class of T2.
3021 //
3022 // Note that we only check this condition when we're allowed to
3023 // complain about errors, because we should not be checking for
3024 // ambiguity (or inaccessibility) unless the reference binding
3025 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003026 if (DerivedToBase)
3027 return CheckDerivedToBaseConversion(T2, T1,
3028 Init->getSourceRange().getBegin(),
3029 Init->getSourceRange());
3030 else
3031 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00003032 }
3033
3034 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redldfc30332009-03-29 15:27:50 +00003035 // type (i.e., cv1 shall be const), or the reference shall be an
3036 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redlce6fff02009-03-16 23:22:08 +00003037 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003038 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00003039 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00003040 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003041 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3042 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00003043 return true;
3044 }
3045
3046 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedmand5a72f02009-08-05 19:21:58 +00003047 // class type, and "cv1 T1" is reference-compatible with
3048 // "cv2 T2," the reference is bound in one of the
Douglas Gregor81c29152008-10-29 00:13:59 +00003049 // following ways (the choice is implementation-defined):
3050 //
3051 // -- The reference is bound to the object represented by
3052 // the rvalue (see 3.10) or to a sub-object within that
3053 // object.
3054 //
Eli Friedmand5a72f02009-08-05 19:21:58 +00003055 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor81c29152008-10-29 00:13:59 +00003056 // a constructor is called to copy the entire rvalue
3057 // object into the temporary. The reference is bound to
3058 // the temporary or to a sub-object within the
3059 // temporary.
3060 //
Douglas Gregor81c29152008-10-29 00:13:59 +00003061 // The constructor that would be used to make the copy
3062 // shall be callable whether or not the copy is actually
3063 // done.
3064 //
Sebastian Redldfc30332009-03-29 15:27:50 +00003065 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor81c29152008-10-29 00:13:59 +00003066 // freedom, so we will always take the first option and never build
3067 // a temporary in this case. FIXME: We will, however, have to check
3068 // for the presence of a copy constructor in C++98/03 mode.
3069 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003070 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3071 if (ICS) {
3072 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3073 ICS->Standard.First = ICK_Identity;
3074 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3075 ICS->Standard.Third = ICK_Identity;
3076 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3077 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00003078 ICS->Standard.ReferenceBinding = true;
Sebastian Redldfc30332009-03-29 15:27:50 +00003079 ICS->Standard.DirectBinding = false;
3080 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redld3169132009-04-17 16:30:52 +00003081 ICS->Standard.CopyConstructor = 0;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003082 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +00003083 // FIXME: Binding to a subobject of the rvalue is going to require more
3084 // AST annotation than this.
Anders Carlsson85186942009-07-31 01:23:52 +00003085 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/false);
Douglas Gregor81c29152008-10-29 00:13:59 +00003086 }
3087 return false;
3088 }
3089
Eli Friedmand5a72f02009-08-05 19:21:58 +00003090 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor81c29152008-10-29 00:13:59 +00003091 // initialized from the initializer expression using the
3092 // rules for a non-reference copy initialization (8.5). The
3093 // reference is then bound to the temporary. If T1 is
3094 // reference-related to T2, cv1 must be the same
3095 // cv-qualification as, or greater cv-qualification than,
3096 // cv2; otherwise, the program is ill-formed.
3097 if (RefRelationship == Ref_Related) {
3098 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3099 // we would be reference-compatible or reference-compatible with
3100 // added qualification. But that wasn't the case, so the reference
3101 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003102 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00003103 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00003104 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003105 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3106 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00003107 return true;
3108 }
3109
Douglas Gregorb206cc42009-01-30 23:27:23 +00003110 // If at least one of the types is a class type, the types are not
3111 // related, and we aren't allowed any user conversions, the
3112 // reference binding fails. This case is important for breaking
3113 // recursion, since TryImplicitConversion below will attempt to
3114 // create a temporary through the use of a copy constructor.
3115 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3116 (T1->isRecordType() || T2->isRecordType())) {
3117 if (!ICS)
3118 Diag(Init->getSourceRange().getBegin(),
3119 diag::err_typecheck_convert_incompatible)
3120 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3121 return true;
3122 }
3123
Douglas Gregor81c29152008-10-29 00:13:59 +00003124 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003125 if (ICS) {
Sebastian Redldfc30332009-03-29 15:27:50 +00003126 // C++ [over.ics.ref]p2:
3127 //
3128 // When a parameter of reference type is not bound directly to
3129 // an argument expression, the conversion sequence is the one
3130 // required to convert the argument expression to the
3131 // underlying type of the reference according to
3132 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3133 // to copy-initializing a temporary of the underlying type with
3134 // the argument expression. Any difference in top-level
3135 // cv-qualification is subsumed by the initialization itself
3136 // and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00003137 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Sebastian Redldfc30332009-03-29 15:27:50 +00003138 // Of course, that's still a reference binding.
3139 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3140 ICS->Standard.ReferenceBinding = true;
3141 ICS->Standard.RRefBinding = isRValRef;
3142 } else if(ICS->ConversionKind ==
3143 ImplicitConversionSequence::UserDefinedConversion) {
3144 ICS->UserDefined.After.ReferenceBinding = true;
3145 ICS->UserDefined.After.RRefBinding = isRValRef;
3146 }
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003147 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3148 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00003149 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003150 }
Douglas Gregor81c29152008-10-29 00:13:59 +00003151}
Douglas Gregore60e5d32008-11-06 22:13:31 +00003152
3153/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3154/// of this overloaded operator is well-formed. If so, returns false;
3155/// otherwise, emits appropriate diagnostics and returns true.
3156bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003157 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00003158 "Expected an overloaded operator declaration");
3159
Douglas Gregore60e5d32008-11-06 22:13:31 +00003160 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3161
3162 // C++ [over.oper]p5:
3163 // The allocation and deallocation functions, operator new,
3164 // operator new[], operator delete and operator delete[], are
3165 // described completely in 3.7.3. The attributes and restrictions
3166 // found in the rest of this subclause do not apply to them unless
3167 // explicitly stated in 3.7.3.
Mike Stumpe127ae32009-05-16 07:39:55 +00003168 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregore60e5d32008-11-06 22:13:31 +00003169 if (Op == OO_New || Op == OO_Array_New ||
3170 Op == OO_Delete || Op == OO_Array_Delete)
3171 return false;
3172
3173 // C++ [over.oper]p6:
3174 // An operator function shall either be a non-static member
3175 // function or be a non-member function and have at least one
3176 // parameter whose type is a class, a reference to a class, an
3177 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003178 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3179 if (MethodDecl->isStatic())
3180 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00003181 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003182 } else {
3183 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003184 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3185 ParamEnd = FnDecl->param_end();
3186 Param != ParamEnd; ++Param) {
3187 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedmana73d6b12009-06-27 05:59:59 +00003188 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3189 ParamType->isEnumeralType()) {
Douglas Gregore60e5d32008-11-06 22:13:31 +00003190 ClassOrEnumParam = true;
3191 break;
3192 }
3193 }
3194
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003195 if (!ClassOrEnumParam)
3196 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003197 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00003198 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003199 }
3200
3201 // C++ [over.oper]p8:
3202 // An operator function cannot have default arguments (8.3.6),
3203 // except where explicitly stated below.
3204 //
3205 // Only the function-call operator allows default arguments
3206 // (C++ [over.call]p1).
3207 if (Op != OO_Call) {
3208 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3209 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +00003210 if ((*Param)->hasUnparsedDefaultArg())
3211 return Diag((*Param)->getLocation(),
3212 diag::err_operator_overload_default_arg)
3213 << FnDecl->getDeclName();
3214 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003215 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003216 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00003217 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003218 }
3219 }
3220
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003221 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3222 { false, false, false }
3223#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3224 , { Unary, Binary, MemberOnly }
3225#include "clang/Basic/OperatorKinds.def"
3226 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00003227
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003228 bool CanBeUnaryOperator = OperatorUses[Op][0];
3229 bool CanBeBinaryOperator = OperatorUses[Op][1];
3230 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00003231
3232 // C++ [over.oper]p8:
3233 // [...] Operator functions cannot have more or fewer parameters
3234 // than the number required for the corresponding operator, as
3235 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003236 unsigned NumParams = FnDecl->getNumParams()
3237 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00003238 if (Op != OO_Call &&
3239 ((NumParams == 1 && !CanBeUnaryOperator) ||
3240 (NumParams == 2 && !CanBeBinaryOperator) ||
3241 (NumParams < 1) || (NumParams > 2))) {
3242 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00003243 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003244 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00003245 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003246 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00003247 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003248 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00003249 assert(CanBeBinaryOperator &&
3250 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00003251 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003252 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00003253
Chris Lattnerbb002332008-11-21 07:57:12 +00003254 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00003255 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00003256 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003257
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003258 // Overloaded operators other than operator() cannot be variadic.
3259 if (Op != OO_Call &&
Douglas Gregor4fa58902009-02-26 23:50:07 +00003260 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003261 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00003262 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003263 }
3264
3265 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003266 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3267 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003268 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00003269 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003270 }
3271
3272 // C++ [over.inc]p1:
3273 // The user-defined function called operator++ implements the
3274 // prefix and postfix ++ operator. If this function is a member
3275 // function with no parameters, or a non-member function with one
3276 // parameter of class or enumeration type, it defines the prefix
3277 // increment operator ++ for objects of that type. If the function
3278 // is a member function with one parameter (which shall be of type
3279 // int) or a non-member function with two parameters (the second
3280 // of which shall be of type int), it defines the postfix
3281 // increment operator ++ for objects of that type.
3282 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3283 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3284 bool ParamIsInt = false;
3285 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
3286 ParamIsInt = BT->getKind() == BuiltinType::Int;
3287
Chris Lattnera7021ee2008-11-21 07:50:02 +00003288 if (!ParamIsInt)
3289 return Diag(LastParam->getLocation(),
3290 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003291 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00003292 }
3293
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003294 // Notify the class if it got an assignment operator.
3295 if (Op == OO_Equal) {
3296 // Would have returned earlier otherwise.
3297 assert(isa<CXXMethodDecl>(FnDecl) &&
3298 "Overloaded = not member, but not filtered.");
3299 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanian9da58e42009-08-13 21:09:41 +00003300 Method->setCopyAssignment(true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003301 Method->getParent()->addedAssignmentOperator(Context, Method);
3302 }
3303
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003304 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00003305}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00003306
Douglas Gregord8028382009-01-05 19:45:36 +00003307/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3308/// linkage specification, including the language and (if present)
3309/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3310/// the location of the language string literal, which is provided
3311/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3312/// the '{' brace. Otherwise, this linkage specification does not
3313/// have any braces.
Chris Lattner5261d0c2009-03-28 19:18:32 +00003314Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3315 SourceLocation ExternLoc,
3316 SourceLocation LangLoc,
3317 const char *Lang,
3318 unsigned StrSize,
3319 SourceLocation LBraceLoc) {
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003320 LinkageSpecDecl::LanguageIDs Language;
3321 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3322 Language = LinkageSpecDecl::lang_c;
3323 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3324 Language = LinkageSpecDecl::lang_cxx;
3325 else {
Douglas Gregord8028382009-01-05 19:45:36 +00003326 Diag(LangLoc, diag::err_bad_language);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003327 return DeclPtrTy();
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003328 }
3329
3330 // FIXME: Add all the various semantics of linkage specifications
3331
Douglas Gregord8028382009-01-05 19:45:36 +00003332 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
3333 LangLoc, Language,
3334 LBraceLoc.isValid());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003335 CurContext->addDecl(D);
Douglas Gregord8028382009-01-05 19:45:36 +00003336 PushDeclContext(S, D);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003337 return DeclPtrTy::make(D);
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003338}
3339
Douglas Gregord8028382009-01-05 19:45:36 +00003340/// ActOnFinishLinkageSpecification - Completely the definition of
3341/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3342/// valid, it's the position of the closing '}' brace in a linkage
3343/// specification that uses braces.
Chris Lattner5261d0c2009-03-28 19:18:32 +00003344Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3345 DeclPtrTy LinkageSpec,
3346 SourceLocation RBraceLoc) {
Douglas Gregord8028382009-01-05 19:45:36 +00003347 if (LinkageSpec)
3348 PopDeclContext();
3349 return LinkageSpec;
Chris Lattnerf58d52b2008-12-17 07:09:26 +00003350}
3351
Douglas Gregor57420b42009-05-18 20:51:54 +00003352/// \brief Perform semantic analysis for the variable declaration that
3353/// occurs within a C++ catch clause, returning the newly-created
3354/// variable.
3355VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003356 DeclaratorInfo *DInfo,
Douglas Gregor57420b42009-05-18 20:51:54 +00003357 IdentifierInfo *Name,
3358 SourceLocation Loc,
3359 SourceRange Range) {
3360 bool Invalid = false;
Sebastian Redl743c8162008-12-22 19:15:10 +00003361
3362 // Arrays and functions decay.
3363 if (ExDeclType->isArrayType())
3364 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3365 else if (ExDeclType->isFunctionType())
3366 ExDeclType = Context.getPointerType(ExDeclType);
3367
3368 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3369 // The exception-declaration shall not denote a pointer or reference to an
3370 // incomplete type, other than [cv] void*.
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003371 // N2844 forbids rvalue references.
Douglas Gregor3b7e9112009-05-18 21:08:14 +00003372 if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor57420b42009-05-18 20:51:54 +00003373 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003374 Invalid = true;
3375 }
Douglas Gregor57420b42009-05-18 20:51:54 +00003376
Sebastian Redl743c8162008-12-22 19:15:10 +00003377 QualType BaseType = ExDeclType;
3378 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003379 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003380 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl743c8162008-12-22 19:15:10 +00003381 BaseType = Ptr->getPointeeType();
3382 Mode = 1;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003383 DK = diag::err_catch_incomplete_ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003384 } else if(const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003385 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl743c8162008-12-22 19:15:10 +00003386 BaseType = Ref->getPointeeType();
3387 Mode = 2;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003388 DK = diag::err_catch_incomplete_ref;
Sebastian Redl743c8162008-12-22 19:15:10 +00003389 }
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003390 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor57420b42009-05-18 20:51:54 +00003391 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl743c8162008-12-22 19:15:10 +00003392 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00003393
Douglas Gregor57420b42009-05-18 20:51:54 +00003394 if (!Invalid && !ExDeclType->isDependentType() &&
3395 RequireNonAbstractType(Loc, ExDeclType,
3396 diag::err_abstract_type_in_decl,
3397 AbstractVariableType))
Sebastian Redl54198652009-04-27 21:03:30 +00003398 Invalid = true;
3399
Douglas Gregor57420b42009-05-18 20:51:54 +00003400 // FIXME: Need to test for ability to copy-construct and destroy the
3401 // exception variable.
3402
Sebastian Redl237116b2008-12-22 21:35:02 +00003403 // FIXME: Need to check for abstract classes.
3404
Douglas Gregor57420b42009-05-18 20:51:54 +00003405 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argiris Kirtzidis42556e42009-08-21 00:31:54 +00003406 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor57420b42009-05-18 20:51:54 +00003407
3408 if (Invalid)
3409 ExDecl->setInvalidDecl();
3410
3411 return ExDecl;
3412}
3413
3414/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3415/// handler.
3416Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003417 DeclaratorInfo *DInfo = 0;
3418 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor57420b42009-05-18 20:51:54 +00003419
3420 bool Invalid = D.isInvalidType();
Sebastian Redl743c8162008-12-22 19:15:10 +00003421 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor09be81b2009-02-04 17:27:36 +00003422 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl743c8162008-12-22 19:15:10 +00003423 // The scope should be freshly made just for us. There is just no way
3424 // it contains any previous declaration.
Chris Lattner5261d0c2009-03-28 19:18:32 +00003425 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl743c8162008-12-22 19:15:10 +00003426 if (PrevDecl->isTemplateParameter()) {
3427 // Maybe we will complain about the shadowed template parameter.
3428 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003429 }
3430 }
3431
Chris Lattner34c61332009-04-25 08:06:05 +00003432 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl743c8162008-12-22 19:15:10 +00003433 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3434 << D.getCXXScopeSpec().getRange();
Chris Lattner34c61332009-04-25 08:06:05 +00003435 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00003436 }
3437
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003438 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor57420b42009-05-18 20:51:54 +00003439 D.getIdentifier(),
3440 D.getIdentifierLoc(),
3441 D.getDeclSpec().getSourceRange());
3442
Chris Lattner34c61332009-04-25 08:06:05 +00003443 if (Invalid)
3444 ExDecl->setInvalidDecl();
3445
Sebastian Redl743c8162008-12-22 19:15:10 +00003446 // Add the exception declaration into this scope.
Sebastian Redl743c8162008-12-22 19:15:10 +00003447 if (II)
Douglas Gregor57420b42009-05-18 20:51:54 +00003448 PushOnScopeChains(ExDecl, S);
3449 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003450 CurContext->addDecl(ExDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003451
Douglas Gregor2a2e0402009-06-17 21:51:59 +00003452 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003453 return DeclPtrTy::make(ExDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003454}
Anders Carlssoned691562009-03-14 00:25:26 +00003455
Chris Lattner5261d0c2009-03-28 19:18:32 +00003456Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
3457 ExprArg assertexpr,
3458 ExprArg assertmessageexpr) {
Anders Carlssoned691562009-03-14 00:25:26 +00003459 Expr *AssertExpr = (Expr *)assertexpr.get();
3460 StringLiteral *AssertMessage =
3461 cast<StringLiteral>((Expr *)assertmessageexpr.get());
3462
Anders Carlsson8b842c52009-03-14 00:33:21 +00003463 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3464 llvm::APSInt Value(32);
3465 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3466 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3467 AssertExpr->getSourceRange();
Chris Lattner5261d0c2009-03-28 19:18:32 +00003468 return DeclPtrTy();
Anders Carlsson8b842c52009-03-14 00:33:21 +00003469 }
Anders Carlssoned691562009-03-14 00:25:26 +00003470
Anders Carlsson8b842c52009-03-14 00:33:21 +00003471 if (Value == 0) {
3472 std::string str(AssertMessage->getStrData(),
3473 AssertMessage->getByteLength());
Anders Carlssonc45057a2009-03-15 18:44:04 +00003474 Diag(AssertLoc, diag::err_static_assert_failed)
3475 << str << AssertExpr->getSourceRange();
Anders Carlsson8b842c52009-03-14 00:33:21 +00003476 }
3477 }
3478
Anders Carlsson0f4942b2009-03-15 17:35:16 +00003479 assertexpr.release();
3480 assertmessageexpr.release();
Anders Carlssoned691562009-03-14 00:25:26 +00003481 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
3482 AssertExpr, AssertMessage);
Anders Carlssoned691562009-03-14 00:25:26 +00003483
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003484 CurContext->addDecl(Decl);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003485 return DeclPtrTy::make(Decl);
Anders Carlssoned691562009-03-14 00:25:26 +00003486}
Sebastian Redla8cecf62009-03-24 22:27:57 +00003487
John McCall140607b2009-08-06 02:15:43 +00003488Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S,
John McCall36493082009-08-11 06:59:38 +00003489 llvm::PointerUnion<const DeclSpec*,Declarator*> DU,
3490 bool IsDefinition) {
John McCall140607b2009-08-06 02:15:43 +00003491 Declarator *D = DU.dyn_cast<Declarator*>();
3492 const DeclSpec &DS = (D ? D->getDeclSpec() : *DU.get<const DeclSpec*>());
3493
3494 assert(DS.isFriendSpecified());
3495 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
3496
3497 // If there's no declarator, then this can only be a friend class
John McCall7be34f42009-08-11 21:13:21 +00003498 // declaration (or else it's just syntactically invalid).
John McCall140607b2009-08-06 02:15:43 +00003499 if (!D) {
John McCall7be34f42009-08-11 21:13:21 +00003500 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall140607b2009-08-06 02:15:43 +00003501
John McCall7be34f42009-08-11 21:13:21 +00003502 QualType T;
3503 DeclContext *DC;
John McCall140607b2009-08-06 02:15:43 +00003504
John McCall7be34f42009-08-11 21:13:21 +00003505 // In C++0x, we just accept any old type.
3506 if (getLangOptions().CPlusPlus0x) {
3507 bool invalid = false;
3508 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
3509 if (invalid)
3510 return DeclPtrTy();
John McCall140607b2009-08-06 02:15:43 +00003511
John McCall7be34f42009-08-11 21:13:21 +00003512 // The semantic context in which to create the decl. If it's not
3513 // a record decl (or we don't yet know if it is), create it in the
3514 // current context.
3515 DC = CurContext;
3516 if (const RecordType *RT = T->getAs<RecordType>())
3517 DC = RT->getDecl()->getDeclContext();
3518
3519 // The C++98 rules are somewhat more complex.
3520 } else {
3521 // C++ [class.friend]p2:
3522 // An elaborated-type-specifier shall be used in a friend declaration
3523 // for a class.*
3524 // * The class-key of the elaborated-type-specifier is required.
3525 CXXRecordDecl *RD = 0;
3526
3527 switch (DS.getTypeSpecType()) {
3528 case DeclSpec::TST_class:
3529 case DeclSpec::TST_struct:
3530 case DeclSpec::TST_union:
3531 RD = dyn_cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
3532 if (!RD) return DeclPtrTy();
3533 break;
3534
3535 case DeclSpec::TST_typename:
3536 if (const RecordType *RT =
3537 ((const Type*) DS.getTypeRep())->getAs<RecordType>())
3538 RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
3539 // fallthrough
3540 default:
3541 if (RD) {
3542 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
3543 << (RD->isUnion())
3544 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
3545 RD->isUnion() ? " union" : " class");
3546 return DeclPtrTy::make(RD);
3547 }
3548
3549 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
3550 << DS.getSourceRange();
3551 return DeclPtrTy();
John McCall140607b2009-08-06 02:15:43 +00003552 }
3553
John McCall7be34f42009-08-11 21:13:21 +00003554 // The record declaration we get from friend declarations is not
3555 // canonicalized; see ActOnTag.
John McCall7be34f42009-08-11 21:13:21 +00003556
3557 // C++ [class.friend]p2: A class shall not be defined inside
3558 // a friend declaration.
3559 if (RD->isDefinition())
3560 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
3561 << RD->getSourceRange();
3562
3563 // C++98 [class.friend]p1: A friend of a class is a function
3564 // or class that is not a member of the class . . .
3565 // But that's a silly restriction which nobody implements for
3566 // inner classes, and C++0x removes it anyway, so we only report
3567 // this (as a warning) if we're being pedantic.
3568 //
3569 // Also, definitions currently get treated in a way that causes
3570 // this error, so only report it if we didn't see a definition.
3571 else if (RD->getDeclContext() == CurContext &&
3572 !getLangOptions().CPlusPlus0x)
3573 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
3574
3575 T = QualType(RD->getTypeForDecl(), 0);
3576 DC = RD->getDeclContext();
John McCall140607b2009-08-06 02:15:43 +00003577 }
3578
John McCall7be34f42009-08-11 21:13:21 +00003579 FriendClassDecl *FCD = FriendClassDecl::Create(Context, DC, Loc, T,
3580 DS.getFriendSpecLoc());
3581 FCD->setLexicalDeclContext(CurContext);
John McCall140607b2009-08-06 02:15:43 +00003582
John McCall7be34f42009-08-11 21:13:21 +00003583 if (CurContext->isDependentContext())
3584 CurContext->addHiddenDecl(FCD);
3585 else
3586 CurContext->addDecl(FCD);
John McCall140607b2009-08-06 02:15:43 +00003587
John McCall7be34f42009-08-11 21:13:21 +00003588 return DeclPtrTy::make(FCD);
Anders Carlssonb56d8b32009-05-11 22:55:49 +00003589 }
John McCall140607b2009-08-06 02:15:43 +00003590
3591 // We have a declarator.
3592 assert(D);
3593
3594 SourceLocation Loc = D->getIdentifierLoc();
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003595 DeclaratorInfo *DInfo = 0;
3596 QualType T = GetTypeForDeclarator(*D, S, &DInfo);
John McCall140607b2009-08-06 02:15:43 +00003597
3598 // C++ [class.friend]p1
3599 // A friend of a class is a function or class....
3600 // Note that this sees through typedefs, which is intended.
3601 if (!T->isFunctionType()) {
3602 Diag(Loc, diag::err_unexpected_friend);
3603
3604 // It might be worthwhile to try to recover by creating an
3605 // appropriate declaration.
3606 return DeclPtrTy();
3607 }
3608
3609 // C++ [namespace.memdef]p3
3610 // - If a friend declaration in a non-local class first declares a
3611 // class or function, the friend class or function is a member
3612 // of the innermost enclosing namespace.
3613 // - The name of the friend is not found by simple name lookup
3614 // until a matching declaration is provided in that namespace
3615 // scope (either before or after the class declaration granting
3616 // friendship).
3617 // - If a friend function is called, its name may be found by the
3618 // name lookup that considers functions from namespaces and
3619 // classes associated with the types of the function arguments.
3620 // - When looking for a prior declaration of a class or a function
3621 // declared as a friend, scopes outside the innermost enclosing
3622 // namespace scope are not considered.
3623
3624 CXXScopeSpec &ScopeQual = D->getCXXScopeSpec();
3625 DeclarationName Name = GetNameForDeclarator(*D);
3626 assert(Name);
3627
3628 // The existing declaration we found.
3629 FunctionDecl *FD = NULL;
3630
3631 // The context we found the declaration in, or in which we should
3632 // create the declaration.
3633 DeclContext *DC;
3634
3635 // FIXME: handle local classes
3636
3637 // Recover from invalid scope qualifiers as if they just weren't there.
3638 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
3639 DC = computeDeclContext(ScopeQual);
3640
3641 // FIXME: handle dependent contexts
3642 if (!DC) return DeclPtrTy();
3643
3644 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3645
3646 // If searching in that context implicitly found a declaration in
3647 // a different context, treat it like it wasn't found at all.
3648 // TODO: better diagnostics for this case. Suggesting the right
3649 // qualified scope would be nice...
3650 if (!Dec || Dec->getDeclContext() != DC) {
3651 D->setInvalidType();
3652 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
3653 return DeclPtrTy();
3654 }
3655
3656 // C++ [class.friend]p1: A friend of a class is a function or
3657 // class that is not a member of the class . . .
3658 if (DC == CurContext)
3659 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
3660
3661 FD = cast<FunctionDecl>(Dec);
3662
3663 // Otherwise walk out to the nearest namespace scope looking for matches.
3664 } else {
3665 // TODO: handle local class contexts.
3666
3667 DC = CurContext;
3668 while (true) {
3669 // Skip class contexts. If someone can cite chapter and verse
3670 // for this behavior, that would be nice --- it's what GCC and
3671 // EDG do, and it seems like a reasonable intent, but the spec
3672 // really only says that checks for unqualified existing
3673 // declarations should stop at the nearest enclosing namespace,
3674 // not that they should only consider the nearest enclosing
3675 // namespace.
3676 while (DC->isRecord()) DC = DC->getParent();
3677
3678 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3679
3680 // TODO: decide what we think about using declarations.
3681 if (Dec) {
3682 FD = cast<FunctionDecl>(Dec);
3683 break;
3684 }
3685 if (DC->isFileContext()) break;
3686 DC = DC->getParent();
3687 }
3688
3689 // C++ [class.friend]p1: A friend of a class is a function or
3690 // class that is not a member of the class . . .
John McCall392245a2009-08-06 20:49:32 +00003691 // C++0x changes this for both friend types and functions.
3692 // Most C++ 98 compilers do seem to give an error here, so
3693 // we do, too.
3694 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall140607b2009-08-06 02:15:43 +00003695 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
3696 }
3697
John McCall36493082009-08-11 06:59:38 +00003698 bool Redeclaration = (FD != 0);
3699
3700 // If we found a match, create a friend function declaration with
3701 // that function as the previous declaration.
3702 if (Redeclaration) {
3703 // Create it in the semantic context of the original declaration.
3704 DC = FD->getDeclContext();
3705
John McCall140607b2009-08-06 02:15:43 +00003706 // If we didn't find something matching the type exactly, create
3707 // a declaration. This declaration should only be findable via
3708 // argument-dependent lookup.
John McCall36493082009-08-11 06:59:38 +00003709 } else {
John McCall140607b2009-08-06 02:15:43 +00003710 assert(DC->isFileContext());
3711
3712 // This implies that it has to be an operator or function.
3713 if (D->getKind() == Declarator::DK_Constructor ||
3714 D->getKind() == Declarator::DK_Destructor ||
3715 D->getKind() == Declarator::DK_Conversion) {
3716 Diag(Loc, diag::err_introducing_special_friend) <<
3717 (D->getKind() == Declarator::DK_Constructor ? 0 :
3718 D->getKind() == Declarator::DK_Destructor ? 1 : 2);
3719 return DeclPtrTy();
3720 }
John McCall140607b2009-08-06 02:15:43 +00003721 }
3722
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003723 NamedDecl *ND = ActOnFunctionDeclarator(S, *D, DC, T, DInfo,
John McCall36493082009-08-11 06:59:38 +00003724 /* PrevDecl = */ FD,
3725 MultiTemplateParamsArg(*this),
3726 IsDefinition,
3727 Redeclaration);
3728 FD = cast_or_null<FriendFunctionDecl>(ND);
3729
John McCallbcee9272009-08-18 00:00:49 +00003730 assert(FD->getDeclContext() == DC);
3731 assert(FD->getLexicalDeclContext() == CurContext);
3732
John McCall36493082009-08-11 06:59:38 +00003733 // If this is a dependent context, just add the decl to the
3734 // class's decl list and don't both with the lookup tables. This
3735 // doesn't affect lookup because any call that might find this
3736 // function via ADL necessarily has to involve dependently-typed
3737 // arguments and hence can't be resolved until
3738 // template-instantiation anyway.
3739 if (CurContext->isDependentContext())
3740 CurContext->addHiddenDecl(FD);
3741 else
3742 CurContext->addDecl(FD);
John McCall140607b2009-08-06 02:15:43 +00003743
3744 return DeclPtrTy::make(FD);
Anders Carlssonb56d8b32009-05-11 22:55:49 +00003745}
3746
Chris Lattner5261d0c2009-03-28 19:18:32 +00003747void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregor84164f02009-08-24 11:57:43 +00003748 AdjustDeclIfTemplate(dcl);
3749
Chris Lattner5261d0c2009-03-28 19:18:32 +00003750 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redla8cecf62009-03-24 22:27:57 +00003751 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
3752 if (!Fn) {
3753 Diag(DelLoc, diag::err_deleted_non_function);
3754 return;
3755 }
3756 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
3757 Diag(DelLoc, diag::err_deleted_decl_not_first);
3758 Diag(Prev->getLocation(), diag::note_previous_declaration);
3759 // If the declaration wasn't the first, we delete the function anyway for
3760 // recovery.
3761 }
3762 Fn->setDeleted();
3763}
Sebastian Redl3b1ef312009-04-27 21:33:24 +00003764
3765static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
3766 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
3767 ++CI) {
3768 Stmt *SubStmt = *CI;
3769 if (!SubStmt)
3770 continue;
3771 if (isa<ReturnStmt>(SubStmt))
3772 Self.Diag(SubStmt->getSourceRange().getBegin(),
3773 diag::err_return_in_constructor_handler);
3774 if (!isa<Expr>(SubStmt))
3775 SearchForReturnInStmt(Self, SubStmt);
3776 }
3777}
3778
3779void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
3780 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
3781 CXXCatchStmt *Handler = TryBlock->getHandler(I);
3782 SearchForReturnInStmt(*this, Handler);
3783 }
3784}
Anders Carlssone80e29c2009-05-14 01:09:04 +00003785
3786bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3787 const CXXMethodDecl *Old) {
3788 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
3789 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
3790
3791 QualType CNewTy = Context.getCanonicalType(NewTy);
3792 QualType COldTy = Context.getCanonicalType(OldTy);
3793
3794 if (CNewTy == COldTy &&
3795 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
3796 return false;
3797
Anders Carlssonee7177b2009-05-14 19:52:19 +00003798 // Check if the return types are covariant
3799 QualType NewClassTy, OldClassTy;
3800
3801 /// Both types must be pointers or references to classes.
3802 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
3803 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
3804 NewClassTy = NewPT->getPointeeType();
3805 OldClassTy = OldPT->getPointeeType();
3806 }
3807 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
3808 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
3809 NewClassTy = NewRT->getPointeeType();
3810 OldClassTy = OldRT->getPointeeType();
3811 }
3812 }
3813
3814 // The return types aren't either both pointers or references to a class type.
3815 if (NewClassTy.isNull()) {
3816 Diag(New->getLocation(),
3817 diag::err_different_return_type_for_overriding_virtual_function)
3818 << New->getDeclName() << NewTy << OldTy;
3819 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3820
3821 return true;
3822 }
Anders Carlssone80e29c2009-05-14 01:09:04 +00003823
Anders Carlssonee7177b2009-05-14 19:52:19 +00003824 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
3825 // Check if the new class derives from the old class.
3826 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
3827 Diag(New->getLocation(),
3828 diag::err_covariant_return_not_derived)
3829 << New->getDeclName() << NewTy << OldTy;
3830 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3831 return true;
3832 }
3833
3834 // Check if we the conversion from derived to base is valid.
3835 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
3836 diag::err_covariant_return_inaccessible_base,
3837 diag::err_covariant_return_ambiguous_derived_to_base_conv,
3838 // FIXME: Should this point to the return type?
3839 New->getLocation(), SourceRange(), New->getDeclName())) {
3840 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3841 return true;
3842 }
3843 }
3844
3845 // The qualifiers of the return types must be the same.
3846 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
3847 Diag(New->getLocation(),
3848 diag::err_covariant_return_type_different_qualifications)
Anders Carlssone80e29c2009-05-14 01:09:04 +00003849 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonee7177b2009-05-14 19:52:19 +00003850 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3851 return true;
3852 };
3853
3854
3855 // The new class type must have the same or less qualifiers as the old type.
3856 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
3857 Diag(New->getLocation(),
3858 diag::err_covariant_return_type_class_type_more_qualified)
3859 << New->getDeclName() << NewTy << OldTy;
3860 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3861 return true;
3862 };
3863
3864 return false;
Anders Carlssone80e29c2009-05-14 01:09:04 +00003865}
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003866
Sebastian Redl953d12a2009-07-07 20:29:57 +00003867bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
3868 const CXXMethodDecl *Old)
3869{
3870 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
3871 diag::note_overridden_virtual_function,
3872 Old->getType()->getAsFunctionProtoType(),
3873 Old->getLocation(),
3874 New->getType()->getAsFunctionProtoType(),
3875 New->getLocation());
3876}
3877
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003878/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3879/// initializer for the declaration 'Dcl'.
3880/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3881/// static data member of class X, names should be looked up in the scope of
3882/// class X.
3883void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregor84164f02009-08-24 11:57:43 +00003884 AdjustDeclIfTemplate(Dcl);
3885
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003886 Decl *D = Dcl.getAs<Decl>();
3887 // If there is no declaration, there was an error parsing it.
3888 if (D == 0)
3889 return;
3890
3891 // Check whether it is a declaration with a nested name specifier like
3892 // int foo::bar;
3893 if (!D->isOutOfLine())
3894 return;
3895
3896 // C++ [basic.lookup.unqual]p13
3897 //
3898 // A name used in the definition of a static data member of class X
3899 // (after the qualified-id of the static member) is looked up as if the name
3900 // was used in a member function of X.
3901
3902 // Change current context into the context of the initializing declaration.
Argiris Kirtzidisa0b19fe2009-06-17 23:15:40 +00003903 EnterDeclaratorContext(S, D->getDeclContext());
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003904}
3905
3906/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3907/// initializer for the declaration 'Dcl'.
3908void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregor84164f02009-08-24 11:57:43 +00003909 AdjustDeclIfTemplate(Dcl);
3910
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003911 Decl *D = Dcl.getAs<Decl>();
3912 // If there is no declaration, there was an error parsing it.
3913 if (D == 0)
3914 return;
3915
3916 // Check whether it is a declaration with a nested name specifier like
3917 // int foo::bar;
3918 if (!D->isOutOfLine())
3919 return;
3920
3921 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argiris Kirtzidisa0b19fe2009-06-17 23:15:40 +00003922 ExitDeclaratorContext(S);
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003923}