blob: 41a7fe653d8ed383cf2e5ec47b1170ad1876730e [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"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000021#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000022#include "clang/Parse/DeclSpec.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000023#include "llvm/ADT/STLExtras.h"
Chris Lattner97316c02008-04-10 02:22:51 +000024#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000025#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000026#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000027
28using namespace clang;
29
Chris Lattner97316c02008-04-10 02:22:51 +000030//===----------------------------------------------------------------------===//
31// CheckDefaultArgumentVisitor
32//===----------------------------------------------------------------------===//
33
Chris Lattnerb1856db2008-04-12 23:52:44 +000034namespace {
35 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
36 /// the default argument of a parameter to determine whether it
37 /// contains any ill-formed subexpressions. For example, this will
38 /// diagnose the use of local variables or parameters within the
39 /// default argument expression.
40 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000041 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000042 Expr *DefaultArg;
43 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000044
Chris Lattnerb1856db2008-04-12 23:52:44 +000045 public:
46 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
47 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000048
Chris Lattnerb1856db2008-04-12 23:52:44 +000049 bool VisitExpr(Expr *Node);
50 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000051 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000052 };
Chris Lattner97316c02008-04-10 02:22:51 +000053
Chris Lattnerb1856db2008-04-12 23:52:44 +000054 /// VisitExpr - Visit all of the children of this expression.
55 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
56 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000057 for (Stmt::child_iterator I = Node->child_begin(),
58 E = Node->child_end(); I != E; ++I)
59 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000060 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000061 }
62
Chris Lattnerb1856db2008-04-12 23:52:44 +000063 /// VisitDeclRefExpr - Visit a reference to a declaration, to
64 /// determine whether this declaration can be used in the default
65 /// argument expression.
66 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000067 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000068 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
69 // C++ [dcl.fct.default]p9
70 // Default arguments are evaluated each time the function is
71 // called. The order of evaluation of function arguments is
72 // unspecified. Consequently, parameters of a function shall not
73 // be used in default argument expressions, even if they are not
74 // evaluated. Parameters of a function declared before a default
75 // argument expression are in scope and can hide namespace and
76 // class member names.
77 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000078 diag::err_param_default_argument_references_param)
Chris Lattnerb1753422008-11-23 21:45:46 +000079 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff72a6ebc2008-04-15 22:42:06 +000080 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000081 // C++ [dcl.fct.default]p7
82 // Local variables shall not be used in default argument
83 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000084 if (VDecl->isBlockVarDecl())
85 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000086 diag::err_param_default_argument_references_local)
Chris Lattnerb1753422008-11-23 21:45:46 +000087 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +000088 }
Chris Lattner97316c02008-04-10 02:22:51 +000089
Douglas Gregor3c246952008-11-04 13:41:56 +000090 return false;
91 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000092
Douglas Gregora5b022a2008-11-04 14:32:21 +000093 /// VisitCXXThisExpr - Visit a C++ "this" expression.
94 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
95 // C++ [dcl.fct.default]p8:
96 // The keyword this shall not be used in a default argument of a
97 // member function.
98 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000099 diag::err_param_default_argument_references_this)
100 << ThisE->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +0000101 }
Chris Lattner97316c02008-04-10 02:22:51 +0000102}
103
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000104bool
105Sema::SetParamDefaultArgument(ParmVarDecl *Param, ExprArg DefaultArg,
106 SourceLocation EqualLoc)
107{
108 QualType ParamType = Param->getType();
109
Anders Carlssonec926872009-08-25 13:46:13 +0000110 if (RequireCompleteType(Param->getLocation(), Param->getType(),
111 diag::err_typecheck_decl_incomplete_type)) {
112 Param->setInvalidDecl();
113 return true;
114 }
115
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000116 Expr *Arg = (Expr *)DefaultArg.get();
117
118 // C++ [dcl.fct.default]p5
119 // A default argument expression is implicitly converted (clause
120 // 4) to the parameter type. The default argument expression has
121 // the same semantic constraints as the initializer expression in
122 // a declaration of a variable of the parameter type, using the
123 // copy-initialization semantics (8.5).
124 if (CheckInitializerTypes(Arg, ParamType, EqualLoc,
125 Param->getDeclName(), /*DirectInit=*/false))
Anders Carlsson92936c42009-08-25 03:18:48 +0000126 return true;
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000127
128 Arg = MaybeCreateCXXExprWithTemporaries(Arg, /*DestroyTemps=*/false);
129
130 // Okay: add the default argument to the parameter
131 Param->setDefaultArg(Arg);
132
133 DefaultArg.release();
134
Anders Carlsson92936c42009-08-25 03:18:48 +0000135 return false;
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000136}
137
Chris Lattner97316c02008-04-10 02:22:51 +0000138/// ActOnParamDefaultArgument - Check whether the default argument
139/// provided for a function parameter is well-formed. If so, attach it
140/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000141void
Chris Lattner5261d0c2009-03-28 19:18:32 +0000142Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000143 ExprArg defarg) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000144 if (!param || !defarg.get())
145 return;
146
Chris Lattner5261d0c2009-03-28 19:18:32 +0000147 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlssona116e6e2009-06-12 16:51:40 +0000148 UnparsedDefaultArgLocs.erase(Param);
149
Anders Carlssonc154a722009-05-01 19:30:39 +0000150 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000151 QualType ParamType = Param->getType();
152
153 // Default arguments are only permitted in C++
154 if (!getLangOptions().CPlusPlus) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000155 Diag(EqualLoc, diag::err_param_default_argument)
156 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000157 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000158 return;
159 }
160
Anders Carlssone0498192009-08-25 01:02:06 +0000161 // Check that the default argument is well-formed
162 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
163 if (DefaultArgChecker.Visit(DefaultArg.get())) {
164 Param->setInvalidDecl();
165 return;
166 }
167
Anders Carlsson60eb3be2009-08-25 02:29:20 +0000168 SetParamDefaultArgument(Param, move(DefaultArg), EqualLoc);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000169}
170
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000171/// ActOnParamUnparsedDefaultArgument - We've seen a default
172/// argument for a function parameter, but we can't parse it yet
173/// because we're inside a class definition. Note that this default
174/// argument will be parsed later.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000175void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlssona116e6e2009-06-12 16:51:40 +0000176 SourceLocation EqualLoc,
177 SourceLocation ArgLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000178 if (!param)
179 return;
180
Chris Lattner5261d0c2009-03-28 19:18:32 +0000181 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000182 if (Param)
183 Param->setUnparsedDefaultArg();
Anders Carlssona116e6e2009-06-12 16:51:40 +0000184
185 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000186}
187
Douglas Gregor605de8d2008-12-16 21:30:33 +0000188/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
189/// the default argument for the parameter param failed.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000190void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000191 if (!param)
192 return;
193
Anders Carlssona116e6e2009-06-12 16:51:40 +0000194 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
195
196 Param->setInvalidDecl();
197
198 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000199}
200
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000201/// CheckExtraCXXDefaultArguments - Check for any extra default
202/// arguments in the declarator, which is not a function declaration
203/// or definition and therefore is not permitted to have default
204/// arguments. This routine should be invoked for every declarator
205/// that is not a function declaration or definition.
206void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
207 // C++ [dcl.fct.default]p3
208 // A default argument expression shall be specified only in the
209 // parameter-declaration-clause of a function declaration or in a
210 // template-parameter (14.1). It shall not be specified for a
211 // parameter pack. If it is specified in a
212 // parameter-declaration-clause, it shall not occur within a
213 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000214 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000215 DeclaratorChunk &chunk = D.getTypeObject(i);
216 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000217 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
218 ParmVarDecl *Param =
219 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000220 if (Param->hasUnparsedDefaultArg()) {
221 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000222 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
223 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
224 delete Toks;
225 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000226 } else if (Param->getDefaultArg()) {
227 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
228 << Param->getDefaultArg()->getSourceRange();
229 Param->setDefaultArg(0);
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000230 }
231 }
232 }
233 }
234}
235
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000236// MergeCXXFunctionDecl - Merge two declarations of the same C++
237// function, once we already know that they have the same
Douglas Gregor083c23e2009-02-16 17:45:42 +0000238// type. Subroutine of MergeFunctionDecl. Returns true if there was an
239// error, false otherwise.
240bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
241 bool Invalid = false;
242
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000243 // C++ [dcl.fct.default]p4:
244 //
245 // For non-template functions, default arguments can be added in
246 // later declarations of a function in the same
247 // scope. Declarations in different scopes have completely
248 // distinct sets of default arguments. That is, declarations in
249 // inner scopes do not acquire default arguments from
250 // declarations in outer scopes, and vice versa. In a given
251 // function declaration, all parameters subsequent to a
252 // parameter with a default argument shall have default
253 // arguments supplied in this or previous declarations. A
254 // default argument shall not be redefined by a later
255 // declaration (not even to the same value).
256 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
257 ParmVarDecl *OldParam = Old->getParamDecl(p);
258 ParmVarDecl *NewParam = New->getParamDecl(p);
259
260 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
261 Diag(NewParam->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000262 diag::err_param_default_argument_redefinition)
263 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000264 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregor083c23e2009-02-16 17:45:42 +0000265 Invalid = true;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000266 } else if (OldParam->getDefaultArg()) {
267 // Merge the old default argument into the new parameter
268 NewParam->setDefaultArg(OldParam->getDefaultArg());
269 }
270 }
271
Sebastian Redl5e1e0a02009-07-04 11:39:00 +0000272 if (CheckEquivalentExceptionSpec(
273 Old->getType()->getAsFunctionProtoType(), Old->getLocation(),
274 New->getType()->getAsFunctionProtoType(), New->getLocation())) {
275 Invalid = true;
276 }
277
Douglas Gregor083c23e2009-02-16 17:45:42 +0000278 return Invalid;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000279}
280
281/// CheckCXXDefaultArguments - Verify that the default arguments for a
282/// function declaration are well-formed according to C++
283/// [dcl.fct.default].
284void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
285 unsigned NumParams = FD->getNumParams();
286 unsigned p;
287
288 // Find first parameter with a default argument
289 for (p = 0; p < NumParams; ++p) {
290 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson73af5192009-08-25 01:23:32 +0000291 if (Param->hasDefaultArg())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000292 break;
293 }
294
295 // C++ [dcl.fct.default]p4:
296 // In a given function declaration, all parameters
297 // subsequent to a parameter with a default argument shall
298 // have default arguments supplied in this or previous
299 // declarations. A default argument shall not be redefined
300 // by a later declaration (not even to the same value).
301 unsigned LastMissingDefaultArg = 0;
302 for(; p < NumParams; ++p) {
303 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlsson73af5192009-08-25 01:23:32 +0000304 if (!Param->hasDefaultArg()) {
Douglas Gregor605de8d2008-12-16 21:30:33 +0000305 if (Param->isInvalidDecl())
306 /* We already complained about this parameter. */;
307 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000308 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000309 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000310 << Param->getIdentifier();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000311 else
312 Diag(Param->getLocation(),
313 diag::err_param_default_argument_missing);
314
315 LastMissingDefaultArg = p;
316 }
317 }
318
319 if (LastMissingDefaultArg > 0) {
320 // Some default arguments were missing. Clear out all of the
321 // default arguments up to (and including) the last missing
322 // default argument, so that we leave the function parameters
323 // in a semantically valid state.
324 for (p = 0; p <= LastMissingDefaultArg; ++p) {
325 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlssona116e6e2009-06-12 16:51:40 +0000326 if (Param->hasDefaultArg()) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000327 if (!Param->hasUnparsedDefaultArg())
328 Param->getDefaultArg()->Destroy(Context);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000329 Param->setDefaultArg(0);
330 }
331 }
332 }
333}
Douglas Gregorec93f442008-04-13 21:30:24 +0000334
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000335/// isCurrentClassName - Determine whether the identifier II is the
336/// name of the class type currently being defined. In the case of
337/// nested classes, this will only return true if II is the name of
338/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000339bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
340 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000341 CXXRecordDecl *CurDecl;
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000342 if (SS && SS->isSet() && !SS->isInvalid()) {
Douglas Gregor0c3c9d02009-08-21 22:16:40 +0000343 DeclContext *DC = computeDeclContext(*SS, true);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000344 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
345 } else
346 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
347
348 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000349 return &II == CurDecl->getIdentifier();
350 else
351 return false;
352}
353
Douglas Gregored3a3982009-03-03 04:44:36 +0000354/// \brief Check the validity of a C++ base class specifier.
355///
356/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
357/// and returns NULL otherwise.
358CXXBaseSpecifier *
359Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
360 SourceRange SpecifierRange,
361 bool Virtual, AccessSpecifier Access,
362 QualType BaseType,
363 SourceLocation BaseLoc) {
364 // C++ [class.union]p1:
365 // A union shall not have base classes.
366 if (Class->isUnion()) {
367 Diag(Class->getLocation(), diag::err_base_clause_on_union)
368 << SpecifierRange;
369 return 0;
370 }
371
372 if (BaseType->isDependentType())
Fariborz Jahanian1373b6f2009-07-22 17:41:53 +0000373 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregored3a3982009-03-03 04:44:36 +0000374 Class->getTagKind() == RecordDecl::TK_class,
375 Access, BaseType);
376
377 // Base specifiers must be record types.
378 if (!BaseType->isRecordType()) {
379 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
380 return 0;
381 }
382
383 // C++ [class.union]p1:
384 // A union shall not be used as a base class.
385 if (BaseType->isUnionType()) {
386 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
387 return 0;
388 }
389
390 // C++ [class.derived]p2:
391 // The class-name in a base-specifier shall not be an incompletely
392 // defined class.
Douglas Gregorc84d8932009-03-09 16:13:40 +0000393 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
Douglas Gregor375733c2009-03-10 00:06:19 +0000394 SpecifierRange))
Douglas Gregored3a3982009-03-03 04:44:36 +0000395 return 0;
396
Eli Friedman10747ff2009-08-15 21:55:26 +0000397 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000398 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
Douglas Gregored3a3982009-03-03 04:44:36 +0000399 assert(BaseDecl && "Record type has no declaration");
400 BaseDecl = BaseDecl->getDefinition(Context);
401 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Eli Friedman10747ff2009-08-15 21:55:26 +0000402 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
403 assert(CXXBaseDecl && "Base type is not a C++ type");
404 if (!CXXBaseDecl->isEmpty())
405 Class->setEmpty(false);
406 if (CXXBaseDecl->isPolymorphic())
Douglas Gregored3a3982009-03-03 04:44:36 +0000407 Class->setPolymorphic(true);
408
409 // C++ [dcl.init.aggr]p1:
410 // An aggregate is [...] a class with [...] no base classes [...].
411 Class->setAggregate(false);
412 Class->setPOD(false);
413
Anders Carlssonc6363712009-04-16 00:08:20 +0000414 if (Virtual) {
415 // C++ [class.ctor]p5:
416 // A constructor is trivial if its class has no virtual base classes.
417 Class->setHasTrivialConstructor(false);
Douglas Gregorf73c8512009-07-22 18:25:24 +0000418
419 // C++ [class.copy]p6:
420 // A copy constructor is trivial if its class has no virtual base classes.
421 Class->setHasTrivialCopyConstructor(false);
422
423 // C++ [class.copy]p11:
424 // A copy assignment operator is trivial if its class has no virtual
425 // base classes.
426 Class->setHasTrivialCopyAssignment(false);
Eli Friedman10747ff2009-08-15 21:55:26 +0000427
428 // C++0x [meta.unary.prop] is_empty:
429 // T is a class type, but not a union type, with ... no virtual base
430 // classes
431 Class->setEmpty(false);
Anders Carlssonc6363712009-04-16 00:08:20 +0000432 } else {
433 // C++ [class.ctor]p5:
434 // A constructor is trivial if all the direct base classes of its
435 // class have trivial constructors.
Douglas Gregorf73c8512009-07-22 18:25:24 +0000436 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialConstructor())
437 Class->setHasTrivialConstructor(false);
438
439 // C++ [class.copy]p6:
440 // A copy constructor is trivial if all the direct base classes of its
441 // class have trivial copy constructors.
442 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyConstructor())
443 Class->setHasTrivialCopyConstructor(false);
444
445 // C++ [class.copy]p11:
446 // A copy assignment operator is trivial if all the direct base classes
447 // of its class have trivial copy assignment operators.
448 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialCopyAssignment())
449 Class->setHasTrivialCopyAssignment(false);
Anders Carlssonc6363712009-04-16 00:08:20 +0000450 }
Anders Carlsson39a10db2009-04-17 02:34:54 +0000451
452 // C++ [class.ctor]p3:
453 // A destructor is trivial if all the direct base classes of its class
454 // have trivial destructors.
Douglas Gregorf73c8512009-07-22 18:25:24 +0000455 if (!cast<CXXRecordDecl>(BaseDecl)->hasTrivialDestructor())
456 Class->setHasTrivialDestructor(false);
Anders Carlssonc6363712009-04-16 00:08:20 +0000457
Douglas Gregored3a3982009-03-03 04:44:36 +0000458 // Create the base specifier.
459 // FIXME: Allocate via ASTContext?
Fariborz Jahanian1373b6f2009-07-22 17:41:53 +0000460 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
Douglas Gregored3a3982009-03-03 04:44:36 +0000461 Class->getTagKind() == RecordDecl::TK_class,
462 Access, BaseType);
463}
464
Douglas Gregorec93f442008-04-13 21:30:24 +0000465/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
466/// one entry in the base class list of a class specifier, for
467/// example:
468/// class foo : public bar, virtual private baz {
469/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000470Sema::BaseResult
Chris Lattner5261d0c2009-03-28 19:18:32 +0000471Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorabed2172008-10-22 17:49:05 +0000472 bool Virtual, AccessSpecifier Access,
473 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000474 if (!classdecl)
475 return true;
476
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000477 AdjustDeclIfTemplate(classdecl);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000478 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000479 QualType BaseType = GetTypeFromParser(basetype);
Douglas Gregored3a3982009-03-03 04:44:36 +0000480 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
481 Virtual, Access,
482 BaseType, BaseLoc))
483 return BaseSpec;
484
485 return true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000486}
Douglas Gregorec93f442008-04-13 21:30:24 +0000487
Douglas Gregored3a3982009-03-03 04:44:36 +0000488/// \brief Performs the actual work of attaching the given base class
489/// specifiers to a C++ class.
490bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
491 unsigned NumBases) {
492 if (NumBases == 0)
493 return false;
Douglas Gregorabed2172008-10-22 17:49:05 +0000494
495 // Used to keep track of which base types we have already seen, so
496 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000497 // that the key is always the unqualified canonical type of the base
498 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000499 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
500
501 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000502 unsigned NumGoodBases = 0;
Douglas Gregored3a3982009-03-03 04:44:36 +0000503 bool Invalid = false;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000504 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000505 QualType NewBaseType
Douglas Gregored3a3982009-03-03 04:44:36 +0000506 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor4fd85902008-10-23 18:13:27 +0000507 NewBaseType = NewBaseType.getUnqualifiedType();
508
Douglas Gregorabed2172008-10-22 17:49:05 +0000509 if (KnownBaseTypes[NewBaseType]) {
510 // C++ [class.mi]p3:
511 // A class shall not be specified as a direct base class of a
512 // derived class more than once.
Douglas Gregored3a3982009-03-03 04:44:36 +0000513 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000514 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000515 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregored3a3982009-03-03 04:44:36 +0000516 << Bases[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000517
518 // Delete the duplicate base class specifier; we're going to
519 // overwrite its pointer later.
Douglas Gregorf2fedc62009-07-22 20:55:49 +0000520 Context.Deallocate(Bases[idx]);
Douglas Gregored3a3982009-03-03 04:44:36 +0000521
522 Invalid = true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000523 } else {
524 // Okay, add this new base class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000525 KnownBaseTypes[NewBaseType] = Bases[idx];
526 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000527 }
528 }
529
530 // Attach the remaining base class specifiers to the derived class.
Fariborz Jahanian9cd0a3c2009-07-02 18:26:15 +0000531 Class->setBases(Context, Bases, NumGoodBases);
Douglas Gregor4fd85902008-10-23 18:13:27 +0000532
533 // Delete the remaining (good) base class specifiers, since their
534 // data has been copied into the CXXRecordDecl.
535 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregorf2fedc62009-07-22 20:55:49 +0000536 Context.Deallocate(Bases[idx]);
Douglas Gregored3a3982009-03-03 04:44:36 +0000537
538 return Invalid;
539}
540
541/// ActOnBaseSpecifiers - Attach the given base specifiers to the
542/// class, after checking whether there are any duplicate base
543/// classes.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000544void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregored3a3982009-03-03 04:44:36 +0000545 unsigned NumBases) {
546 if (!ClassDecl || !Bases || !NumBases)
547 return;
548
549 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000550 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregored3a3982009-03-03 04:44:36 +0000551 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregorec93f442008-04-13 21:30:24 +0000552}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000553
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000554//===----------------------------------------------------------------------===//
555// C++ class member Handling
556//===----------------------------------------------------------------------===//
557
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000558/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
559/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
560/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerd6c78092009-04-12 22:37:57 +0000561/// any.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000562Sema::DeclPtrTy
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000563Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Douglas Gregor398a8012009-08-20 22:52:58 +0000564 MultiTemplateParamsArg TemplateParameterLists,
Sebastian Redla55834a2009-04-12 17:16:29 +0000565 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000566 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000567 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000568 Expr *BitWidth = static_cast<Expr*>(BW);
569 Expr *Init = static_cast<Expr*>(InitExpr);
570 SourceLocation Loc = D.getIdentifierLoc();
571
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000572 bool isFunc = D.isFunctionDeclarator();
573
John McCall140607b2009-08-06 02:15:43 +0000574 assert(!DS.isFriendSpecified());
575
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000576 // C++ 9.2p6: A member shall not be declared to have automatic storage
577 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000578 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
579 // data members and cannot be applied to names declared const or static,
580 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000581 switch (DS.getStorageClassSpec()) {
582 case DeclSpec::SCS_unspecified:
583 case DeclSpec::SCS_typedef:
584 case DeclSpec::SCS_static:
585 // FALL THROUGH.
586 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000587 case DeclSpec::SCS_mutable:
588 if (isFunc) {
589 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000590 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000591 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000592 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
593
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000594 // FIXME: It would be nicer if the keyword was ignored only for this
595 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000596 D.getMutableDeclSpec().ClearStorageClassSpecs();
597 } else {
598 QualType T = GetTypeForDeclarator(D, S);
599 diag::kind err = static_cast<diag::kind>(0);
600 if (T->isReferenceType())
601 err = diag::err_mutable_reference;
602 else if (T.isConstQualified())
603 err = diag::err_mutable_const;
604 if (err != 0) {
605 if (DS.getStorageClassSpecLoc().isValid())
606 Diag(DS.getStorageClassSpecLoc(), err);
607 else
608 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000609 // FIXME: It would be nicer if the keyword was ignored only for this
610 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000611 D.getMutableDeclSpec().ClearStorageClassSpecs();
612 }
613 }
614 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000615 default:
616 if (DS.getStorageClassSpecLoc().isValid())
617 Diag(DS.getStorageClassSpecLoc(),
618 diag::err_storageclass_invalid_for_member);
619 else
620 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
621 D.getMutableDeclSpec().ClearStorageClassSpecs();
622 }
623
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000624 if (!isFunc &&
Douglas Gregora60c62e2009-02-09 15:09:02 +0000625 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000626 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000627 // Check also for this case:
628 //
629 // typedef int f();
630 // f a;
631 //
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000632 QualType TDType = GetTypeFromParser(DS.getTypeRep());
Douglas Gregora60c62e2009-02-09 15:09:02 +0000633 isFunc = TDType->isFunctionType();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000634 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000635
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000636 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
637 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000638 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000639
640 Decl *Member;
Chris Lattner9cffefc2009-03-05 22:45:59 +0000641 if (isInstField) {
Douglas Gregor398a8012009-08-20 22:52:58 +0000642 // FIXME: Check for template parameters!
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000643 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
644 AS);
Chris Lattnere384c182009-03-05 23:03:49 +0000645 assert(Member && "HandleField never returns null");
Chris Lattner9cffefc2009-03-05 22:45:59 +0000646 } else {
Douglas Gregor398a8012009-08-20 22:52:58 +0000647 Member = HandleDeclarator(S, D, move(TemplateParameterLists), false)
648 .getAs<Decl>();
Chris Lattnere384c182009-03-05 23:03:49 +0000649 if (!Member) {
650 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattnera17991f2009-03-29 16:50:03 +0000651 return DeclPtrTy();
Chris Lattnere384c182009-03-05 23:03:49 +0000652 }
Chris Lattner432780c2009-03-05 23:01:03 +0000653
654 // Non-instance-fields can't have a bitfield.
655 if (BitWidth) {
656 if (Member->isInvalidDecl()) {
657 // don't emit another diagnostic.
Douglas Gregor00660582009-03-11 20:22:50 +0000658 } else if (isa<VarDecl>(Member)) {
Chris Lattner432780c2009-03-05 23:01:03 +0000659 // C++ 9.6p3: A bit-field shall not be a static member.
660 // "static member 'A' cannot be a bit-field"
661 Diag(Loc, diag::err_static_not_bitfield)
662 << Name << BitWidth->getSourceRange();
663 } else if (isa<TypedefDecl>(Member)) {
664 // "typedef member 'x' cannot be a bit-field"
665 Diag(Loc, diag::err_typedef_not_bitfield)
666 << Name << BitWidth->getSourceRange();
667 } else {
668 // A function typedef ("typedef int f(); f a;").
669 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
670 Diag(Loc, diag::err_not_integral_type_bitfield)
Douglas Gregor0e518af2009-03-11 18:59:21 +0000671 << Name << cast<ValueDecl>(Member)->getType()
672 << BitWidth->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000673 }
674
675 DeleteExpr(BitWidth);
676 BitWidth = 0;
677 Member->setInvalidDecl();
678 }
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000679
680 Member->setAccess(AS);
Douglas Gregor398a8012009-08-20 22:52:58 +0000681
682 // If we have declared a member function template, set the access of the
683 // templated declaration as well.
684 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
685 FunTmpl->getTemplatedDecl()->setAccess(AS);
Chris Lattner9cffefc2009-03-05 22:45:59 +0000686 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000687
Douglas Gregor6704b312008-11-17 22:58:34 +0000688 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000689
Douglas Gregor8f53bb72009-03-11 23:00:04 +0000690 if (Init)
Chris Lattner5261d0c2009-03-28 19:18:32 +0000691 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redla55834a2009-04-12 17:16:29 +0000692 if (Deleted) // FIXME: Source location is not very good.
693 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000694
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000695 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000696 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattnera17991f2009-03-29 16:50:03 +0000697 return DeclPtrTy();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000698 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000699 return DeclPtrTy::make(Member);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000700}
701
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000702/// ActOnMemInitializer - Handle a C++ member initializer.
703Sema::MemInitResult
Chris Lattner5261d0c2009-03-28 19:18:32 +0000704Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000705 Scope *S,
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000706 const CXXScopeSpec &SS,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000707 IdentifierInfo *MemberOrBase,
Fariborz Jahanian2b2b7362009-07-01 19:21:19 +0000708 TypeTy *TemplateTypeTy,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000709 SourceLocation IdLoc,
710 SourceLocation LParenLoc,
711 ExprTy **Args, unsigned NumArgs,
712 SourceLocation *CommaLocs,
713 SourceLocation RParenLoc) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000714 if (!ConstructorD)
715 return true;
716
Douglas Gregor84164f02009-08-24 11:57:43 +0000717 AdjustDeclIfTemplate(ConstructorD);
718
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000719 CXXConstructorDecl *Constructor
Chris Lattner5261d0c2009-03-28 19:18:32 +0000720 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000721 if (!Constructor) {
722 // The user wrote a constructor initializer on a function that is
723 // not a C++ constructor. Ignore the error for now, because we may
724 // have more member initializers coming; we'll diagnose it just
725 // once in ActOnMemInitializers.
726 return true;
727 }
728
729 CXXRecordDecl *ClassDecl = Constructor->getParent();
730
731 // C++ [class.base.init]p2:
732 // Names in a mem-initializer-id are looked up in the scope of the
733 // constructor’s class and, if not found in that scope, are looked
734 // up in the scope containing the constructor’s
735 // definition. [Note: if the constructor’s class contains a member
736 // with the same name as a direct or virtual base class of the
737 // class, a mem-initializer-id naming the member or base class and
738 // composed of a single identifier refers to the class member. A
739 // mem-initializer-id for the hidden base class may be specified
740 // using a qualified name. ]
Fariborz Jahanian2b2b7362009-07-01 19:21:19 +0000741 if (!SS.getScopeRep() && !TemplateTypeTy) {
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000742 // Look for a member, first.
743 FieldDecl *Member = 0;
744 DeclContext::lookup_result Result
745 = ClassDecl->lookup(MemberOrBase);
746 if (Result.first != Result.second)
747 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000748
Fariborz Jahanianc37d3062009-06-30 23:26:25 +0000749 // FIXME: Handle members of an anonymous union.
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000750
Eli Friedman724478c2009-07-29 19:44:27 +0000751 if (Member)
752 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
753 RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000754 }
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000755 // It didn't name a member, so see if it names a class.
Fariborz Jahanian2b2b7362009-07-01 19:21:19 +0000756 TypeTy *BaseTy = TemplateTypeTy ? TemplateTypeTy
757 : getTypeName(*MemberOrBase, IdLoc, S, &SS);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000758 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000759 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
760 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000761
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +0000762 QualType BaseType = GetTypeFromParser(BaseTy);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000763
Eli Friedman724478c2009-07-29 19:44:27 +0000764 return BuildBaseInitializer(BaseType, (Expr **)Args, NumArgs, IdLoc,
765 RParenLoc, ClassDecl);
766}
767
768Sema::MemInitResult
769Sema::BuildMemberInitializer(FieldDecl *Member, Expr **Args,
770 unsigned NumArgs, SourceLocation IdLoc,
771 SourceLocation RParenLoc) {
772 bool HasDependentArg = false;
773 for (unsigned i = 0; i < NumArgs; i++)
774 HasDependentArg |= Args[i]->isTypeDependent();
775
776 CXXConstructorDecl *C = 0;
777 QualType FieldType = Member->getType();
778 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
779 FieldType = Array->getElementType();
780 if (FieldType->isDependentType()) {
781 // Can't check init for dependent type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000782 } else if (FieldType->getAs<RecordType>()) {
Eli Friedman724478c2009-07-29 19:44:27 +0000783 if (!HasDependentArg)
784 C = PerformInitializationByConstructor(
785 FieldType, (Expr **)Args, NumArgs, IdLoc,
786 SourceRange(IdLoc, RParenLoc), Member->getDeclName(), IK_Direct);
787 } else if (NumArgs != 1) {
788 return Diag(IdLoc, diag::err_mem_initializer_mismatch)
789 << Member->getDeclName() << SourceRange(IdLoc, RParenLoc);
790 } else if (!HasDependentArg) {
791 Expr *NewExp = (Expr*)Args[0];
792 if (PerformCopyInitialization(NewExp, FieldType, "passing"))
793 return true;
794 Args[0] = NewExp;
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000795 }
Eli Friedman724478c2009-07-29 19:44:27 +0000796 // FIXME: Perform direct initialization of the member.
797 return new (Context) CXXBaseOrMemberInitializer(Member, (Expr **)Args,
798 NumArgs, C, IdLoc);
799}
800
801Sema::MemInitResult
802Sema::BuildBaseInitializer(QualType BaseType, Expr **Args,
803 unsigned NumArgs, SourceLocation IdLoc,
804 SourceLocation RParenLoc, CXXRecordDecl *ClassDecl) {
805 bool HasDependentArg = false;
806 for (unsigned i = 0; i < NumArgs; i++)
807 HasDependentArg |= Args[i]->isTypeDependent();
808
809 if (!BaseType->isDependentType()) {
810 if (!BaseType->isRecordType())
811 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
812 << BaseType << SourceRange(IdLoc, RParenLoc);
813
814 // C++ [class.base.init]p2:
815 // [...] Unless the mem-initializer-id names a nonstatic data
816 // member of the constructor’s class or a direct or virtual base
817 // of that class, the mem-initializer is ill-formed. A
818 // mem-initializer-list can initialize a base class using any
819 // name that denotes that base class type.
820
821 // First, check for a direct base class.
822 const CXXBaseSpecifier *DirectBaseSpec = 0;
823 for (CXXRecordDecl::base_class_const_iterator Base =
824 ClassDecl->bases_begin(); Base != ClassDecl->bases_end(); ++Base) {
825 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
826 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
827 // We found a direct base of this type. That's what we're
828 // initializing.
829 DirectBaseSpec = &*Base;
830 break;
831 }
832 }
833
834 // Check for a virtual base class.
835 // FIXME: We might be able to short-circuit this if we know in advance that
836 // there are no virtual bases.
837 const CXXBaseSpecifier *VirtualBaseSpec = 0;
838 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
839 // We haven't found a base yet; search the class hierarchy for a
840 // virtual base class.
841 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
842 /*DetectVirtual=*/false);
843 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
844 for (BasePaths::paths_iterator Path = Paths.begin();
845 Path != Paths.end(); ++Path) {
846 if (Path->back().Base->isVirtual()) {
847 VirtualBaseSpec = Path->back().Base;
848 break;
849 }
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000850 }
851 }
852 }
Eli Friedman724478c2009-07-29 19:44:27 +0000853
854 // C++ [base.class.init]p2:
855 // If a mem-initializer-id is ambiguous because it designates both
856 // a direct non-virtual base class and an inherited virtual base
857 // class, the mem-initializer is ill-formed.
858 if (DirectBaseSpec && VirtualBaseSpec)
859 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
860 << BaseType << SourceRange(IdLoc, RParenLoc);
861 // C++ [base.class.init]p2:
862 // Unless the mem-initializer-id names a nonstatic data membeer of the
863 // constructor's class ot a direst or virtual base of that class, the
864 // mem-initializer is ill-formed.
865 if (!DirectBaseSpec && !VirtualBaseSpec)
866 return Diag(IdLoc, diag::err_not_direct_base_or_virtual)
867 << BaseType << ClassDecl->getNameAsCString()
868 << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000869 }
870
Fariborz Jahanian898f5742009-07-23 00:42:24 +0000871 CXXConstructorDecl *C = 0;
Eli Friedman724478c2009-07-29 19:44:27 +0000872 if (!BaseType->isDependentType() && !HasDependentArg) {
873 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(
874 Context.getCanonicalType(BaseType));
875 C = PerformInitializationByConstructor(BaseType, (Expr **)Args, NumArgs,
876 IdLoc, SourceRange(IdLoc, RParenLoc),
877 Name, IK_Direct);
878 }
879
880 return new (Context) CXXBaseOrMemberInitializer(BaseType, (Expr **)Args,
Fariborz Jahanian898f5742009-07-23 00:42:24 +0000881 NumArgs, C, IdLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000882}
883
Fariborz Jahanian7c1771c2009-07-23 23:32:59 +0000884void
885Sema::BuildBaseOrMemberInitializers(ASTContext &C,
886 CXXConstructorDecl *Constructor,
887 CXXBaseOrMemberInitializer **Initializers,
888 unsigned NumInitializers
889 ) {
890 llvm::SmallVector<CXXBaseSpecifier *, 4>Bases;
891 llvm::SmallVector<FieldDecl *, 4>Members;
892
893 Constructor->setBaseOrMemberInitializers(C,
894 Initializers, NumInitializers,
895 Bases, Members);
896 for (unsigned int i = 0; i < Bases.size(); i++)
897 Diag(Bases[i]->getSourceRange().getBegin(),
898 diag::err_missing_default_constructor) << 0 << Bases[i]->getType();
899 for (unsigned int i = 0; i < Members.size(); i++)
900 Diag(Members[i]->getLocation(), diag::err_missing_default_constructor)
901 << 1 << Members[i]->getType();
902}
903
Eli Friedman16a1ca72009-07-21 19:28:10 +0000904static void *GetKeyForTopLevelField(FieldDecl *Field) {
905 // For anonymous unions, use the class declaration as the key.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000906 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
Eli Friedman16a1ca72009-07-21 19:28:10 +0000907 if (RT->getDecl()->isAnonymousStructOrUnion())
908 return static_cast<void *>(RT->getDecl());
909 }
910 return static_cast<void *>(Field);
911}
912
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +0000913static void *GetKeyForMember(CXXBaseOrMemberInitializer *Member,
914 bool MemberMaybeAnon=false) {
Eli Friedman16a1ca72009-07-21 19:28:10 +0000915 // For fields injected into the class via declaration of an anonymous union,
916 // use its anonymous union class declaration as the unique key.
917 if (FieldDecl *Field = Member->getMember()) {
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +0000918 // After BuildBaseOrMemberInitializers call, Field is the anonymous union
919 // data member of the class. Data member used in the initializer list is
920 // in AnonUnionMember field.
921 if (MemberMaybeAnon && Field->isAnonymousStructOrUnion())
922 Field = Member->getAnonUnionMember();
Eli Friedman16a1ca72009-07-21 19:28:10 +0000923 if (Field->getDeclContext()->isRecord()) {
924 RecordDecl *RD = cast<RecordDecl>(Field->getDeclContext());
925 if (RD->isAnonymousStructOrUnion())
926 return static_cast<void *>(RD);
927 }
928 return static_cast<void *>(Field);
929 }
930 return static_cast<RecordType *>(Member->getBaseClass());
931}
932
Chris Lattner5261d0c2009-03-28 19:18:32 +0000933void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssonc7f87202009-03-25 02:58:17 +0000934 SourceLocation ColonLoc,
935 MemInitTy **MemInits, unsigned NumMemInits) {
Douglas Gregorac77dd62009-06-22 23:20:33 +0000936 if (!ConstructorDecl)
937 return;
Douglas Gregor84164f02009-08-24 11:57:43 +0000938
939 AdjustDeclIfTemplate(ConstructorDecl);
Douglas Gregorac77dd62009-06-22 23:20:33 +0000940
941 CXXConstructorDecl *Constructor
942 = dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Anders Carlssonc7f87202009-03-25 02:58:17 +0000943
944 if (!Constructor) {
945 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
946 return;
947 }
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000948 llvm::DenseMap<void*, CXXBaseOrMemberInitializer *>Members;
Fariborz Jahanianbb70eb32009-07-01 23:35:25 +0000949 bool err = false;
Fariborz Jahanian4e0aba82009-06-29 22:33:26 +0000950 for (unsigned i = 0; i < NumMemInits; i++) {
951 CXXBaseOrMemberInitializer *Member =
952 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
Eli Friedman16a1ca72009-07-21 19:28:10 +0000953 void *KeyToMember = GetKeyForMember(Member);
Fariborz Jahanianf75b9d52009-06-30 21:52:59 +0000954 CXXBaseOrMemberInitializer *&PrevMember = Members[KeyToMember];
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000955 if (!PrevMember) {
Fariborz Jahanian89f61bd2009-06-30 00:02:17 +0000956 PrevMember = Member;
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000957 continue;
Fariborz Jahanian4e0aba82009-06-29 22:33:26 +0000958 }
Fariborz Jahanian4b61ba62009-06-30 00:17:27 +0000959 if (FieldDecl *Field = Member->getMember())
960 Diag(Member->getSourceLocation(),
961 diag::error_multiple_mem_initialization)
962 << Field->getNameAsString();
963 else {
964 Type *BaseClass = Member->getBaseClass();
965 assert(BaseClass && "ActOnMemInitializers - neither field or base");
966 Diag(Member->getSourceLocation(),
967 diag::error_multiple_base_initialization)
968 << BaseClass->getDesugaredType(true);
969 }
970 Diag(PrevMember->getSourceLocation(), diag::note_previous_initializer)
971 << 0;
Fariborz Jahanianbb70eb32009-07-01 23:35:25 +0000972 err = true;
Fariborz Jahanian4e0aba82009-06-29 22:33:26 +0000973 }
Fariborz Jahanian7c1771c2009-07-23 23:32:59 +0000974 if (!err)
975 BuildBaseOrMemberInitializers(Context, Constructor,
976 reinterpret_cast<CXXBaseOrMemberInitializer **>(MemInits),
977 NumMemInits);
978
Eli Friedman16a1ca72009-07-21 19:28:10 +0000979 if (!err && (Diags.getDiagnosticLevel(diag::warn_base_initialized)
980 != Diagnostic::Ignored ||
981 Diags.getDiagnosticLevel(diag::warn_field_initialized)
982 != Diagnostic::Ignored)) {
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +0000983 // Also issue warning if order of ctor-initializer list does not match order
984 // of 1) base class declarations and 2) order of non-static data members.
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +0000985 llvm::SmallVector<const void*, 32> AllBaseOrMembers;
986
987 CXXRecordDecl *ClassDecl
988 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanianc1ce61b2009-07-10 20:13:23 +0000989 // Push virtual bases before others.
990 for (CXXRecordDecl::base_class_iterator VBase =
991 ClassDecl->vbases_begin(),
992 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000993 AllBaseOrMembers.push_back(VBase->getType()->getAs<RecordType>());
Fariborz Jahanianc1ce61b2009-07-10 20:13:23 +0000994
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +0000995 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
Fariborz Jahanianc1ce61b2009-07-10 20:13:23 +0000996 E = ClassDecl->bases_end(); Base != E; ++Base) {
997 // Virtuals are alread in the virtual base list and are constructed
998 // first.
999 if (Base->isVirtual())
1000 continue;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001001 AllBaseOrMembers.push_back(Base->getType()->getAs<RecordType>());
Fariborz Jahanianc1ce61b2009-07-10 20:13:23 +00001002 }
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001003
1004 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
1005 E = ClassDecl->field_end(); Field != E; ++Field)
Eli Friedman16a1ca72009-07-21 19:28:10 +00001006 AllBaseOrMembers.push_back(GetKeyForTopLevelField(*Field));
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001007
1008 int Last = AllBaseOrMembers.size();
1009 int curIndex = 0;
1010 CXXBaseOrMemberInitializer *PrevMember = 0;
1011 for (unsigned i = 0; i < NumMemInits; i++) {
1012 CXXBaseOrMemberInitializer *Member =
1013 static_cast<CXXBaseOrMemberInitializer*>(MemInits[i]);
Fariborz Jahanianfef75cb2009-08-11 18:49:54 +00001014 void *MemberInCtorList = GetKeyForMember(Member, true);
Eli Friedman16a1ca72009-07-21 19:28:10 +00001015
1016 for (; curIndex < Last; curIndex++)
1017 if (MemberInCtorList == AllBaseOrMembers[curIndex])
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001018 break;
Eli Friedman16a1ca72009-07-21 19:28:10 +00001019 if (curIndex == Last) {
1020 assert(PrevMember && "Member not in member list?!");
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001021 // Initializer as specified in ctor-initializer list is out of order.
1022 // Issue a warning diagnostic.
1023 if (PrevMember->isBaseInitializer()) {
1024 // Diagnostics is for an initialized base class.
1025 Type *BaseClass = PrevMember->getBaseClass();
1026 Diag(PrevMember->getSourceLocation(),
1027 diag::warn_base_initialized)
1028 << BaseClass->getDesugaredType(true);
Mike Stump90fc78e2009-08-04 21:02:39 +00001029 } else {
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001030 FieldDecl *Field = PrevMember->getMember();
1031 Diag(PrevMember->getSourceLocation(),
1032 diag::warn_field_initialized)
1033 << Field->getNameAsString();
1034 }
1035 // Also the note!
1036 if (FieldDecl *Field = Member->getMember())
1037 Diag(Member->getSourceLocation(),
1038 diag::note_fieldorbase_initialized_here) << 0
1039 << Field->getNameAsString();
1040 else {
1041 Type *BaseClass = Member->getBaseClass();
1042 Diag(Member->getSourceLocation(),
1043 diag::note_fieldorbase_initialized_here) << 1
1044 << BaseClass->getDesugaredType(true);
1045 }
Eli Friedman16a1ca72009-07-21 19:28:10 +00001046 for (curIndex = 0; curIndex < Last; curIndex++)
1047 if (MemberInCtorList == AllBaseOrMembers[curIndex])
1048 break;
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001049 }
1050 PrevMember = Member;
Fariborz Jahaniancca8d8d2009-07-09 19:59:47 +00001051 }
1052 }
Anders Carlssonc7f87202009-03-25 02:58:17 +00001053}
1054
Fariborz Jahanian4e127232009-07-21 22:36:06 +00001055void Sema::ActOnDefaultCtorInitializers(DeclPtrTy CDtorDecl) {
Fariborz Jahanian21e25e72009-07-15 22:34:08 +00001056 if (!CDtorDecl)
Fariborz Jahanian9294d192009-07-14 18:24:21 +00001057 return;
1058
Douglas Gregor84164f02009-08-24 11:57:43 +00001059 AdjustDeclIfTemplate(CDtorDecl);
1060
Fariborz Jahanian9294d192009-07-14 18:24:21 +00001061 if (CXXConstructorDecl *Constructor
Fariborz Jahanian21e25e72009-07-15 22:34:08 +00001062 = dyn_cast<CXXConstructorDecl>(CDtorDecl.getAs<Decl>()))
Fariborz Jahanian7c1771c2009-07-23 23:32:59 +00001063 BuildBaseOrMemberInitializers(Context,
1064 Constructor,
1065 (CXXBaseOrMemberInitializer **)0, 0);
Fariborz Jahanian9294d192009-07-14 18:24:21 +00001066}
1067
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001068namespace {
1069 /// PureVirtualMethodCollector - traverses a class and its superclasses
1070 /// and determines if it has any pure virtual methods.
1071 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
1072 ASTContext &Context;
1073
Sebastian Redl16ac38f2009-03-22 21:28:55 +00001074 public:
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001075 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redl16ac38f2009-03-22 21:28:55 +00001076
1077 private:
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001078 MethodList Methods;
1079
1080 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
1081
1082 public:
1083 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
1084 : Context(Ctx) {
1085
1086 MethodList List;
1087 Collect(RD, List);
1088
1089 // Copy the temporary list to methods, and make sure to ignore any
1090 // null entries.
1091 for (size_t i = 0, e = List.size(); i != e; ++i) {
1092 if (List[i])
1093 Methods.push_back(List[i]);
1094 }
1095 }
1096
Anders Carlssone1299b32009-03-22 20:18:17 +00001097 bool empty() const { return Methods.empty(); }
1098
1099 MethodList::const_iterator methods_begin() { return Methods.begin(); }
1100 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001101 };
1102
1103 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
1104 MethodList& Methods) {
1105 // First, collect the pure virtual methods for the base classes.
1106 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
1107 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001108 if (const RecordType *RT = Base->getType()->getAs<RecordType>()) {
Chris Lattner330a05b2009-03-29 05:01:10 +00001109 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001110 if (BaseDecl && BaseDecl->isAbstract())
1111 Collect(BaseDecl, Methods);
1112 }
1113 }
1114
1115 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001116 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
1117
1118 MethodSetTy OverriddenMethods;
1119 size_t MethodsSize = Methods.size();
1120
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001121 for (RecordDecl::decl_iterator i = RD->decls_begin(), e = RD->decls_end();
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001122 i != e; ++i) {
1123 // Traverse the record, looking for methods.
1124 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
Sebastian Redl953d12a2009-07-07 20:29:57 +00001125 // If the method is pure virtual, add it to the methods vector.
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001126 if (MD->isPure()) {
1127 Methods.push_back(MD);
1128 continue;
1129 }
1130
1131 // Otherwise, record all the overridden methods in our set.
1132 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
1133 E = MD->end_overridden_methods(); I != E; ++I) {
1134 // Keep track of the overridden methods.
1135 OverriddenMethods.insert(*I);
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001136 }
1137 }
1138 }
1139
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001140 // Now go through the methods and zero out all the ones we know are
1141 // overridden.
1142 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
1143 if (OverriddenMethods.count(Methods[i]))
1144 Methods[i] = 0;
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001145 }
Anders Carlsson1eba0ac2009-05-17 00:00:05 +00001146
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001147 }
1148}
Douglas Gregora65e8dd2008-11-05 04:29:56 +00001149
Anders Carlssone1299b32009-03-22 20:18:17 +00001150bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonde9e7892009-03-24 17:23:42 +00001151 unsigned DiagID, AbstractDiagSelID SelID,
1152 const CXXRecordDecl *CurrentRD) {
Anders Carlssone1299b32009-03-22 20:18:17 +00001153
1154 if (!getLangOptions().CPlusPlus)
1155 return false;
Anders Carlssonc263c9b2009-03-23 19:10:31 +00001156
1157 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssonde9e7892009-03-24 17:23:42 +00001158 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
1159 CurrentRD);
Anders Carlssonce9240e2009-03-24 01:46:45 +00001160
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001161 if (const PointerType *PT = T->getAs<PointerType>()) {
Anders Carlssonce9240e2009-03-24 01:46:45 +00001162 // Find the innermost pointer type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001163 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
Anders Carlssonce9240e2009-03-24 01:46:45 +00001164 PT = T;
Anders Carlssone1299b32009-03-22 20:18:17 +00001165
Anders Carlssonce9240e2009-03-24 01:46:45 +00001166 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssonde9e7892009-03-24 17:23:42 +00001167 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
1168 CurrentRD);
Anders Carlssonce9240e2009-03-24 01:46:45 +00001169 }
1170
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001171 const RecordType *RT = T->getAs<RecordType>();
Anders Carlssone1299b32009-03-22 20:18:17 +00001172 if (!RT)
1173 return false;
1174
1175 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
1176 if (!RD)
1177 return false;
1178
Anders Carlssonde9e7892009-03-24 17:23:42 +00001179 if (CurrentRD && CurrentRD != RD)
1180 return false;
1181
Anders Carlssone1299b32009-03-22 20:18:17 +00001182 if (!RD->isAbstract())
1183 return false;
1184
Anders Carlssond5a94982009-03-23 17:49:10 +00001185 Diag(Loc, DiagID) << RD->getDeclName() << SelID;
Anders Carlssone1299b32009-03-22 20:18:17 +00001186
1187 // Check if we've already emitted the list of pure virtual functions for this
1188 // class.
1189 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
1190 return true;
1191
1192 PureVirtualMethodCollector Collector(Context, RD);
1193
1194 for (PureVirtualMethodCollector::MethodList::const_iterator I =
1195 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
1196 const CXXMethodDecl *MD = *I;
1197
1198 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
1199 MD->getDeclName();
1200 }
1201
1202 if (!PureVirtualClassDiagSet)
1203 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
1204 PureVirtualClassDiagSet->insert(RD);
1205
1206 return true;
1207}
1208
Anders Carlsson412c3402009-03-24 01:19:16 +00001209namespace {
1210 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
1211 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
1212 Sema &SemaRef;
1213 CXXRecordDecl *AbstractClass;
1214
Anders Carlssonde9e7892009-03-24 17:23:42 +00001215 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson412c3402009-03-24 01:19:16 +00001216 bool Invalid = false;
1217
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001218 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(),
1219 E = DC->decls_end(); I != E; ++I)
Anders Carlsson412c3402009-03-24 01:19:16 +00001220 Invalid |= Visit(*I);
Anders Carlssonde9e7892009-03-24 17:23:42 +00001221
Anders Carlsson412c3402009-03-24 01:19:16 +00001222 return Invalid;
1223 }
Anders Carlssonde9e7892009-03-24 17:23:42 +00001224
1225 public:
1226 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
1227 : SemaRef(SemaRef), AbstractClass(ac) {
1228 Visit(SemaRef.Context.getTranslationUnitDecl());
1229 }
Anders Carlsson412c3402009-03-24 01:19:16 +00001230
Anders Carlssonde9e7892009-03-24 17:23:42 +00001231 bool VisitFunctionDecl(const FunctionDecl *FD) {
1232 if (FD->isThisDeclarationADefinition()) {
1233 // No need to do the check if we're in a definition, because it requires
1234 // that the return/param types are complete.
1235 // because that requires
1236 return VisitDeclContext(FD);
1237 }
1238
1239 // Check the return type.
1240 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
1241 bool Invalid =
1242 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
1243 diag::err_abstract_type_in_decl,
1244 Sema::AbstractReturnType,
1245 AbstractClass);
1246
1247 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
1248 E = FD->param_end(); I != E; ++I) {
Anders Carlsson412c3402009-03-24 01:19:16 +00001249 const ParmVarDecl *VD = *I;
1250 Invalid |=
1251 SemaRef.RequireNonAbstractType(VD->getLocation(),
1252 VD->getOriginalType(),
1253 diag::err_abstract_type_in_decl,
Anders Carlssonde9e7892009-03-24 17:23:42 +00001254 Sema::AbstractParamType,
1255 AbstractClass);
Anders Carlsson412c3402009-03-24 01:19:16 +00001256 }
1257
1258 return Invalid;
1259 }
Anders Carlssonde9e7892009-03-24 17:23:42 +00001260
1261 bool VisitDecl(const Decl* D) {
1262 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
1263 return VisitDeclContext(DC);
1264
1265 return false;
1266 }
Anders Carlsson412c3402009-03-24 01:19:16 +00001267 };
1268}
1269
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001270void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001271 DeclPtrTy TagDecl,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001272 SourceLocation LBrac,
1273 SourceLocation RBrac) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001274 if (!TagDecl)
1275 return;
1276
Douglas Gregor3eb20702009-05-11 19:58:34 +00001277 AdjustDeclIfTemplate(TagDecl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001278 ActOnFields(S, RLoc, TagDecl,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001279 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +00001280 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregored3a3982009-03-03 04:44:36 +00001281
Chris Lattner5261d0c2009-03-28 19:18:32 +00001282 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001283 if (!RD->isAbstract()) {
1284 // Collect all the pure virtual methods and see if this is an abstract
1285 // class after all.
1286 PureVirtualMethodCollector Collector(Context, RD);
1287 if (!Collector.empty())
1288 RD->setAbstract(true);
1289 }
1290
Anders Carlssonde9e7892009-03-24 17:23:42 +00001291 if (RD->isAbstract())
1292 AbstractClassUsageDiagnoser(*this, RD);
Anders Carlsson412c3402009-03-24 01:19:16 +00001293
Douglas Gregor3eb20702009-05-11 19:58:34 +00001294 if (!RD->isDependentType())
Anders Carlsson1dae87f2009-03-22 01:52:17 +00001295 AddImplicitlyDeclaredMembersToClass(RD);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001296}
1297
Douglas Gregore640ab62008-11-03 17:51:48 +00001298/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1299/// special functions, such as the default constructor, copy
1300/// constructor, or destructor, to the given C++ class (C++
1301/// [special]p1). This routine can only be executed just before the
1302/// definition of the class is complete.
1303void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregorcfe6ae52009-08-05 05:36:45 +00001304 CanQualType ClassType
1305 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001306
Sebastian Redl2767d882009-05-27 22:11:52 +00001307 // FIXME: Implicit declarations have exception specifications, which are
1308 // the union of the specifications of the implicitly called functions.
1309
Douglas Gregore640ab62008-11-03 17:51:48 +00001310 if (!ClassDecl->hasUserDeclaredConstructor()) {
1311 // C++ [class.ctor]p5:
1312 // A default constructor for a class X is a constructor of class X
1313 // that can be called without an argument. If there is no
1314 // user-declared constructor for class X, a default constructor is
1315 // implicitly declared. An implicitly-declared default constructor
1316 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001317 DeclarationName Name
1318 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001319 CXXConstructorDecl *DefaultCon =
1320 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001321 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +00001322 Context.getFunctionType(Context.VoidTy,
1323 0, 0, false, 0),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001324 /*DInfo=*/0,
Douglas Gregore640ab62008-11-03 17:51:48 +00001325 /*isExplicit=*/false,
1326 /*isInline=*/true,
1327 /*isImplicitlyDeclared=*/true);
1328 DefaultCon->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001329 DefaultCon->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001330 DefaultCon->setTrivial(ClassDecl->hasTrivialConstructor());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001331 ClassDecl->addDecl(DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +00001332 }
1333
1334 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1335 // C++ [class.copy]p4:
1336 // If the class definition does not explicitly declare a copy
1337 // constructor, one is declared implicitly.
1338
1339 // C++ [class.copy]p5:
1340 // The implicitly-declared copy constructor for a class X will
1341 // have the form
1342 //
1343 // X::X(const X&)
1344 //
1345 // if
1346 bool HasConstCopyConstructor = true;
1347
1348 // -- each direct or virtual base class B of X has a copy
1349 // constructor whose first parameter is of type const B& or
1350 // const volatile B&, and
1351 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1352 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1353 const CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001354 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Douglas Gregore640ab62008-11-03 17:51:48 +00001355 HasConstCopyConstructor
1356 = BaseClassDecl->hasConstCopyConstructor(Context);
1357 }
1358
1359 // -- for all the nonstatic data members of X that are of a
1360 // class type M (or array thereof), each such class type
1361 // has a copy constructor whose first parameter is of type
1362 // const M& or const volatile M&.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001363 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1364 HasConstCopyConstructor && Field != ClassDecl->field_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001365 ++Field) {
Douglas Gregore640ab62008-11-03 17:51:48 +00001366 QualType FieldType = (*Field)->getType();
1367 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1368 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001369 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Douglas Gregore640ab62008-11-03 17:51:48 +00001370 const CXXRecordDecl *FieldClassDecl
1371 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1372 HasConstCopyConstructor
1373 = FieldClassDecl->hasConstCopyConstructor(Context);
1374 }
1375 }
1376
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001377 // Otherwise, the implicitly declared copy constructor will have
1378 // the form
Douglas Gregore640ab62008-11-03 17:51:48 +00001379 //
1380 // X::X(X&)
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001381 QualType ArgType = ClassType;
Douglas Gregore640ab62008-11-03 17:51:48 +00001382 if (HasConstCopyConstructor)
1383 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +00001384 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001385
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001386 // An implicitly-declared copy constructor is an inline public
1387 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001388 DeclarationName Name
1389 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001390 CXXConstructorDecl *CopyConstructor
1391 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001392 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +00001393 Context.getFunctionType(Context.VoidTy,
1394 &ArgType, 1,
1395 false, 0),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001396 /*DInfo=*/0,
Douglas Gregore640ab62008-11-03 17:51:48 +00001397 /*isExplicit=*/false,
1398 /*isInline=*/true,
1399 /*isImplicitlyDeclared=*/true);
1400 CopyConstructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001401 CopyConstructor->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001402 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
Douglas Gregore640ab62008-11-03 17:51:48 +00001403
1404 // Add the parameter to the constructor.
1405 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1406 ClassDecl->getLocation(),
1407 /*IdentifierInfo=*/0,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001408 ArgType, /*DInfo=*/0,
1409 VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001410 CopyConstructor->setParams(Context, &FromParam, 1);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001411 ClassDecl->addDecl(CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +00001412 }
1413
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001414 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1415 // Note: The following rules are largely analoguous to the copy
1416 // constructor rules. Note that virtual bases are not taken into account
1417 // for determining the argument type of the operator. Note also that
1418 // operators taking an object instead of a reference are allowed.
1419 //
1420 // C++ [class.copy]p10:
1421 // If the class definition does not explicitly declare a copy
1422 // assignment operator, one is declared implicitly.
1423 // The implicitly-defined copy assignment operator for a class X
1424 // will have the form
1425 //
1426 // X& X::operator=(const X&)
1427 //
1428 // if
1429 bool HasConstCopyAssignment = true;
1430
1431 // -- each direct base class B of X has a copy assignment operator
1432 // whose parameter is of type const B&, const volatile B& or B,
1433 // and
1434 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1435 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1436 const CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001437 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian04500242009-08-12 23:34:46 +00001438 const CXXMethodDecl *MD = 0;
1439 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context,
1440 MD);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001441 }
1442
1443 // -- for all the nonstatic data members of X that are of a class
1444 // type M (or array thereof), each such class type has a copy
1445 // assignment operator whose parameter is of type const M&,
1446 // const volatile M& or M.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001447 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
1448 HasConstCopyAssignment && Field != ClassDecl->field_end();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001449 ++Field) {
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001450 QualType FieldType = (*Field)->getType();
1451 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1452 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001453 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001454 const CXXRecordDecl *FieldClassDecl
1455 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Fariborz Jahanian04500242009-08-12 23:34:46 +00001456 const CXXMethodDecl *MD = 0;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001457 HasConstCopyAssignment
Fariborz Jahanian04500242009-08-12 23:34:46 +00001458 = FieldClassDecl->hasConstCopyAssignment(Context, MD);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001459 }
1460 }
1461
1462 // Otherwise, the implicitly declared copy assignment operator will
1463 // have the form
1464 //
1465 // X& X::operator=(X&)
1466 QualType ArgType = ClassType;
Sebastian Redlce6fff02009-03-16 23:22:08 +00001467 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001468 if (HasConstCopyAssignment)
1469 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +00001470 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001471
1472 // An implicitly-declared copy assignment operator is an inline public
1473 // member of its class.
1474 DeclarationName Name =
1475 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1476 CXXMethodDecl *CopyAssignment =
1477 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1478 Context.getFunctionType(RetType, &ArgType, 1,
1479 false, 0),
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001480 /*DInfo=*/0, /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001481 CopyAssignment->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001482 CopyAssignment->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001483 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
Fariborz Jahanian651efb72009-08-12 21:14:35 +00001484 CopyAssignment->setCopyAssignment(true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001485
1486 // Add the parameter to the operator.
1487 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1488 ClassDecl->getLocation(),
1489 /*IdentifierInfo=*/0,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00001490 ArgType, /*DInfo=*/0,
1491 VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001492 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001493
1494 // Don't call addedAssignmentOperator. There is no way to distinguish an
1495 // implicit from an explicit assignment operator.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001496 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001497 }
1498
Douglas Gregorb9213832008-12-15 21:24:18 +00001499 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001500 // C++ [class.dtor]p2:
1501 // If a class has no user-declared destructor, a destructor is
1502 // declared implicitly. An implicitly-declared destructor is an
1503 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001504 DeclarationName Name
1505 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001506 CXXDestructorDecl *Destructor
1507 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001508 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001509 Context.getFunctionType(Context.VoidTy,
1510 0, 0, false, 0),
1511 /*isInline=*/true,
1512 /*isImplicitlyDeclared=*/true);
1513 Destructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001514 Destructor->setImplicit();
Douglas Gregorf73c8512009-07-22 18:25:24 +00001515 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00001516 ClassDecl->addDecl(Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001517 }
Douglas Gregore640ab62008-11-03 17:51:48 +00001518}
1519
Douglas Gregora376cbd2009-05-27 23:11:45 +00001520void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1521 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1522 if (!Template)
1523 return;
1524
1525 TemplateParameterList *Params = Template->getTemplateParameters();
1526 for (TemplateParameterList::iterator Param = Params->begin(),
1527 ParamEnd = Params->end();
1528 Param != ParamEnd; ++Param) {
1529 NamedDecl *Named = cast<NamedDecl>(*Param);
1530 if (Named->getDeclName()) {
1531 S->AddDecl(DeclPtrTy::make(Named));
1532 IdResolver.AddDecl(Named);
1533 }
1534 }
1535}
1536
Douglas Gregor605de8d2008-12-16 21:30:33 +00001537/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1538/// parsing a top-level (non-nested) C++ class, and we are now
1539/// parsing those parts of the given Method declaration that could
1540/// not be parsed earlier (C++ [class.mem]p2), such as default
1541/// arguments. This action should enter the scope of the given
1542/// Method declaration as if we had just parsed the qualified method
1543/// name. However, it should not bring the parameters into scope;
1544/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001545void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001546 if (!MethodD)
1547 return;
1548
Douglas Gregor84164f02009-08-24 11:57:43 +00001549 AdjustDeclIfTemplate(MethodD);
1550
Douglas Gregor605de8d2008-12-16 21:30:33 +00001551 CXXScopeSpec SS;
Chris Lattner5261d0c2009-03-28 19:18:32 +00001552 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001553 QualType ClassTy
1554 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1555 SS.setScopeRep(
1556 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001557 ActOnCXXEnterDeclaratorScope(S, SS);
1558}
1559
1560/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1561/// C++ method declaration. We're (re-)introducing the given
1562/// function parameter into scope for use in parsing later parts of
1563/// the method declaration. For example, we could see an
1564/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001565void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001566 if (!ParamD)
1567 return;
1568
Chris Lattner5261d0c2009-03-28 19:18:32 +00001569 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001570
1571 // If this parameter has an unparsed default argument, clear it out
1572 // to make way for the parsed default argument.
1573 if (Param->hasUnparsedDefaultArg())
1574 Param->setDefaultArg(0);
1575
Chris Lattner5261d0c2009-03-28 19:18:32 +00001576 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001577 if (Param->getDeclName())
1578 IdResolver.AddDecl(Param);
1579}
1580
1581/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1582/// processing the delayed method declaration for Method. The method
1583/// declaration is now considered finished. There may be a separate
1584/// ActOnStartOfFunctionDef action later (not necessarily
1585/// immediately!) for this method, if it was also defined inside the
1586/// class body.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001587void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregorac77dd62009-06-22 23:20:33 +00001588 if (!MethodD)
1589 return;
1590
Douglas Gregor84164f02009-08-24 11:57:43 +00001591 AdjustDeclIfTemplate(MethodD);
1592
Chris Lattner5261d0c2009-03-28 19:18:32 +00001593 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor605de8d2008-12-16 21:30:33 +00001594 CXXScopeSpec SS;
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001595 QualType ClassTy
1596 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1597 SS.setScopeRep(
1598 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001599 ActOnCXXExitDeclaratorScope(S, SS);
1600
1601 // Now that we have our default arguments, check the constructor
1602 // again. It could produce additional diagnostics or affect whether
1603 // the class has implicitly-declared destructors, among other
1604 // things.
Chris Lattner08da4772009-04-25 08:35:12 +00001605 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1606 CheckConstructor(Constructor);
Douglas Gregor605de8d2008-12-16 21:30:33 +00001607
1608 // Check the default arguments, which we may have added.
1609 if (!Method->isInvalidDecl())
1610 CheckCXXDefaultArguments(Method);
1611}
1612
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001613/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +00001614/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001615/// R. If there are any errors in the declarator, this routine will
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001616/// emit diagnostics and set the invalid bit to true. In any case, the type
1617/// will be updated to reflect a well-formed type for the constructor and
1618/// returned.
1619QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1620 FunctionDecl::StorageClass &SC) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001621 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001622
1623 // C++ [class.ctor]p3:
1624 // A constructor shall not be virtual (10.3) or static (9.4). A
1625 // constructor can be invoked for a const, volatile or const
1626 // volatile object. A constructor shall not be declared const,
1627 // volatile, or const volatile (9.3.2).
1628 if (isVirtual) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001629 if (!D.isInvalidType())
1630 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1631 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1632 << SourceRange(D.getIdentifierLoc());
1633 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001634 }
1635 if (SC == FunctionDecl::Static) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001636 if (!D.isInvalidType())
1637 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1638 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1639 << SourceRange(D.getIdentifierLoc());
1640 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001641 SC = FunctionDecl::None;
1642 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001643
1644 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1645 if (FTI.TypeQuals != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001646 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001647 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1648 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001649 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001650 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1651 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001652 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001653 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1654 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001655 }
1656
1657 // Rebuild the function type "R" without any type qualifiers (in
1658 // case any of the errors above fired) and with "void" as the
1659 // return type, since constructors don't have return types. We
1660 // *always* have to do this, because GetTypeForDeclarator will
1661 // put in a result type of "int" when none was specified.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001662 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001663 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1664 Proto->getNumArgs(),
1665 Proto->isVariadic(), 0);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001666}
1667
Douglas Gregor605de8d2008-12-16 21:30:33 +00001668/// CheckConstructor - Checks a fully-formed constructor for
1669/// well-formedness, issuing any diagnostics required. Returns true if
1670/// the constructor declarator is invalid.
Chris Lattner08da4772009-04-25 08:35:12 +00001671void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Douglas Gregor869cabf2009-03-27 04:38:56 +00001672 CXXRecordDecl *ClassDecl
1673 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1674 if (!ClassDecl)
Chris Lattner08da4772009-04-25 08:35:12 +00001675 return Constructor->setInvalidDecl();
Douglas Gregor605de8d2008-12-16 21:30:33 +00001676
1677 // C++ [class.copy]p3:
1678 // A declaration of a constructor for a class X is ill-formed if
1679 // its first parameter is of type (optionally cv-qualified) X and
1680 // either there are no other parameters or else all other
1681 // parameters have default arguments.
Douglas Gregor869cabf2009-03-27 04:38:56 +00001682 if (!Constructor->isInvalidDecl() &&
1683 ((Constructor->getNumParams() == 1) ||
1684 (Constructor->getNumParams() > 1 &&
Anders Carlssond2e57d92009-06-06 04:14:07 +00001685 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00001686 QualType ParamType = Constructor->getParamDecl(0)->getType();
1687 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1688 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00001689 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
1690 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor133d2552009-04-02 01:08:08 +00001691 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner08da4772009-04-25 08:35:12 +00001692 Constructor->setInvalidDecl();
Douglas Gregor605de8d2008-12-16 21:30:33 +00001693 }
1694 }
1695
1696 // Notify the class that we've added a constructor.
1697 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor605de8d2008-12-16 21:30:33 +00001698}
1699
Anders Carlssonfcfa2442009-04-30 23:18:11 +00001700static inline bool
1701FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
1702 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1703 FTI.ArgInfo[0].Param &&
1704 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
1705}
1706
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001707/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1708/// the well-formednes of the destructor declarator @p D with type @p
1709/// R. If there are any errors in the declarator, this routine will
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001710/// emit diagnostics and set the declarator to invalid. Even if this happens,
1711/// will be updated to reflect a well-formed type for the destructor and
1712/// returned.
1713QualType Sema::CheckDestructorDeclarator(Declarator &D,
1714 FunctionDecl::StorageClass& SC) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001715 // C++ [class.dtor]p1:
1716 // [...] A typedef-name that names a class is a class-name
1717 // (7.1.3); however, a typedef-name that names a class shall not
1718 // be used as the identifier in the declarator for a destructor
1719 // declaration.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001720 QualType DeclaratorType = GetTypeFromParser(D.getDeclaratorIdType());
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001721 if (isa<TypedefType>(DeclaratorType)) {
1722 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregora60c62e2009-02-09 15:09:02 +00001723 << DeclaratorType;
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001724 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001725 }
1726
1727 // C++ [class.dtor]p2:
1728 // A destructor is used to destroy objects of its class type. A
1729 // destructor takes no parameters, and no return type can be
1730 // specified for it (not even void). The address of a destructor
1731 // shall not be taken. A destructor shall not be static. A
1732 // destructor can be invoked for a const, volatile or const
1733 // volatile object. A destructor shall not be declared const,
1734 // volatile or const volatile (9.3.2).
1735 if (SC == FunctionDecl::Static) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001736 if (!D.isInvalidType())
1737 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1738 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1739 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001740 SC = FunctionDecl::None;
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001741 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001742 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001743 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001744 // Destructors don't have return types, but the parser will
1745 // happily parse something like:
1746 //
1747 // class X {
1748 // float ~X();
1749 // };
1750 //
1751 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001752 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1753 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1754 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001755 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001756
1757 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1758 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001759 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001760 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1761 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001762 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001763 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1764 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001765 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001766 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1767 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001768 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001769 }
1770
1771 // Make sure we don't have any parameters.
Anders Carlssonfcfa2442009-04-30 23:18:11 +00001772 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001773 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1774
1775 // Delete the parameters.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001776 FTI.freeArgs();
1777 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001778 }
1779
1780 // Make sure the destructor isn't variadic.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001781 if (FTI.isVariadic) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001782 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001783 D.setInvalidType();
1784 }
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001785
1786 // Rebuild the function type "R" without any type qualifiers or
1787 // parameters (in case any of the errors above fired) and with
1788 // "void" as the return type, since destructors don't have return
1789 // types. We *always* have to do this, because GetTypeForDeclarator
1790 // will put in a result type of "int" when none was specified.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001791 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001792}
1793
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001794/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1795/// well-formednes of the conversion function declarator @p D with
1796/// type @p R. If there are any errors in the declarator, this routine
1797/// will emit diagnostics and return true. Otherwise, it will return
1798/// false. Either way, the type @p R will be updated to reflect a
1799/// well-formed type for the conversion operator.
Chris Lattner08da4772009-04-25 08:35:12 +00001800void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001801 FunctionDecl::StorageClass& SC) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001802 // C++ [class.conv.fct]p1:
1803 // Neither parameter types nor return type can be specified. The
Eli Friedmand5a72f02009-08-05 19:21:58 +00001804 // type of a conversion function (8.3.5) is "function taking no
1805 // parameter returning conversion-type-id."
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001806 if (SC == FunctionDecl::Static) {
Chris Lattner08da4772009-04-25 08:35:12 +00001807 if (!D.isInvalidType())
1808 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1809 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1810 << SourceRange(D.getIdentifierLoc());
1811 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001812 SC = FunctionDecl::None;
1813 }
Chris Lattner08da4772009-04-25 08:35:12 +00001814 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001815 // Conversion functions don't have return types, but the parser will
1816 // happily parse something like:
1817 //
1818 // class X {
1819 // float operator bool();
1820 // };
1821 //
1822 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001823 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1824 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1825 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001826 }
1827
1828 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001829 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001830 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1831
1832 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001833 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner08da4772009-04-25 08:35:12 +00001834 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001835 }
1836
1837 // Make sure the conversion function isn't variadic.
Chris Lattner08da4772009-04-25 08:35:12 +00001838 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001839 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner08da4772009-04-25 08:35:12 +00001840 D.setInvalidType();
1841 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001842
1843 // C++ [class.conv.fct]p4:
1844 // The conversion-type-id shall not represent a function type nor
1845 // an array type.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001846 QualType ConvType = GetTypeFromParser(D.getDeclaratorIdType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001847 if (ConvType->isArrayType()) {
1848 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1849 ConvType = Context.getPointerType(ConvType);
Chris Lattner08da4772009-04-25 08:35:12 +00001850 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001851 } else if (ConvType->isFunctionType()) {
1852 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1853 ConvType = Context.getPointerType(ConvType);
Chris Lattner08da4772009-04-25 08:35:12 +00001854 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001855 }
1856
1857 // Rebuild the function type "R" without any parameters (in case any
1858 // of the errors above fired) and with the conversion type as the
1859 // return type.
1860 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001861 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001862
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001863 // C++0x explicit conversion operators.
1864 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1865 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1866 diag::warn_explicit_conversion_functions)
1867 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001868}
1869
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001870/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1871/// the declaration of the given C++ conversion function. This routine
1872/// is responsible for recording the conversion function in the C++
1873/// class, if possible.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001874Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001875 assert(Conversion && "Expected to receive a conversion function declaration");
1876
Douglas Gregor98341042008-12-12 08:25:50 +00001877 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001878
1879 // Make sure we aren't redeclaring the conversion function.
1880 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001881
1882 // C++ [class.conv.fct]p1:
1883 // [...] A conversion function is never used to convert a
1884 // (possibly cv-qualified) object to the (possibly cv-qualified)
1885 // same object type (or a reference to it), to a (possibly
1886 // cv-qualified) base class of that type (or a reference to it),
1887 // or to (possibly cv-qualified) void.
Mike Stumpe127ae32009-05-16 07:39:55 +00001888 // FIXME: Suppress this warning if the conversion function ends up being a
1889 // virtual function that overrides a virtual function in a base class.
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001890 QualType ClassType
1891 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001892 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001893 ConvType = ConvTypeRef->getPointeeType();
1894 if (ConvType->isRecordType()) {
1895 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1896 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001897 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001898 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001899 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001900 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001901 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001902 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001903 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001904 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001905 }
1906
Douglas Gregor853dd392008-12-26 15:00:45 +00001907 if (Conversion->getPreviousDeclaration()) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001908 const NamedDecl *ExpectedPrevDecl = Conversion->getPreviousDeclaration();
1909 if (FunctionTemplateDecl *ConversionTemplate
1910 = Conversion->getDescribedFunctionTemplate())
1911 ExpectedPrevDecl = ConversionTemplate->getPreviousDeclaration();
Douglas Gregor853dd392008-12-26 15:00:45 +00001912 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1913 for (OverloadedFunctionDecl::function_iterator
1914 Conv = Conversions->function_begin(),
1915 ConvEnd = Conversions->function_end();
1916 Conv != ConvEnd; ++Conv) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00001917 if (*Conv == ExpectedPrevDecl) {
Douglas Gregor853dd392008-12-26 15:00:45 +00001918 *Conv = Conversion;
Chris Lattner5261d0c2009-03-28 19:18:32 +00001919 return DeclPtrTy::make(Conversion);
Douglas Gregor853dd392008-12-26 15:00:45 +00001920 }
1921 }
1922 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
Douglas Gregor8c860df2009-08-21 23:19:43 +00001923 } else if (FunctionTemplateDecl *ConversionTemplate
1924 = Conversion->getDescribedFunctionTemplate())
1925 ClassDecl->addConversionFunction(Context, ConversionTemplate);
1926 else if (!Conversion->getPrimaryTemplate()) // ignore specializations
Douglas Gregor853dd392008-12-26 15:00:45 +00001927 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001928
Chris Lattner5261d0c2009-03-28 19:18:32 +00001929 return DeclPtrTy::make(Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001930}
1931
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001932//===----------------------------------------------------------------------===//
1933// Namespace Handling
1934//===----------------------------------------------------------------------===//
1935
1936/// ActOnStartNamespaceDef - This is called at the start of a namespace
1937/// definition.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001938Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1939 SourceLocation IdentLoc,
1940 IdentifierInfo *II,
1941 SourceLocation LBrace) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001942 NamespaceDecl *Namespc =
1943 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1944 Namespc->setLBracLoc(LBrace);
1945
1946 Scope *DeclRegionScope = NamespcScope->getParent();
1947
1948 if (II) {
1949 // C++ [namespace.def]p2:
1950 // The identifier in an original-namespace-definition shall not have been
1951 // previously defined in the declarative region in which the
1952 // original-namespace-definition appears. The identifier in an
1953 // original-namespace-definition is the name of the namespace. Subsequently
1954 // in that declarative region, it is treated as an original-namespace-name.
1955
Douglas Gregor09be81b2009-02-04 17:27:36 +00001956 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1957 true);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001958
1959 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1960 // This is an extended namespace definition.
1961 // Attach this namespace decl to the chain of extended namespace
1962 // definitions.
1963 OrigNS->setNextNamespace(Namespc);
1964 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001965
Douglas Gregor8acb7272008-12-11 16:49:14 +00001966 // Remove the previous declaration from the scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001967 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor39677622008-12-11 20:41:00 +00001968 IdResolver.RemoveDecl(OrigNS);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001969 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001970 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001971 } else if (PrevDecl) {
1972 // This is an invalid name redefinition.
1973 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1974 << Namespc->getDeclName();
1975 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1976 Namespc->setInvalidDecl();
1977 // Continue on to push Namespc as current DeclContext and return it.
1978 }
1979
1980 PushOnScopeChains(Namespc, DeclRegionScope);
1981 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001982 // FIXME: Handle anonymous namespaces
1983 }
1984
1985 // Although we could have an invalid decl (i.e. the namespace name is a
1986 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stumpe127ae32009-05-16 07:39:55 +00001987 // FIXME: We should be able to push Namespc here, so that the each DeclContext
1988 // for the namespace has the declarations that showed up in that particular
1989 // namespace definition.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001990 PushDeclContext(NamespcScope, Namespc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001991 return DeclPtrTy::make(Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001992}
1993
1994/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1995/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001996void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
1997 Decl *Dcl = D.getAs<Decl>();
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001998 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1999 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
2000 Namespc->setRBracLoc(RBrace);
2001 PopDeclContext();
2002}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002003
Chris Lattner5261d0c2009-03-28 19:18:32 +00002004Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
2005 SourceLocation UsingLoc,
2006 SourceLocation NamespcLoc,
2007 const CXXScopeSpec &SS,
2008 SourceLocation IdentLoc,
2009 IdentifierInfo *NamespcName,
2010 AttributeList *AttrList) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002011 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
2012 assert(NamespcName && "Invalid NamespcName.");
2013 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor7a7be652009-02-03 19:21:40 +00002014 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002015
Douglas Gregor7a7be652009-02-03 19:21:40 +00002016 UsingDirectiveDecl *UDir = 0;
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002017
Douglas Gregor78d70132009-01-14 22:20:51 +00002018 // Lookup namespace name.
Douglas Gregor7a7be652009-02-03 19:21:40 +00002019 LookupResult R = LookupParsedName(S, &SS, NamespcName,
2020 LookupNamespaceName, false);
2021 if (R.isAmbiguous()) {
2022 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002023 return DeclPtrTy();
Douglas Gregor7a7be652009-02-03 19:21:40 +00002024 }
Douglas Gregor09be81b2009-02-04 17:27:36 +00002025 if (NamedDecl *NS = R) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002026 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor7a7be652009-02-03 19:21:40 +00002027 // C++ [namespace.udir]p1:
2028 // A using-directive specifies that the names in the nominated
2029 // namespace can be used in the scope in which the
2030 // using-directive appears after the using-directive. During
2031 // unqualified name lookup (3.4.1), the names appear as if they
2032 // were declared in the nearest enclosing namespace which
2033 // contains both the using-directive and the nominated
Eli Friedmand5a72f02009-08-05 19:21:58 +00002034 // namespace. [Note: in this context, "contains" means "contains
2035 // directly or indirectly". ]
Douglas Gregor7a7be652009-02-03 19:21:40 +00002036
2037 // Find enclosing context containing both using-directive and
2038 // nominated namespace.
2039 DeclContext *CommonAncestor = cast<DeclContext>(NS);
2040 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
2041 CommonAncestor = CommonAncestor->getParent();
2042
Douglas Gregor1d27d692009-05-30 06:31:56 +00002043 UDir = UsingDirectiveDecl::Create(Context,
2044 CurContext, UsingLoc,
2045 NamespcLoc,
2046 SS.getRange(),
2047 (NestedNameSpecifier *)SS.getScopeRep(),
2048 IdentLoc,
Douglas Gregor7a7be652009-02-03 19:21:40 +00002049 cast<NamespaceDecl>(NS),
2050 CommonAncestor);
2051 PushUsingDirective(S, UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002052 } else {
Chris Lattner954381a2009-01-06 07:24:29 +00002053 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002054 }
2055
Douglas Gregor7a7be652009-02-03 19:21:40 +00002056 // FIXME: We ignore attributes for now.
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002057 delete AttrList;
Chris Lattner5261d0c2009-03-28 19:18:32 +00002058 return DeclPtrTy::make(UDir);
Douglas Gregor7a7be652009-02-03 19:21:40 +00002059}
2060
2061void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
2062 // If scope has associated entity, then using directive is at namespace
2063 // or translation unit scope. We add UsingDirectiveDecls, into
2064 // it's lookup structure.
2065 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002066 Ctx->addDecl(UDir);
Douglas Gregor7a7be652009-02-03 19:21:40 +00002067 else
2068 // Otherwise it is block-sope. using-directives will affect lookup
2069 // only to the end of scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002070 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00002071}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002072
Douglas Gregor683a1142009-06-20 00:51:54 +00002073
2074Sema::DeclPtrTy Sema::ActOnUsingDeclaration(Scope *S,
2075 SourceLocation UsingLoc,
2076 const CXXScopeSpec &SS,
2077 SourceLocation IdentLoc,
2078 IdentifierInfo *TargetName,
Anders Carlssone8c36f22009-06-27 00:27:47 +00002079 OverloadedOperatorKind Op,
Douglas Gregor683a1142009-06-20 00:51:54 +00002080 AttributeList *AttrList,
2081 bool IsTypeName) {
2082 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
Eli Friedmana73d6b12009-06-27 05:59:59 +00002083 assert((TargetName || Op) && "Invalid TargetName.");
Douglas Gregor683a1142009-06-20 00:51:54 +00002084 assert(IdentLoc.isValid() && "Invalid TargetName location.");
2085 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
2086
2087 UsingDecl *UsingAlias = 0;
2088
Anders Carlssone8c36f22009-06-27 00:27:47 +00002089 DeclarationName Name;
2090 if (TargetName)
2091 Name = TargetName;
2092 else
2093 Name = Context.DeclarationNames.getCXXOperatorName(Op);
2094
Douglas Gregor683a1142009-06-20 00:51:54 +00002095 // Lookup target name.
Anders Carlssone8c36f22009-06-27 00:27:47 +00002096 LookupResult R = LookupParsedName(S, &SS, Name, LookupOrdinaryName, false);
Douglas Gregor683a1142009-06-20 00:51:54 +00002097
2098 if (NamedDecl *NS = R) {
2099 if (IsTypeName && !isa<TypeDecl>(NS)) {
2100 Diag(IdentLoc, diag::err_using_typename_non_type);
2101 }
2102 UsingAlias = UsingDecl::Create(Context, CurContext, IdentLoc, SS.getRange(),
2103 NS->getLocation(), UsingLoc, NS,
2104 static_cast<NestedNameSpecifier *>(SS.getScopeRep()),
2105 IsTypeName);
2106 PushOnScopeChains(UsingAlias, S);
2107 } else {
2108 Diag(IdentLoc, diag::err_using_requires_qualname) << SS.getRange();
2109 }
2110
2111 // FIXME: We ignore attributes for now.
2112 delete AttrList;
2113 return DeclPtrTy::make(UsingAlias);
2114}
2115
Anders Carlsson7c1c5482009-03-28 23:53:49 +00002116/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
2117/// is a namespace alias, returns the namespace it points to.
2118static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
2119 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
2120 return AD->getNamespace();
2121 return dyn_cast_or_null<NamespaceDecl>(D);
2122}
2123
Chris Lattner5261d0c2009-03-28 19:18:32 +00002124Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson26de7882009-03-28 22:53:22 +00002125 SourceLocation NamespaceLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +00002126 SourceLocation AliasLoc,
2127 IdentifierInfo *Alias,
2128 const CXXScopeSpec &SS,
Anders Carlsson26de7882009-03-28 22:53:22 +00002129 SourceLocation IdentLoc,
2130 IdentifierInfo *Ident) {
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002131
Anders Carlsson7c1c5482009-03-28 23:53:49 +00002132 // Lookup the namespace name.
2133 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
2134
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002135 // Check if we have a previous declaration with the same name.
Anders Carlsson1cd05f52009-03-28 23:49:35 +00002136 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson7c1c5482009-03-28 23:53:49 +00002137 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
2138 // We already have an alias with the same name that points to the same
2139 // namespace, so don't create a new one.
2140 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
2141 return DeclPtrTy();
2142 }
2143
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002144 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
2145 diag::err_redefinition_different_kind;
2146 Diag(AliasLoc, DiagID) << Alias;
2147 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002148 return DeclPtrTy();
Anders Carlsson640eb7c2009-03-28 06:23:46 +00002149 }
2150
Anders Carlsson279ebc42009-03-28 06:42:02 +00002151 if (R.isAmbiguous()) {
Anders Carlsson26de7882009-03-28 22:53:22 +00002152 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002153 return DeclPtrTy();
Anders Carlsson279ebc42009-03-28 06:42:02 +00002154 }
2155
2156 if (!R) {
2157 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner5261d0c2009-03-28 19:18:32 +00002158 return DeclPtrTy();
Anders Carlsson279ebc42009-03-28 06:42:02 +00002159 }
2160
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002161 NamespaceAliasDecl *AliasDecl =
Douglas Gregor8d8ddca2009-05-30 06:48:27 +00002162 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
2163 Alias, SS.getRange(),
2164 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlssonddb1d8b2009-03-28 22:58:02 +00002165 IdentLoc, R);
2166
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002167 CurContext->addDecl(AliasDecl);
Anders Carlssonddb1d8b2009-03-28 22:58:02 +00002168 return DeclPtrTy::make(AliasDecl);
Anders Carlsson8cffcd62009-03-28 05:27:17 +00002169}
2170
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002171void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
2172 CXXConstructorDecl *Constructor) {
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00002173 assert((Constructor->isImplicit() && Constructor->isDefaultConstructor() &&
2174 !Constructor->isUsed()) &&
2175 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002176
2177 CXXRecordDecl *ClassDecl
2178 = cast<CXXRecordDecl>(Constructor->getDeclContext());
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002179 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002180 // Before the implicitly-declared default constructor for a class is
2181 // implicitly defined, all the implicitly-declared default constructors
2182 // for its base class and its non-static data members shall have been
2183 // implicitly defined.
2184 bool err = false;
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002185 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2186 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002187 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002188 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002189 if (!BaseClassDecl->hasTrivialConstructor()) {
2190 if (CXXConstructorDecl *BaseCtor =
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002191 BaseClassDecl->getDefaultConstructor(Context))
2192 MarkDeclarationReferenced(CurrentLocation, BaseCtor);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002193 else {
2194 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian16443602009-06-20 20:23:38 +00002195 << Context.getTagDeclType(ClassDecl) << 1
2196 << Context.getTagDeclType(BaseClassDecl);
2197 Diag(BaseClassDecl->getLocation(), diag::note_previous_class_decl)
2198 << Context.getTagDeclType(BaseClassDecl);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002199 err = true;
2200 }
2201 }
2202 }
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002203 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2204 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002205 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2206 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2207 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002208 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002209 CXXRecordDecl *FieldClassDecl
2210 = cast<CXXRecordDecl>(FieldClassType->getDecl());
Duncan Sands78146712009-06-25 09:03:06 +00002211 if (!FieldClassDecl->hasTrivialConstructor()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002212 if (CXXConstructorDecl *FieldCtor =
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002213 FieldClassDecl->getDefaultConstructor(Context))
2214 MarkDeclarationReferenced(CurrentLocation, FieldCtor);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002215 else {
2216 Diag(CurrentLocation, diag::err_defining_default_ctor)
Fariborz Jahanian16443602009-06-20 20:23:38 +00002217 << Context.getTagDeclType(ClassDecl) << 0 <<
2218 Context.getTagDeclType(FieldClassDecl);
2219 Diag(FieldClassDecl->getLocation(), diag::note_previous_class_decl)
2220 << Context.getTagDeclType(FieldClassDecl);
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002221 err = true;
2222 }
2223 }
Mike Stump90fc78e2009-08-04 21:02:39 +00002224 } else if (FieldType->isReferenceType()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002225 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson6a661262009-07-09 17:37:12 +00002226 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002227 Diag((*Field)->getLocation(), diag::note_declared_at);
2228 err = true;
Mike Stump90fc78e2009-08-04 21:02:39 +00002229 } else if (FieldType.isConstQualified()) {
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002230 Diag(CurrentLocation, diag::err_unintialized_member)
Anders Carlsson6a661262009-07-09 17:37:12 +00002231 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002232 Diag((*Field)->getLocation(), diag::note_declared_at);
2233 err = true;
2234 }
2235 }
2236 if (!err)
Fariborz Jahanian2c313fb2009-06-26 16:08:57 +00002237 Constructor->setUsed();
2238 else
2239 Constructor->setInvalidDecl();
Fariborz Jahanian3603e0c2009-06-19 19:55:27 +00002240}
2241
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002242void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
2243 CXXDestructorDecl *Destructor) {
2244 assert((Destructor->isImplicit() && !Destructor->isUsed()) &&
2245 "DefineImplicitDestructor - call it for implicit default dtor");
2246
2247 CXXRecordDecl *ClassDecl
2248 = cast<CXXRecordDecl>(Destructor->getDeclContext());
2249 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
2250 // C++ [class.dtor] p5
2251 // Before the implicitly-declared default destructor for a class is
2252 // implicitly defined, all the implicitly-declared default destructors
2253 // for its base class and its non-static data members shall have been
2254 // implicitly defined.
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002255 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2256 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002257 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002258 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002259 if (!BaseClassDecl->hasTrivialDestructor()) {
2260 if (CXXDestructorDecl *BaseDtor =
2261 const_cast<CXXDestructorDecl*>(BaseClassDecl->getDestructor(Context)))
2262 MarkDeclarationReferenced(CurrentLocation, BaseDtor);
2263 else
2264 assert(false &&
2265 "DefineImplicitDestructor - missing dtor in a base class");
2266 }
2267 }
2268
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002269 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2270 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002271 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2272 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2273 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002274 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002275 CXXRecordDecl *FieldClassDecl
2276 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2277 if (!FieldClassDecl->hasTrivialDestructor()) {
2278 if (CXXDestructorDecl *FieldDtor =
2279 const_cast<CXXDestructorDecl*>(
2280 FieldClassDecl->getDestructor(Context)))
2281 MarkDeclarationReferenced(CurrentLocation, FieldDtor);
2282 else
2283 assert(false &&
2284 "DefineImplicitDestructor - missing dtor in class of a data member");
2285 }
2286 }
2287 }
2288 Destructor->setUsed();
2289}
2290
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002291void Sema::DefineImplicitOverloadedAssign(SourceLocation CurrentLocation,
2292 CXXMethodDecl *MethodDecl) {
2293 assert((MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
2294 MethodDecl->getOverloadedOperator() == OO_Equal &&
2295 !MethodDecl->isUsed()) &&
2296 "DefineImplicitOverloadedAssign - call it for implicit assignment op");
2297
2298 CXXRecordDecl *ClassDecl
2299 = cast<CXXRecordDecl>(MethodDecl->getDeclContext());
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002300
Fariborz Jahanian2c313fb2009-06-26 16:08:57 +00002301 // C++[class.copy] p12
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002302 // Before the implicitly-declared copy assignment operator for a class is
2303 // implicitly defined, all implicitly-declared copy assignment operators
2304 // for its direct base classes and its nonstatic data members shall have
2305 // been implicitly defined.
2306 bool err = false;
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002307 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2308 E = ClassDecl->bases_end(); Base != E; ++Base) {
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002309 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002310 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002311 if (CXXMethodDecl *BaseAssignOpMethod =
2312 getAssignOperatorMethod(MethodDecl->getParamDecl(0), BaseClassDecl))
2313 MarkDeclarationReferenced(CurrentLocation, BaseAssignOpMethod);
2314 }
Fariborz Jahanianb394bd32009-06-30 16:36:53 +00002315 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2316 E = ClassDecl->field_end(); Field != E; ++Field) {
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002317 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2318 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2319 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002320 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002321 CXXRecordDecl *FieldClassDecl
2322 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2323 if (CXXMethodDecl *FieldAssignOpMethod =
2324 getAssignOperatorMethod(MethodDecl->getParamDecl(0), FieldClassDecl))
2325 MarkDeclarationReferenced(CurrentLocation, FieldAssignOpMethod);
Mike Stump90fc78e2009-08-04 21:02:39 +00002326 } else if (FieldType->isReferenceType()) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002327 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson1c0c52c2009-07-09 17:47:25 +00002328 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
2329 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002330 Diag(CurrentLocation, diag::note_first_required_here);
2331 err = true;
Mike Stump90fc78e2009-08-04 21:02:39 +00002332 } else if (FieldType.isConstQualified()) {
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002333 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
Anders Carlsson1c0c52c2009-07-09 17:47:25 +00002334 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
2335 Diag(Field->getLocation(), diag::note_declared_at);
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00002336 Diag(CurrentLocation, diag::note_first_required_here);
2337 err = true;
2338 }
2339 }
2340 if (!err)
2341 MethodDecl->setUsed();
2342}
2343
2344CXXMethodDecl *
2345Sema::getAssignOperatorMethod(ParmVarDecl *ParmDecl,
2346 CXXRecordDecl *ClassDecl) {
2347 QualType LHSType = Context.getTypeDeclType(ClassDecl);
2348 QualType RHSType(LHSType);
2349 // If class's assignment operator argument is const/volatile qualified,
2350 // look for operator = (const/volatile B&). Otherwise, look for
2351 // operator = (B&).
2352 if (ParmDecl->getType().isConstQualified())
2353 RHSType.addConst();
2354 if (ParmDecl->getType().isVolatileQualified())
2355 RHSType.addVolatile();
2356 ExprOwningPtr<Expr> LHS(this, new (Context) DeclRefExpr(ParmDecl,
2357 LHSType,
2358 SourceLocation()));
2359 ExprOwningPtr<Expr> RHS(this, new (Context) DeclRefExpr(ParmDecl,
2360 RHSType,
2361 SourceLocation()));
2362 Expr *Args[2] = { &*LHS, &*RHS };
2363 OverloadCandidateSet CandidateSet;
2364 AddMemberOperatorCandidates(clang::OO_Equal, SourceLocation(), Args, 2,
2365 CandidateSet);
2366 OverloadCandidateSet::iterator Best;
2367 if (BestViableFunction(CandidateSet,
2368 ClassDecl->getLocation(), Best) == OR_Success)
2369 return cast<CXXMethodDecl>(Best->Function);
2370 assert(false &&
2371 "getAssignOperatorMethod - copy assignment operator method not found");
2372 return 0;
2373}
2374
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002375void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
2376 CXXConstructorDecl *CopyConstructor,
2377 unsigned TypeQuals) {
2378 assert((CopyConstructor->isImplicit() &&
2379 CopyConstructor->isCopyConstructor(Context, TypeQuals) &&
2380 !CopyConstructor->isUsed()) &&
2381 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
2382
2383 CXXRecordDecl *ClassDecl
2384 = cast<CXXRecordDecl>(CopyConstructor->getDeclContext());
2385 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002386 // C++ [class.copy] p209
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002387 // Before the implicitly-declared copy constructor for a class is
2388 // implicitly defined, all the implicitly-declared copy constructors
2389 // for its base class and its non-static data members shall have been
2390 // implicitly defined.
2391 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2392 Base != ClassDecl->bases_end(); ++Base) {
2393 CXXRecordDecl *BaseClassDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002394 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002395 if (CXXConstructorDecl *BaseCopyCtor =
2396 BaseClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002397 MarkDeclarationReferenced(CurrentLocation, BaseCopyCtor);
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002398 }
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002399 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2400 FieldEnd = ClassDecl->field_end();
2401 Field != FieldEnd; ++Field) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002402 QualType FieldType = Context.getCanonicalType((*Field)->getType());
2403 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
2404 FieldType = Array->getElementType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002405 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002406 CXXRecordDecl *FieldClassDecl
2407 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2408 if (CXXConstructorDecl *FieldCopyCtor =
2409 FieldClassDecl->getCopyConstructor(Context, TypeQuals))
Fariborz Jahanianf6da0dd2009-06-23 23:42:10 +00002410 MarkDeclarationReferenced(CurrentLocation, FieldCopyCtor);
Fariborz Jahanian599778e2009-06-22 23:34:40 +00002411 }
2412 }
2413 CopyConstructor->setUsed();
2414}
2415
Anders Carlsson665e4692009-08-25 05:12:04 +00002416Sema::OwningExprResult
2417Sema::BuildCXXConstructExpr(QualType DeclInitType,
2418 CXXConstructorDecl *Constructor,
2419 Expr **Exprs, unsigned NumExprs) {
Anders Carlssonbd9f51a2009-08-16 05:13:48 +00002420 bool Elidable = false;
2421
2422 // [class.copy]p15:
2423 // Whenever a temporary class object is copied using a copy constructor, and
2424 // this object and the copy have the same cv-unqualified type, an
2425 // implementation is permitted to treat the original and the copy as two
2426 // different ways of referring to the same object and not perform a copy at
2427 //all, even if the class copy constructor or destructor have side effects.
2428
2429 // FIXME: Is this enough?
2430 if (Constructor->isCopyConstructor(Context) && NumExprs == 1) {
2431 Expr *E = Exprs[0];
2432 while (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
2433 E = BE->getSubExpr();
2434
2435 if (isa<CallExpr>(E) || isa<CXXTemporaryObjectExpr>(E))
2436 Elidable = true;
2437 }
2438
2439 return BuildCXXConstructExpr(DeclInitType, Constructor, Elidable,
2440 Exprs, NumExprs);
2441}
2442
Fariborz Jahanian1c30f262009-08-05 17:03:54 +00002443/// BuildCXXConstructExpr - Creates a complete call to a constructor,
2444/// including handling of its default argument expressions.
Anders Carlsson665e4692009-08-25 05:12:04 +00002445Sema::OwningExprResult
2446Sema::BuildCXXConstructExpr(QualType DeclInitType,
2447 CXXConstructorDecl *Constructor,
2448 bool Elidable,
2449 Expr **Exprs,
2450 unsigned NumExprs) {
Anders Carlsson3e03d832009-08-25 13:07:08 +00002451 ExprOwningPtr<CXXConstructExpr> Temp(this,
2452 CXXConstructExpr::Create(Context,
2453 DeclInitType,
2454 Constructor,
2455 Elidable,
2456 Exprs,
2457 NumExprs));
Fariborz Jahanianbeb68c42009-08-05 00:26:10 +00002458 // default arguments must be added to constructor call expression.
2459 FunctionDecl *FDecl = cast<FunctionDecl>(Constructor);
2460 unsigned NumArgsInProto = FDecl->param_size();
2461 for (unsigned j = NumExprs; j != NumArgsInProto; j++) {
Anders Carlsson3e03d832009-08-25 13:07:08 +00002462 ParmVarDecl *Param = FDecl->getParamDecl(j);
2463
2464 OwningExprResult ArgExpr =
2465 BuildCXXDefaultArgExpr(/*FIXME:*/SourceLocation(),
2466 FDecl, Param);
2467 if (ArgExpr.isInvalid())
2468 return ExprError();
2469
2470 Temp->setArg(j, ArgExpr.takeAs<Expr>());
Fariborz Jahanianbeb68c42009-08-05 00:26:10 +00002471 }
Anders Carlsson3e03d832009-08-25 13:07:08 +00002472 return move(Temp);
Fariborz Jahanian1c30f262009-08-05 17:03:54 +00002473}
2474
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002475bool Sema::InitializeVarWithConstructor(VarDecl *VD,
Fariborz Jahanian1c30f262009-08-05 17:03:54 +00002476 CXXConstructorDecl *Constructor,
2477 QualType DeclInitType,
2478 Expr **Exprs, unsigned NumExprs) {
Anders Carlsson665e4692009-08-25 05:12:04 +00002479 OwningExprResult TempResult = BuildCXXConstructExpr(DeclInitType, Constructor,
2480 Exprs, NumExprs);
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002481 if (TempResult.isInvalid())
2482 return true;
Anders Carlsson665e4692009-08-25 05:12:04 +00002483
2484 Expr *Temp = TempResult.takeAs<Expr>();
Douglas Gregorcad27f62009-06-22 23:06:13 +00002485 MarkDeclarationReferenced(VD->getLocation(), Constructor);
Fariborz Jahanian88e09cc2009-08-05 18:17:32 +00002486 Temp = MaybeCreateCXXExprWithTemporaries(Temp, /*DestroyTemps=*/true);
Douglas Gregor4833ff02009-05-26 18:54:04 +00002487 VD->setInit(Context, Temp);
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002488
2489 return false;
Anders Carlsson05e59652009-04-16 23:50:50 +00002490}
2491
Fariborz Jahaniancd208112009-08-03 19:13:25 +00002492void Sema::FinalizeVarWithDestructor(VarDecl *VD, QualType DeclInitType)
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002493{
2494 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002495 DeclInitType->getAs<RecordType>()->getDecl());
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002496 if (!ClassDecl->hasTrivialDestructor())
2497 if (CXXDestructorDecl *Destructor =
2498 const_cast<CXXDestructorDecl*>(ClassDecl->getDestructor(Context)))
Fariborz Jahaniancd208112009-08-03 19:13:25 +00002499 MarkDeclarationReferenced(VD->getLocation(), Destructor);
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00002500}
2501
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002502/// AddCXXDirectInitializerToDecl - This action is called immediately after
2503/// ActOnDeclarator, when a C++ direct initializer is present.
2504/// e.g: "int x(1);"
Chris Lattner5261d0c2009-03-28 19:18:32 +00002505void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
2506 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002507 MultiExprArg Exprs,
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002508 SourceLocation *CommaLocs,
2509 SourceLocation RParenLoc) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002510 unsigned NumExprs = Exprs.size();
2511 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner5261d0c2009-03-28 19:18:32 +00002512 Decl *RealDecl = Dcl.getAs<Decl>();
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002513
2514 // If there is no declaration, there was an error parsing it. Just ignore
2515 // the initializer.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002516 if (RealDecl == 0)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002517 return;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002518
2519 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2520 if (!VDecl) {
2521 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
2522 RealDecl->setInvalidDecl();
2523 return;
2524 }
2525
Douglas Gregor52be1ca2009-08-26 21:14:46 +00002526 // We will represent direct-initialization similarly to copy-initialization:
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002527 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002528 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
2529 //
2530 // Clients that want to distinguish between the two forms, can check for
2531 // direct initializer using VarDecl::hasCXXDirectInitializer().
2532 // A major benefit is that clients that don't particularly care about which
2533 // exactly form was it (like the CodeGen) can handle both cases without
2534 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002535
Douglas Gregor52be1ca2009-08-26 21:14:46 +00002536 // If either the declaration has a dependent type or if any of the expressions
2537 // is type-dependent, we represent the initialization via a ParenListExpr for
2538 // later use during template instantiation.
2539 if (VDecl->getType()->isDependentType() ||
2540 Expr::hasAnyTypeDependentArguments((Expr **)Exprs.get(), Exprs.size())) {
2541 // Let clients know that initialization was done with a direct initializer.
2542 VDecl->setCXXDirectInitializer(true);
2543
2544 // Store the initialization expressions as a ParenListExpr.
2545 unsigned NumExprs = Exprs.size();
2546 VDecl->setInit(Context,
2547 new (Context) ParenListExpr(Context, LParenLoc,
2548 (Expr **)Exprs.release(),
2549 NumExprs, RParenLoc));
2550 return;
2551 }
2552
2553
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002554 // C++ 8.5p11:
2555 // The form of initialization (using parentheses or '=') is generally
2556 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002557 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00002558 QualType DeclInitType = VDecl->getType();
2559 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
2560 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002561
Douglas Gregorad7d1812009-03-24 16:43:20 +00002562 // FIXME: This isn't the right place to complete the type.
2563 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
2564 diag::err_typecheck_decl_incomplete_type)) {
2565 VDecl->setInvalidDecl();
2566 return;
2567 }
2568
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002569 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00002570 CXXConstructorDecl *Constructor
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002571 = PerformInitializationByConstructor(DeclInitType,
2572 (Expr **)Exprs.get(), NumExprs,
Douglas Gregor6428e762008-11-05 15:29:30 +00002573 VDecl->getLocation(),
2574 SourceRange(VDecl->getLocation(),
2575 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00002576 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002577 IK_Direct);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002578 if (!Constructor)
Douglas Gregor5870a952008-11-03 20:45:27 +00002579 RealDecl->setInvalidDecl();
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002580 else {
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002581 VDecl->setCXXDirectInitializer(true);
Anders Carlssonbaa8a312009-08-25 05:18:00 +00002582 if (InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
2583 (Expr**)Exprs.release(), NumExprs))
2584 RealDecl->setInvalidDecl();
Fariborz Jahaniancd208112009-08-03 19:13:25 +00002585 FinalizeVarWithDestructor(VDecl, DeclInitType);
Anders Carlsson9c7b4922009-04-15 21:48:18 +00002586 }
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00002587 return;
2588 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002589
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002590 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002591 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
2592 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002593 RealDecl->setInvalidDecl();
2594 return;
2595 }
2596
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002597 // Let clients know that initialization was done with a direct initializer.
2598 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00002599
2600 assert(NumExprs == 1 && "Expected 1 expression");
2601 // Set the init expression, handles conversions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00002602 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
2603 /*DirectInit=*/true);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00002604}
Douglas Gregor81c29152008-10-29 00:13:59 +00002605
Douglas Gregor6428e762008-11-05 15:29:30 +00002606/// PerformInitializationByConstructor - Perform initialization by
2607/// constructor (C++ [dcl.init]p14), which may occur as part of
2608/// direct-initialization or copy-initialization. We are initializing
2609/// an object of type @p ClassType with the given arguments @p
2610/// Args. @p Loc is the location in the source code where the
2611/// initializer occurs (e.g., a declaration, member initializer,
2612/// functional cast, etc.) while @p Range covers the whole
2613/// initialization. @p InitEntity is the entity being initialized,
2614/// which may by the name of a declaration or a type. @p Kind is the
2615/// kind of initialization we're performing, which affects whether
2616/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00002617/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00002618/// when the initialization fails, emits a diagnostic and returns
2619/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00002620CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00002621Sema::PerformInitializationByConstructor(QualType ClassType,
2622 Expr **Args, unsigned NumArgs,
2623 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00002624 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00002625 InitializationKind Kind) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002626 const RecordType *ClassRec = ClassType->getAs<RecordType>();
Douglas Gregor5870a952008-11-03 20:45:27 +00002627 assert(ClassRec && "Can only initialize a class type here");
2628
2629 // C++ [dcl.init]p14:
2630 //
2631 // If the initialization is direct-initialization, or if it is
2632 // copy-initialization where the cv-unqualified version of the
2633 // source type is the same class as, or a derived class of, the
2634 // class of the destination, constructors are considered. The
2635 // applicable constructors are enumerated (13.3.1.3), and the
2636 // best one is chosen through overload resolution (13.3). The
2637 // constructor so selected is called to initialize the object,
2638 // with the initializer expression(s) as its argument(s). If no
2639 // constructor applies, or the overload resolution is ambiguous,
2640 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00002641 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
2642 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00002643
2644 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00002645 DeclarationName ConstructorName
2646 = Context.DeclarationNames.getCXXConstructorName(
2647 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002648 DeclContext::lookup_const_iterator Con, ConEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002649 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002650 Con != ConEnd; ++Con) {
Douglas Gregor050cabf2009-08-21 18:42:58 +00002651 // Find the constructor (which may be a template).
2652 CXXConstructorDecl *Constructor = 0;
2653 FunctionTemplateDecl *ConstructorTmpl= dyn_cast<FunctionTemplateDecl>(*Con);
2654 if (ConstructorTmpl)
2655 Constructor
2656 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2657 else
2658 Constructor = cast<CXXConstructorDecl>(*Con);
2659
Douglas Gregor6428e762008-11-05 15:29:30 +00002660 if ((Kind == IK_Direct) ||
2661 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
Douglas Gregor050cabf2009-08-21 18:42:58 +00002662 (Kind == IK_Default && Constructor->isDefaultConstructor())) {
2663 if (ConstructorTmpl)
2664 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0,
2665 Args, NumArgs, CandidateSet);
2666 else
2667 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
2668 }
Douglas Gregor6428e762008-11-05 15:29:30 +00002669 }
2670
Douglas Gregorb9213832008-12-15 21:24:18 +00002671 // FIXME: When we decide not to synthesize the implicitly-declared
2672 // constructors, we'll need to make them appear here.
2673
Douglas Gregor5870a952008-11-03 20:45:27 +00002674 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00002675 switch (BestViableFunction(CandidateSet, Loc, Best)) {
Douglas Gregor5870a952008-11-03 20:45:27 +00002676 case OR_Success:
2677 // We found a constructor. Return it.
2678 return cast<CXXConstructorDecl>(Best->Function);
2679
2680 case OR_No_Viable_Function:
Douglas Gregor538a4c22009-02-02 17:43:21 +00002681 if (InitEntity)
2682 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00002683 << InitEntity << Range;
Douglas Gregor538a4c22009-02-02 17:43:21 +00002684 else
2685 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00002686 << ClassType << Range;
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00002687 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00002688 return 0;
2689
2690 case OR_Ambiguous:
Douglas Gregor538a4c22009-02-02 17:43:21 +00002691 if (InitEntity)
2692 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
2693 else
2694 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00002695 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2696 return 0;
Douglas Gregoraa57e862009-02-18 21:56:37 +00002697
2698 case OR_Deleted:
2699 if (InitEntity)
2700 Diag(Loc, diag::err_ovl_deleted_init)
2701 << Best->Function->isDeleted()
2702 << InitEntity << Range;
2703 else
2704 Diag(Loc, diag::err_ovl_deleted_init)
2705 << Best->Function->isDeleted()
2706 << InitEntity << Range;
2707 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
2708 return 0;
Douglas Gregor5870a952008-11-03 20:45:27 +00002709 }
2710
2711 return 0;
2712}
2713
Douglas Gregor81c29152008-10-29 00:13:59 +00002714/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2715/// determine whether they are reference-related,
2716/// reference-compatible, reference-compatible with added
2717/// qualification, or incompatible, for use in C++ initialization by
2718/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2719/// type, and the first type (T1) is the pointee type of the reference
2720/// type being initialized.
2721Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002722Sema::CompareReferenceRelationship(QualType T1, QualType T2,
2723 bool& DerivedToBase) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002724 assert(!T1->isReferenceType() &&
2725 "T1 must be the pointee type of the reference type");
Douglas Gregor81c29152008-10-29 00:13:59 +00002726 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
2727
2728 T1 = Context.getCanonicalType(T1);
2729 T2 = Context.getCanonicalType(T2);
2730 QualType UnqualT1 = T1.getUnqualifiedType();
2731 QualType UnqualT2 = T2.getUnqualifiedType();
2732
2733 // C++ [dcl.init.ref]p4:
Eli Friedmand5a72f02009-08-05 19:21:58 +00002734 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2735 // reference-related to "cv2 T2" if T1 is the same type as T2, or
Douglas Gregor81c29152008-10-29 00:13:59 +00002736 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002737 if (UnqualT1 == UnqualT2)
2738 DerivedToBase = false;
2739 else if (IsDerivedFrom(UnqualT2, UnqualT1))
2740 DerivedToBase = true;
2741 else
Douglas Gregor81c29152008-10-29 00:13:59 +00002742 return Ref_Incompatible;
2743
2744 // At this point, we know that T1 and T2 are reference-related (at
2745 // least).
2746
2747 // C++ [dcl.init.ref]p4:
Eli Friedmand5a72f02009-08-05 19:21:58 +00002748 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
Douglas Gregor81c29152008-10-29 00:13:59 +00002749 // reference-related to T2 and cv1 is the same cv-qualification
2750 // as, or greater cv-qualification than, cv2. For purposes of
2751 // overload resolution, cases for which cv1 is greater
2752 // cv-qualification than cv2 are identified as
2753 // reference-compatible with added qualification (see 13.3.3.2).
2754 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2755 return Ref_Compatible;
2756 else if (T1.isMoreQualifiedThan(T2))
2757 return Ref_Compatible_With_Added_Qualification;
2758 else
2759 return Ref_Related;
2760}
2761
2762/// CheckReferenceInit - Check the initialization of a reference
2763/// variable with the given initializer (C++ [dcl.init.ref]). Init is
2764/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00002765/// list), and DeclType is the type of the declaration. When ICS is
2766/// non-null, this routine will compute the implicit conversion
2767/// sequence according to C++ [over.ics.ref] and will not produce any
2768/// diagnostics; when ICS is null, it will emit diagnostics when any
2769/// errors are found. Either way, a return value of true indicates
2770/// that there was a failure, a return value of false indicates that
2771/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002772///
2773/// When @p SuppressUserConversions, user-defined conversions are
2774/// suppressed.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002775/// When @p AllowExplicit, we also permit explicit user-defined
2776/// conversion functions.
Sebastian Redla55834a2009-04-12 17:16:29 +00002777/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002778bool
Sebastian Redlbd261962009-04-16 17:51:27 +00002779Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002780 ImplicitConversionSequence *ICS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002781 bool SuppressUserConversions,
Sebastian Redla55834a2009-04-12 17:16:29 +00002782 bool AllowExplicit, bool ForceRValue) {
Douglas Gregor81c29152008-10-29 00:13:59 +00002783 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2784
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002785 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
Douglas Gregor81c29152008-10-29 00:13:59 +00002786 QualType T2 = Init->getType();
2787
Douglas Gregor45014fd2008-11-10 20:40:00 +00002788 // If the initializer is the address of an overloaded function, try
2789 // to resolve the overloaded function. If all goes well, T2 is the
2790 // type of the resulting function.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002791 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00002792 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
2793 ICS != 0);
2794 if (Fn) {
2795 // Since we're performing this reference-initialization for
2796 // real, update the initializer with the resulting function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00002797 if (!ICS) {
2798 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
2799 return true;
2800
Douglas Gregor45014fd2008-11-10 20:40:00 +00002801 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregoraa57e862009-02-18 21:56:37 +00002802 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002803
2804 T2 = Fn->getType();
2805 }
2806 }
2807
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002808 // Compute some basic properties of the types and the initializer.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002809 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002810 bool DerivedToBase = false;
Sebastian Redla55834a2009-04-12 17:16:29 +00002811 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2812 Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002813 ReferenceCompareResult RefRelationship
2814 = CompareReferenceRelationship(T1, T2, DerivedToBase);
2815
2816 // Most paths end in a failed conversion.
2817 if (ICS)
2818 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00002819
2820 // C++ [dcl.init.ref]p5:
Eli Friedmand5a72f02009-08-05 19:21:58 +00002821 // A reference to type "cv1 T1" is initialized by an expression
2822 // of type "cv2 T2" as follows:
Douglas Gregor81c29152008-10-29 00:13:59 +00002823
2824 // -- If the initializer expression
2825
Sebastian Redldfc30332009-03-29 15:27:50 +00002826 // Rvalue references cannot bind to lvalues (N2812).
2827 // There is absolutely no situation where they can. In particular, note that
2828 // this is ill-formed, even if B has a user-defined conversion to A&&:
2829 // B b;
2830 // A&& r = b;
2831 if (isRValRef && InitLvalue == Expr::LV_Valid) {
2832 if (!ICS)
2833 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
2834 << Init->getSourceRange();
2835 return true;
2836 }
2837
Douglas Gregor81c29152008-10-29 00:13:59 +00002838 bool BindsDirectly = false;
Eli Friedmand5a72f02009-08-05 19:21:58 +00002839 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2840 // reference-compatible with "cv2 T2," or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002841 //
2842 // Note that the bit-field check is skipped if we are just computing
2843 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor531434b2009-05-02 02:18:30 +00002844 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002845 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00002846 BindsDirectly = true;
2847
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002848 if (ICS) {
2849 // C++ [over.ics.ref]p1:
2850 // When a parameter of reference type binds directly (8.5.3)
2851 // to an argument expression, the implicit conversion sequence
2852 // is the identity conversion, unless the argument expression
2853 // has a type that is a derived class of the parameter type,
2854 // in which case the implicit conversion sequence is a
2855 // derived-to-base Conversion (13.3.3.1).
2856 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2857 ICS->Standard.First = ICK_Identity;
2858 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2859 ICS->Standard.Third = ICK_Identity;
2860 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2861 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00002862 ICS->Standard.ReferenceBinding = true;
2863 ICS->Standard.DirectBinding = true;
Sebastian Redldfc30332009-03-29 15:27:50 +00002864 ICS->Standard.RRefBinding = false;
Sebastian Redld3169132009-04-17 16:30:52 +00002865 ICS->Standard.CopyConstructor = 0;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002866
2867 // Nothing more to do: the inaccessibility/ambiguity check for
2868 // derived-to-base conversions is suppressed when we're
2869 // computing the implicit conversion sequence (C++
2870 // [over.best.ics]p2).
2871 return false;
2872 } else {
2873 // Perform the conversion.
Mike Stumpe127ae32009-05-16 07:39:55 +00002874 // FIXME: Binding to a subobject of the lvalue is going to require more
2875 // AST annotation than this.
Anders Carlsson85186942009-07-31 01:23:52 +00002876 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00002877 }
2878 }
2879
2880 // -- has a class type (i.e., T2 is a class type) and can be
Eli Friedmand5a72f02009-08-05 19:21:58 +00002881 // implicitly converted to an lvalue of type "cv3 T3,"
2882 // where "cv1 T1" is reference-compatible with "cv3 T3"
Douglas Gregor81c29152008-10-29 00:13:59 +00002883 // 92) (this conversion is selected by enumerating the
2884 // applicable conversion functions (13.3.1.6) and choosing
2885 // the best one through overload resolution (13.3)),
Douglas Gregorb35c7992009-08-24 15:23:48 +00002886 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2887 !RequireCompleteType(SourceLocation(), T2, 0)) {
Douglas Gregore6985fe2008-11-10 16:14:15 +00002888 // FIXME: Look for conversions in base classes!
2889 CXXRecordDecl *T2RecordDecl
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002890 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00002891
Douglas Gregore6985fe2008-11-10 16:14:15 +00002892 OverloadCandidateSet CandidateSet;
2893 OverloadedFunctionDecl *Conversions
2894 = T2RecordDecl->getConversionFunctions();
2895 for (OverloadedFunctionDecl::function_iterator Func
2896 = Conversions->function_begin();
2897 Func != Conversions->function_end(); ++Func) {
Douglas Gregor8c860df2009-08-21 23:19:43 +00002898 FunctionTemplateDecl *ConvTemplate
2899 = dyn_cast<FunctionTemplateDecl>(*Func);
2900 CXXConversionDecl *Conv;
2901 if (ConvTemplate)
2902 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2903 else
2904 Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redl16ac38f2009-03-22 21:28:55 +00002905
Douglas Gregore6985fe2008-11-10 16:14:15 +00002906 // If the conversion function doesn't return a reference type,
2907 // it can't be considered for this conversion.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002908 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor8c860df2009-08-21 23:19:43 +00002909 (AllowExplicit || !Conv->isExplicit())) {
2910 if (ConvTemplate)
2911 AddTemplateConversionCandidate(ConvTemplate, Init, DeclType,
2912 CandidateSet);
2913 else
2914 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
2915 }
Douglas Gregore6985fe2008-11-10 16:14:15 +00002916 }
2917
2918 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00002919 switch (BestViableFunction(CandidateSet, Init->getLocStart(), Best)) {
Douglas Gregore6985fe2008-11-10 16:14:15 +00002920 case OR_Success:
2921 // This is a direct binding.
2922 BindsDirectly = true;
2923
2924 if (ICS) {
2925 // C++ [over.ics.ref]p1:
2926 //
2927 // [...] If the parameter binds directly to the result of
2928 // applying a conversion function to the argument
2929 // expression, the implicit conversion sequence is a
2930 // user-defined conversion sequence (13.3.3.1.2), with the
2931 // second standard conversion sequence either an identity
2932 // conversion or, if the conversion function returns an
2933 // entity of a type that is a derived class of the parameter
2934 // type, a derived-to-base Conversion.
2935 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
2936 ICS->UserDefined.Before = Best->Conversions[0].Standard;
2937 ICS->UserDefined.After = Best->FinalConversion;
2938 ICS->UserDefined.ConversionFunction = Best->Function;
2939 assert(ICS->UserDefined.After.ReferenceBinding &&
2940 ICS->UserDefined.After.DirectBinding &&
2941 "Expected a direct reference binding!");
2942 return false;
2943 } else {
2944 // Perform the conversion.
Mike Stumpe127ae32009-05-16 07:39:55 +00002945 // FIXME: Binding to a subobject of the lvalue is going to require more
2946 // AST annotation than this.
Anders Carlsson85186942009-07-31 01:23:52 +00002947 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00002948 }
2949 break;
2950
2951 case OR_Ambiguous:
2952 assert(false && "Ambiguous reference binding conversions not implemented.");
2953 return true;
2954
2955 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00002956 case OR_Deleted:
2957 // There was no suitable conversion, or we found a deleted
2958 // conversion; continue with other checks.
Douglas Gregore6985fe2008-11-10 16:14:15 +00002959 break;
2960 }
2961 }
2962
Douglas Gregor81c29152008-10-29 00:13:59 +00002963 if (BindsDirectly) {
2964 // C++ [dcl.init.ref]p4:
2965 // [...] In all cases where the reference-related or
2966 // reference-compatible relationship of two types is used to
2967 // establish the validity of a reference binding, and T1 is a
2968 // base class of T2, a program that necessitates such a binding
2969 // is ill-formed if T1 is an inaccessible (clause 11) or
2970 // ambiguous (10.2) base class of T2.
2971 //
2972 // Note that we only check this condition when we're allowed to
2973 // complain about errors, because we should not be checking for
2974 // ambiguity (or inaccessibility) unless the reference binding
2975 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002976 if (DerivedToBase)
2977 return CheckDerivedToBaseConversion(T2, T1,
2978 Init->getSourceRange().getBegin(),
2979 Init->getSourceRange());
2980 else
2981 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00002982 }
2983
2984 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redldfc30332009-03-29 15:27:50 +00002985 // type (i.e., cv1 shall be const), or the reference shall be an
2986 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002987 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002988 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00002989 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00002990 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002991 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2992 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00002993 return true;
2994 }
2995
2996 // -- If the initializer expression is an rvalue, with T2 a
Eli Friedmand5a72f02009-08-05 19:21:58 +00002997 // class type, and "cv1 T1" is reference-compatible with
2998 // "cv2 T2," the reference is bound in one of the
Douglas Gregor81c29152008-10-29 00:13:59 +00002999 // following ways (the choice is implementation-defined):
3000 //
3001 // -- The reference is bound to the object represented by
3002 // the rvalue (see 3.10) or to a sub-object within that
3003 // object.
3004 //
Eli Friedmand5a72f02009-08-05 19:21:58 +00003005 // -- A temporary of type "cv1 T2" [sic] is created, and
Douglas Gregor81c29152008-10-29 00:13:59 +00003006 // a constructor is called to copy the entire rvalue
3007 // object into the temporary. The reference is bound to
3008 // the temporary or to a sub-object within the
3009 // temporary.
3010 //
Douglas Gregor81c29152008-10-29 00:13:59 +00003011 // The constructor that would be used to make the copy
3012 // shall be callable whether or not the copy is actually
3013 // done.
3014 //
Sebastian Redldfc30332009-03-29 15:27:50 +00003015 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor81c29152008-10-29 00:13:59 +00003016 // freedom, so we will always take the first option and never build
3017 // a temporary in this case. FIXME: We will, however, have to check
3018 // for the presence of a copy constructor in C++98/03 mode.
3019 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003020 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
3021 if (ICS) {
3022 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
3023 ICS->Standard.First = ICK_Identity;
3024 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
3025 ICS->Standard.Third = ICK_Identity;
3026 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
3027 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00003028 ICS->Standard.ReferenceBinding = true;
Sebastian Redldfc30332009-03-29 15:27:50 +00003029 ICS->Standard.DirectBinding = false;
3030 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redld3169132009-04-17 16:30:52 +00003031 ICS->Standard.CopyConstructor = 0;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003032 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +00003033 // FIXME: Binding to a subobject of the rvalue is going to require more
3034 // AST annotation than this.
Anders Carlsson85186942009-07-31 01:23:52 +00003035 ImpCastExprToType(Init, T1, CastExpr::CK_Unknown, /*isLvalue=*/false);
Douglas Gregor81c29152008-10-29 00:13:59 +00003036 }
3037 return false;
3038 }
3039
Eli Friedmand5a72f02009-08-05 19:21:58 +00003040 // -- Otherwise, a temporary of type "cv1 T1" is created and
Douglas Gregor81c29152008-10-29 00:13:59 +00003041 // initialized from the initializer expression using the
3042 // rules for a non-reference copy initialization (8.5). The
3043 // reference is then bound to the temporary. If T1 is
3044 // reference-related to T2, cv1 must be the same
3045 // cv-qualification as, or greater cv-qualification than,
3046 // cv2; otherwise, the program is ill-formed.
3047 if (RefRelationship == Ref_Related) {
3048 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3049 // we would be reference-compatible or reference-compatible with
3050 // added qualification. But that wasn't the case, so the reference
3051 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003052 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00003053 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00003054 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003055 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
3056 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00003057 return true;
3058 }
3059
Douglas Gregorb206cc42009-01-30 23:27:23 +00003060 // If at least one of the types is a class type, the types are not
3061 // related, and we aren't allowed any user conversions, the
3062 // reference binding fails. This case is important for breaking
3063 // recursion, since TryImplicitConversion below will attempt to
3064 // create a temporary through the use of a copy constructor.
3065 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
3066 (T1->isRecordType() || T2->isRecordType())) {
3067 if (!ICS)
3068 Diag(Init->getSourceRange().getBegin(),
3069 diag::err_typecheck_convert_incompatible)
3070 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
3071 return true;
3072 }
3073
Douglas Gregor81c29152008-10-29 00:13:59 +00003074 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003075 if (ICS) {
Sebastian Redldfc30332009-03-29 15:27:50 +00003076 // C++ [over.ics.ref]p2:
3077 //
3078 // When a parameter of reference type is not bound directly to
3079 // an argument expression, the conversion sequence is the one
3080 // required to convert the argument expression to the
3081 // underlying type of the reference according to
3082 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3083 // to copy-initializing a temporary of the underlying type with
3084 // the argument expression. Any difference in top-level
3085 // cv-qualification is subsumed by the initialization itself
3086 // and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00003087 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Sebastian Redldfc30332009-03-29 15:27:50 +00003088 // Of course, that's still a reference binding.
3089 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
3090 ICS->Standard.ReferenceBinding = true;
3091 ICS->Standard.RRefBinding = isRValRef;
3092 } else if(ICS->ConversionKind ==
3093 ImplicitConversionSequence::UserDefinedConversion) {
3094 ICS->UserDefined.After.ReferenceBinding = true;
3095 ICS->UserDefined.After.RRefBinding = isRValRef;
3096 }
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003097 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
3098 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00003099 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00003100 }
Douglas Gregor81c29152008-10-29 00:13:59 +00003101}
Douglas Gregore60e5d32008-11-06 22:13:31 +00003102
3103/// CheckOverloadedOperatorDeclaration - Check whether the declaration
3104/// of this overloaded operator is well-formed. If so, returns false;
3105/// otherwise, emits appropriate diagnostics and returns true.
3106bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003107 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00003108 "Expected an overloaded operator declaration");
3109
Douglas Gregore60e5d32008-11-06 22:13:31 +00003110 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
3111
3112 // C++ [over.oper]p5:
3113 // The allocation and deallocation functions, operator new,
3114 // operator new[], operator delete and operator delete[], are
3115 // described completely in 3.7.3. The attributes and restrictions
3116 // found in the rest of this subclause do not apply to them unless
3117 // explicitly stated in 3.7.3.
Mike Stumpe127ae32009-05-16 07:39:55 +00003118 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregore60e5d32008-11-06 22:13:31 +00003119 if (Op == OO_New || Op == OO_Array_New ||
3120 Op == OO_Delete || Op == OO_Array_Delete)
3121 return false;
3122
3123 // C++ [over.oper]p6:
3124 // An operator function shall either be a non-static member
3125 // function or be a non-member function and have at least one
3126 // parameter whose type is a class, a reference to a class, an
3127 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003128 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
3129 if (MethodDecl->isStatic())
3130 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00003131 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003132 } else {
3133 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003134 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
3135 ParamEnd = FnDecl->param_end();
3136 Param != ParamEnd; ++Param) {
3137 QualType ParamType = (*Param)->getType().getNonReferenceType();
Eli Friedmana73d6b12009-06-27 05:59:59 +00003138 if (ParamType->isDependentType() || ParamType->isRecordType() ||
3139 ParamType->isEnumeralType()) {
Douglas Gregore60e5d32008-11-06 22:13:31 +00003140 ClassOrEnumParam = true;
3141 break;
3142 }
3143 }
3144
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003145 if (!ClassOrEnumParam)
3146 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003147 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00003148 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003149 }
3150
3151 // C++ [over.oper]p8:
3152 // An operator function cannot have default arguments (8.3.6),
3153 // except where explicitly stated below.
3154 //
3155 // Only the function-call operator allows default arguments
3156 // (C++ [over.call]p1).
3157 if (Op != OO_Call) {
3158 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
3159 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +00003160 if ((*Param)->hasUnparsedDefaultArg())
3161 return Diag((*Param)->getLocation(),
3162 diag::err_operator_overload_default_arg)
3163 << FnDecl->getDeclName();
3164 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003165 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003166 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00003167 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003168 }
3169 }
3170
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003171 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
3172 { false, false, false }
3173#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
3174 , { Unary, Binary, MemberOnly }
3175#include "clang/Basic/OperatorKinds.def"
3176 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00003177
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003178 bool CanBeUnaryOperator = OperatorUses[Op][0];
3179 bool CanBeBinaryOperator = OperatorUses[Op][1];
3180 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00003181
3182 // C++ [over.oper]p8:
3183 // [...] Operator functions cannot have more or fewer parameters
3184 // than the number required for the corresponding operator, as
3185 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003186 unsigned NumParams = FnDecl->getNumParams()
3187 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00003188 if (Op != OO_Call &&
3189 ((NumParams == 1 && !CanBeUnaryOperator) ||
3190 (NumParams == 2 && !CanBeBinaryOperator) ||
3191 (NumParams < 1) || (NumParams > 2))) {
3192 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00003193 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003194 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00003195 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003196 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00003197 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003198 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00003199 assert(CanBeBinaryOperator &&
3200 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00003201 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00003202 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00003203
Chris Lattnerbb002332008-11-21 07:57:12 +00003204 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00003205 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00003206 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003207
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003208 // Overloaded operators other than operator() cannot be variadic.
3209 if (Op != OO_Call &&
Douglas Gregor4fa58902009-02-26 23:50:07 +00003210 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003211 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00003212 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003213 }
3214
3215 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003216 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
3217 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003218 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00003219 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00003220 }
3221
3222 // C++ [over.inc]p1:
3223 // The user-defined function called operator++ implements the
3224 // prefix and postfix ++ operator. If this function is a member
3225 // function with no parameters, or a non-member function with one
3226 // parameter of class or enumeration type, it defines the prefix
3227 // increment operator ++ for objects of that type. If the function
3228 // is a member function with one parameter (which shall be of type
3229 // int) or a non-member function with two parameters (the second
3230 // of which shall be of type int), it defines the postfix
3231 // increment operator ++ for objects of that type.
3232 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
3233 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
3234 bool ParamIsInt = false;
3235 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
3236 ParamIsInt = BT->getKind() == BuiltinType::Int;
3237
Chris Lattnera7021ee2008-11-21 07:50:02 +00003238 if (!ParamIsInt)
3239 return Diag(LastParam->getLocation(),
3240 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003241 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00003242 }
3243
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003244 // Notify the class if it got an assignment operator.
3245 if (Op == OO_Equal) {
3246 // Would have returned earlier otherwise.
3247 assert(isa<CXXMethodDecl>(FnDecl) &&
3248 "Overloaded = not member, but not filtered.");
3249 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Fariborz Jahanian9da58e42009-08-13 21:09:41 +00003250 Method->setCopyAssignment(true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003251 Method->getParent()->addedAssignmentOperator(Context, Method);
3252 }
3253
Douglas Gregor682a8cf2008-11-17 16:14:12 +00003254 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00003255}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00003256
Douglas Gregord8028382009-01-05 19:45:36 +00003257/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
3258/// linkage specification, including the language and (if present)
3259/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
3260/// the location of the language string literal, which is provided
3261/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
3262/// the '{' brace. Otherwise, this linkage specification does not
3263/// have any braces.
Chris Lattner5261d0c2009-03-28 19:18:32 +00003264Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
3265 SourceLocation ExternLoc,
3266 SourceLocation LangLoc,
3267 const char *Lang,
3268 unsigned StrSize,
3269 SourceLocation LBraceLoc) {
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003270 LinkageSpecDecl::LanguageIDs Language;
3271 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3272 Language = LinkageSpecDecl::lang_c;
3273 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3274 Language = LinkageSpecDecl::lang_cxx;
3275 else {
Douglas Gregord8028382009-01-05 19:45:36 +00003276 Diag(LangLoc, diag::err_bad_language);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003277 return DeclPtrTy();
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003278 }
3279
3280 // FIXME: Add all the various semantics of linkage specifications
3281
Douglas Gregord8028382009-01-05 19:45:36 +00003282 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
3283 LangLoc, Language,
3284 LBraceLoc.isValid());
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003285 CurContext->addDecl(D);
Douglas Gregord8028382009-01-05 19:45:36 +00003286 PushDeclContext(S, D);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003287 return DeclPtrTy::make(D);
Chris Lattner9bb9abf2008-12-17 07:13:27 +00003288}
3289
Douglas Gregord8028382009-01-05 19:45:36 +00003290/// ActOnFinishLinkageSpecification - Completely the definition of
3291/// the C++ linkage specification LinkageSpec. If RBraceLoc is
3292/// valid, it's the position of the closing '}' brace in a linkage
3293/// specification that uses braces.
Chris Lattner5261d0c2009-03-28 19:18:32 +00003294Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
3295 DeclPtrTy LinkageSpec,
3296 SourceLocation RBraceLoc) {
Douglas Gregord8028382009-01-05 19:45:36 +00003297 if (LinkageSpec)
3298 PopDeclContext();
3299 return LinkageSpec;
Chris Lattnerf58d52b2008-12-17 07:09:26 +00003300}
3301
Douglas Gregor57420b42009-05-18 20:51:54 +00003302/// \brief Perform semantic analysis for the variable declaration that
3303/// occurs within a C++ catch clause, returning the newly-created
3304/// variable.
3305VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003306 DeclaratorInfo *DInfo,
Douglas Gregor57420b42009-05-18 20:51:54 +00003307 IdentifierInfo *Name,
3308 SourceLocation Loc,
3309 SourceRange Range) {
3310 bool Invalid = false;
Sebastian Redl743c8162008-12-22 19:15:10 +00003311
3312 // Arrays and functions decay.
3313 if (ExDeclType->isArrayType())
3314 ExDeclType = Context.getArrayDecayedType(ExDeclType);
3315 else if (ExDeclType->isFunctionType())
3316 ExDeclType = Context.getPointerType(ExDeclType);
3317
3318 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
3319 // The exception-declaration shall not denote a pointer or reference to an
3320 // incomplete type, other than [cv] void*.
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003321 // N2844 forbids rvalue references.
Douglas Gregor3b7e9112009-05-18 21:08:14 +00003322 if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor57420b42009-05-18 20:51:54 +00003323 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003324 Invalid = true;
3325 }
Douglas Gregor57420b42009-05-18 20:51:54 +00003326
Sebastian Redl743c8162008-12-22 19:15:10 +00003327 QualType BaseType = ExDeclType;
3328 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003329 unsigned DK = diag::err_catch_incomplete;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003330 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
Sebastian Redl743c8162008-12-22 19:15:10 +00003331 BaseType = Ptr->getPointeeType();
3332 Mode = 1;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003333 DK = diag::err_catch_incomplete_ptr;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003334 } else if(const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003335 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl743c8162008-12-22 19:15:10 +00003336 BaseType = Ref->getPointeeType();
3337 Mode = 2;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003338 DK = diag::err_catch_incomplete_ref;
Sebastian Redl743c8162008-12-22 19:15:10 +00003339 }
Sebastian Redl8a8b3512009-03-22 23:49:27 +00003340 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor57420b42009-05-18 20:51:54 +00003341 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl743c8162008-12-22 19:15:10 +00003342 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00003343
Douglas Gregor57420b42009-05-18 20:51:54 +00003344 if (!Invalid && !ExDeclType->isDependentType() &&
3345 RequireNonAbstractType(Loc, ExDeclType,
3346 diag::err_abstract_type_in_decl,
3347 AbstractVariableType))
Sebastian Redl54198652009-04-27 21:03:30 +00003348 Invalid = true;
3349
Douglas Gregor57420b42009-05-18 20:51:54 +00003350 // FIXME: Need to test for ability to copy-construct and destroy the
3351 // exception variable.
3352
Sebastian Redl237116b2008-12-22 21:35:02 +00003353 // FIXME: Need to check for abstract classes.
3354
Douglas Gregor57420b42009-05-18 20:51:54 +00003355 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
Argiris Kirtzidis42556e42009-08-21 00:31:54 +00003356 Name, ExDeclType, DInfo, VarDecl::None);
Douglas Gregor57420b42009-05-18 20:51:54 +00003357
3358 if (Invalid)
3359 ExDecl->setInvalidDecl();
3360
3361 return ExDecl;
3362}
3363
3364/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
3365/// handler.
3366Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003367 DeclaratorInfo *DInfo = 0;
3368 QualType ExDeclType = GetTypeForDeclarator(D, S, &DInfo);
Douglas Gregor57420b42009-05-18 20:51:54 +00003369
3370 bool Invalid = D.isInvalidType();
Sebastian Redl743c8162008-12-22 19:15:10 +00003371 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor09be81b2009-02-04 17:27:36 +00003372 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl743c8162008-12-22 19:15:10 +00003373 // The scope should be freshly made just for us. There is just no way
3374 // it contains any previous declaration.
Chris Lattner5261d0c2009-03-28 19:18:32 +00003375 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl743c8162008-12-22 19:15:10 +00003376 if (PrevDecl->isTemplateParameter()) {
3377 // Maybe we will complain about the shadowed template parameter.
3378 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003379 }
3380 }
3381
Chris Lattner34c61332009-04-25 08:06:05 +00003382 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl743c8162008-12-22 19:15:10 +00003383 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
3384 << D.getCXXScopeSpec().getRange();
Chris Lattner34c61332009-04-25 08:06:05 +00003385 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00003386 }
3387
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003388 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType, DInfo,
Douglas Gregor57420b42009-05-18 20:51:54 +00003389 D.getIdentifier(),
3390 D.getIdentifierLoc(),
3391 D.getDeclSpec().getSourceRange());
3392
Chris Lattner34c61332009-04-25 08:06:05 +00003393 if (Invalid)
3394 ExDecl->setInvalidDecl();
3395
Sebastian Redl743c8162008-12-22 19:15:10 +00003396 // Add the exception declaration into this scope.
Sebastian Redl743c8162008-12-22 19:15:10 +00003397 if (II)
Douglas Gregor57420b42009-05-18 20:51:54 +00003398 PushOnScopeChains(ExDecl, S);
3399 else
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003400 CurContext->addDecl(ExDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003401
Douglas Gregor2a2e0402009-06-17 21:51:59 +00003402 ProcessDeclAttributes(S, ExDecl, D);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003403 return DeclPtrTy::make(ExDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00003404}
Anders Carlssoned691562009-03-14 00:25:26 +00003405
Chris Lattner5261d0c2009-03-28 19:18:32 +00003406Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
3407 ExprArg assertexpr,
3408 ExprArg assertmessageexpr) {
Anders Carlssoned691562009-03-14 00:25:26 +00003409 Expr *AssertExpr = (Expr *)assertexpr.get();
3410 StringLiteral *AssertMessage =
3411 cast<StringLiteral>((Expr *)assertmessageexpr.get());
3412
Anders Carlsson8b842c52009-03-14 00:33:21 +00003413 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
3414 llvm::APSInt Value(32);
3415 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
3416 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
3417 AssertExpr->getSourceRange();
Chris Lattner5261d0c2009-03-28 19:18:32 +00003418 return DeclPtrTy();
Anders Carlsson8b842c52009-03-14 00:33:21 +00003419 }
Anders Carlssoned691562009-03-14 00:25:26 +00003420
Anders Carlsson8b842c52009-03-14 00:33:21 +00003421 if (Value == 0) {
3422 std::string str(AssertMessage->getStrData(),
3423 AssertMessage->getByteLength());
Anders Carlssonc45057a2009-03-15 18:44:04 +00003424 Diag(AssertLoc, diag::err_static_assert_failed)
3425 << str << AssertExpr->getSourceRange();
Anders Carlsson8b842c52009-03-14 00:33:21 +00003426 }
3427 }
3428
Anders Carlsson0f4942b2009-03-15 17:35:16 +00003429 assertexpr.release();
3430 assertmessageexpr.release();
Anders Carlssoned691562009-03-14 00:25:26 +00003431 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
3432 AssertExpr, AssertMessage);
Anders Carlssoned691562009-03-14 00:25:26 +00003433
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003434 CurContext->addDecl(Decl);
Chris Lattner5261d0c2009-03-28 19:18:32 +00003435 return DeclPtrTy::make(Decl);
Anders Carlssoned691562009-03-14 00:25:26 +00003436}
Sebastian Redla8cecf62009-03-24 22:27:57 +00003437
John McCall140607b2009-08-06 02:15:43 +00003438Sema::DeclPtrTy Sema::ActOnFriendDecl(Scope *S,
John McCall36493082009-08-11 06:59:38 +00003439 llvm::PointerUnion<const DeclSpec*,Declarator*> DU,
3440 bool IsDefinition) {
John McCall140607b2009-08-06 02:15:43 +00003441 Declarator *D = DU.dyn_cast<Declarator*>();
3442 const DeclSpec &DS = (D ? D->getDeclSpec() : *DU.get<const DeclSpec*>());
3443
3444 assert(DS.isFriendSpecified());
3445 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
3446
3447 // If there's no declarator, then this can only be a friend class
John McCall7be34f42009-08-11 21:13:21 +00003448 // declaration (or else it's just syntactically invalid).
John McCall140607b2009-08-06 02:15:43 +00003449 if (!D) {
John McCall7be34f42009-08-11 21:13:21 +00003450 SourceLocation Loc = DS.getSourceRange().getBegin();
John McCall140607b2009-08-06 02:15:43 +00003451
John McCall7be34f42009-08-11 21:13:21 +00003452 QualType T;
3453 DeclContext *DC;
John McCall140607b2009-08-06 02:15:43 +00003454
John McCall7be34f42009-08-11 21:13:21 +00003455 // In C++0x, we just accept any old type.
3456 if (getLangOptions().CPlusPlus0x) {
3457 bool invalid = false;
3458 QualType T = ConvertDeclSpecToType(DS, Loc, invalid);
3459 if (invalid)
3460 return DeclPtrTy();
John McCall140607b2009-08-06 02:15:43 +00003461
John McCall7be34f42009-08-11 21:13:21 +00003462 // The semantic context in which to create the decl. If it's not
3463 // a record decl (or we don't yet know if it is), create it in the
3464 // current context.
3465 DC = CurContext;
3466 if (const RecordType *RT = T->getAs<RecordType>())
3467 DC = RT->getDecl()->getDeclContext();
3468
3469 // The C++98 rules are somewhat more complex.
3470 } else {
3471 // C++ [class.friend]p2:
3472 // An elaborated-type-specifier shall be used in a friend declaration
3473 // for a class.*
3474 // * The class-key of the elaborated-type-specifier is required.
3475 CXXRecordDecl *RD = 0;
3476
3477 switch (DS.getTypeSpecType()) {
3478 case DeclSpec::TST_class:
3479 case DeclSpec::TST_struct:
3480 case DeclSpec::TST_union:
3481 RD = dyn_cast_or_null<CXXRecordDecl>((Decl*) DS.getTypeRep());
3482 if (!RD) return DeclPtrTy();
3483 break;
3484
3485 case DeclSpec::TST_typename:
3486 if (const RecordType *RT =
3487 ((const Type*) DS.getTypeRep())->getAs<RecordType>())
3488 RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
3489 // fallthrough
3490 default:
3491 if (RD) {
3492 Diag(DS.getFriendSpecLoc(), diag::err_unelaborated_friend_type)
3493 << (RD->isUnion())
3494 << CodeModificationHint::CreateInsertion(DS.getTypeSpecTypeLoc(),
3495 RD->isUnion() ? " union" : " class");
3496 return DeclPtrTy::make(RD);
3497 }
3498
3499 Diag(DS.getFriendSpecLoc(), diag::err_unexpected_friend)
3500 << DS.getSourceRange();
3501 return DeclPtrTy();
John McCall140607b2009-08-06 02:15:43 +00003502 }
3503
John McCall7be34f42009-08-11 21:13:21 +00003504 // The record declaration we get from friend declarations is not
3505 // canonicalized; see ActOnTag.
John McCall7be34f42009-08-11 21:13:21 +00003506
3507 // C++ [class.friend]p2: A class shall not be defined inside
3508 // a friend declaration.
3509 if (RD->isDefinition())
3510 Diag(DS.getFriendSpecLoc(), diag::err_friend_decl_defines_class)
3511 << RD->getSourceRange();
3512
3513 // C++98 [class.friend]p1: A friend of a class is a function
3514 // or class that is not a member of the class . . .
3515 // But that's a silly restriction which nobody implements for
3516 // inner classes, and C++0x removes it anyway, so we only report
3517 // this (as a warning) if we're being pedantic.
3518 //
3519 // Also, definitions currently get treated in a way that causes
3520 // this error, so only report it if we didn't see a definition.
3521 else if (RD->getDeclContext() == CurContext &&
3522 !getLangOptions().CPlusPlus0x)
3523 Diag(DS.getFriendSpecLoc(), diag::ext_friend_inner_class);
3524
3525 T = QualType(RD->getTypeForDecl(), 0);
3526 DC = RD->getDeclContext();
John McCall140607b2009-08-06 02:15:43 +00003527 }
3528
John McCall7be34f42009-08-11 21:13:21 +00003529 FriendClassDecl *FCD = FriendClassDecl::Create(Context, DC, Loc, T,
3530 DS.getFriendSpecLoc());
3531 FCD->setLexicalDeclContext(CurContext);
John McCall140607b2009-08-06 02:15:43 +00003532
John McCall7be34f42009-08-11 21:13:21 +00003533 if (CurContext->isDependentContext())
3534 CurContext->addHiddenDecl(FCD);
3535 else
3536 CurContext->addDecl(FCD);
John McCall140607b2009-08-06 02:15:43 +00003537
John McCall7be34f42009-08-11 21:13:21 +00003538 return DeclPtrTy::make(FCD);
Anders Carlssonb56d8b32009-05-11 22:55:49 +00003539 }
John McCall140607b2009-08-06 02:15:43 +00003540
3541 // We have a declarator.
3542 assert(D);
3543
3544 SourceLocation Loc = D->getIdentifierLoc();
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003545 DeclaratorInfo *DInfo = 0;
3546 QualType T = GetTypeForDeclarator(*D, S, &DInfo);
John McCall140607b2009-08-06 02:15:43 +00003547
3548 // C++ [class.friend]p1
3549 // A friend of a class is a function or class....
3550 // Note that this sees through typedefs, which is intended.
3551 if (!T->isFunctionType()) {
3552 Diag(Loc, diag::err_unexpected_friend);
3553
3554 // It might be worthwhile to try to recover by creating an
3555 // appropriate declaration.
3556 return DeclPtrTy();
3557 }
3558
3559 // C++ [namespace.memdef]p3
3560 // - If a friend declaration in a non-local class first declares a
3561 // class or function, the friend class or function is a member
3562 // of the innermost enclosing namespace.
3563 // - The name of the friend is not found by simple name lookup
3564 // until a matching declaration is provided in that namespace
3565 // scope (either before or after the class declaration granting
3566 // friendship).
3567 // - If a friend function is called, its name may be found by the
3568 // name lookup that considers functions from namespaces and
3569 // classes associated with the types of the function arguments.
3570 // - When looking for a prior declaration of a class or a function
3571 // declared as a friend, scopes outside the innermost enclosing
3572 // namespace scope are not considered.
3573
3574 CXXScopeSpec &ScopeQual = D->getCXXScopeSpec();
3575 DeclarationName Name = GetNameForDeclarator(*D);
3576 assert(Name);
3577
3578 // The existing declaration we found.
3579 FunctionDecl *FD = NULL;
3580
3581 // The context we found the declaration in, or in which we should
3582 // create the declaration.
3583 DeclContext *DC;
3584
3585 // FIXME: handle local classes
3586
3587 // Recover from invalid scope qualifiers as if they just weren't there.
3588 if (!ScopeQual.isInvalid() && ScopeQual.isSet()) {
3589 DC = computeDeclContext(ScopeQual);
3590
3591 // FIXME: handle dependent contexts
3592 if (!DC) return DeclPtrTy();
3593
3594 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3595
3596 // If searching in that context implicitly found a declaration in
3597 // a different context, treat it like it wasn't found at all.
3598 // TODO: better diagnostics for this case. Suggesting the right
3599 // qualified scope would be nice...
3600 if (!Dec || Dec->getDeclContext() != DC) {
3601 D->setInvalidType();
3602 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
3603 return DeclPtrTy();
3604 }
3605
3606 // C++ [class.friend]p1: A friend of a class is a function or
3607 // class that is not a member of the class . . .
3608 if (DC == CurContext)
3609 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
3610
3611 FD = cast<FunctionDecl>(Dec);
3612
3613 // Otherwise walk out to the nearest namespace scope looking for matches.
3614 } else {
3615 // TODO: handle local class contexts.
3616
3617 DC = CurContext;
3618 while (true) {
3619 // Skip class contexts. If someone can cite chapter and verse
3620 // for this behavior, that would be nice --- it's what GCC and
3621 // EDG do, and it seems like a reasonable intent, but the spec
3622 // really only says that checks for unqualified existing
3623 // declarations should stop at the nearest enclosing namespace,
3624 // not that they should only consider the nearest enclosing
3625 // namespace.
3626 while (DC->isRecord()) DC = DC->getParent();
3627
3628 Decl *Dec = LookupQualifiedNameWithType(DC, Name, T);
3629
3630 // TODO: decide what we think about using declarations.
3631 if (Dec) {
3632 FD = cast<FunctionDecl>(Dec);
3633 break;
3634 }
3635 if (DC->isFileContext()) break;
3636 DC = DC->getParent();
3637 }
3638
3639 // C++ [class.friend]p1: A friend of a class is a function or
3640 // class that is not a member of the class . . .
John McCall392245a2009-08-06 20:49:32 +00003641 // C++0x changes this for both friend types and functions.
3642 // Most C++ 98 compilers do seem to give an error here, so
3643 // we do, too.
3644 if (FD && DC == CurContext && !getLangOptions().CPlusPlus0x)
John McCall140607b2009-08-06 02:15:43 +00003645 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
3646 }
3647
John McCall36493082009-08-11 06:59:38 +00003648 bool Redeclaration = (FD != 0);
3649
3650 // If we found a match, create a friend function declaration with
3651 // that function as the previous declaration.
3652 if (Redeclaration) {
3653 // Create it in the semantic context of the original declaration.
3654 DC = FD->getDeclContext();
3655
John McCall140607b2009-08-06 02:15:43 +00003656 // If we didn't find something matching the type exactly, create
3657 // a declaration. This declaration should only be findable via
3658 // argument-dependent lookup.
John McCall36493082009-08-11 06:59:38 +00003659 } else {
John McCall140607b2009-08-06 02:15:43 +00003660 assert(DC->isFileContext());
3661
3662 // This implies that it has to be an operator or function.
3663 if (D->getKind() == Declarator::DK_Constructor ||
3664 D->getKind() == Declarator::DK_Destructor ||
3665 D->getKind() == Declarator::DK_Conversion) {
3666 Diag(Loc, diag::err_introducing_special_friend) <<
3667 (D->getKind() == Declarator::DK_Constructor ? 0 :
3668 D->getKind() == Declarator::DK_Destructor ? 1 : 2);
3669 return DeclPtrTy();
3670 }
John McCall140607b2009-08-06 02:15:43 +00003671 }
3672
Argiris Kirtzidisb17120c2009-08-19 01:27:57 +00003673 NamedDecl *ND = ActOnFunctionDeclarator(S, *D, DC, T, DInfo,
John McCall36493082009-08-11 06:59:38 +00003674 /* PrevDecl = */ FD,
3675 MultiTemplateParamsArg(*this),
3676 IsDefinition,
3677 Redeclaration);
3678 FD = cast_or_null<FriendFunctionDecl>(ND);
3679
John McCallbcee9272009-08-18 00:00:49 +00003680 assert(FD->getDeclContext() == DC);
3681 assert(FD->getLexicalDeclContext() == CurContext);
3682
John McCall36493082009-08-11 06:59:38 +00003683 // If this is a dependent context, just add the decl to the
3684 // class's decl list and don't both with the lookup tables. This
3685 // doesn't affect lookup because any call that might find this
3686 // function via ADL necessarily has to involve dependently-typed
3687 // arguments and hence can't be resolved until
3688 // template-instantiation anyway.
3689 if (CurContext->isDependentContext())
3690 CurContext->addHiddenDecl(FD);
3691 else
3692 CurContext->addDecl(FD);
John McCall140607b2009-08-06 02:15:43 +00003693
3694 return DeclPtrTy::make(FD);
Anders Carlssonb56d8b32009-05-11 22:55:49 +00003695}
3696
Chris Lattner5261d0c2009-03-28 19:18:32 +00003697void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
Douglas Gregor84164f02009-08-24 11:57:43 +00003698 AdjustDeclIfTemplate(dcl);
3699
Chris Lattner5261d0c2009-03-28 19:18:32 +00003700 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redla8cecf62009-03-24 22:27:57 +00003701 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
3702 if (!Fn) {
3703 Diag(DelLoc, diag::err_deleted_non_function);
3704 return;
3705 }
3706 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
3707 Diag(DelLoc, diag::err_deleted_decl_not_first);
3708 Diag(Prev->getLocation(), diag::note_previous_declaration);
3709 // If the declaration wasn't the first, we delete the function anyway for
3710 // recovery.
3711 }
3712 Fn->setDeleted();
3713}
Sebastian Redl3b1ef312009-04-27 21:33:24 +00003714
3715static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
3716 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
3717 ++CI) {
3718 Stmt *SubStmt = *CI;
3719 if (!SubStmt)
3720 continue;
3721 if (isa<ReturnStmt>(SubStmt))
3722 Self.Diag(SubStmt->getSourceRange().getBegin(),
3723 diag::err_return_in_constructor_handler);
3724 if (!isa<Expr>(SubStmt))
3725 SearchForReturnInStmt(Self, SubStmt);
3726 }
3727}
3728
3729void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
3730 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
3731 CXXCatchStmt *Handler = TryBlock->getHandler(I);
3732 SearchForReturnInStmt(*this, Handler);
3733 }
3734}
Anders Carlssone80e29c2009-05-14 01:09:04 +00003735
3736bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
3737 const CXXMethodDecl *Old) {
3738 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
3739 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
3740
3741 QualType CNewTy = Context.getCanonicalType(NewTy);
3742 QualType COldTy = Context.getCanonicalType(OldTy);
3743
3744 if (CNewTy == COldTy &&
3745 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
3746 return false;
3747
Anders Carlssonee7177b2009-05-14 19:52:19 +00003748 // Check if the return types are covariant
3749 QualType NewClassTy, OldClassTy;
3750
3751 /// Both types must be pointers or references to classes.
3752 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
3753 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
3754 NewClassTy = NewPT->getPointeeType();
3755 OldClassTy = OldPT->getPointeeType();
3756 }
3757 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
3758 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
3759 NewClassTy = NewRT->getPointeeType();
3760 OldClassTy = OldRT->getPointeeType();
3761 }
3762 }
3763
3764 // The return types aren't either both pointers or references to a class type.
3765 if (NewClassTy.isNull()) {
3766 Diag(New->getLocation(),
3767 diag::err_different_return_type_for_overriding_virtual_function)
3768 << New->getDeclName() << NewTy << OldTy;
3769 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3770
3771 return true;
3772 }
Anders Carlssone80e29c2009-05-14 01:09:04 +00003773
Anders Carlssonee7177b2009-05-14 19:52:19 +00003774 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
3775 // Check if the new class derives from the old class.
3776 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
3777 Diag(New->getLocation(),
3778 diag::err_covariant_return_not_derived)
3779 << New->getDeclName() << NewTy << OldTy;
3780 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3781 return true;
3782 }
3783
3784 // Check if we the conversion from derived to base is valid.
3785 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
3786 diag::err_covariant_return_inaccessible_base,
3787 diag::err_covariant_return_ambiguous_derived_to_base_conv,
3788 // FIXME: Should this point to the return type?
3789 New->getLocation(), SourceRange(), New->getDeclName())) {
3790 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3791 return true;
3792 }
3793 }
3794
3795 // The qualifiers of the return types must be the same.
3796 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
3797 Diag(New->getLocation(),
3798 diag::err_covariant_return_type_different_qualifications)
Anders Carlssone80e29c2009-05-14 01:09:04 +00003799 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonee7177b2009-05-14 19:52:19 +00003800 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3801 return true;
3802 };
3803
3804
3805 // The new class type must have the same or less qualifiers as the old type.
3806 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
3807 Diag(New->getLocation(),
3808 diag::err_covariant_return_type_class_type_more_qualified)
3809 << New->getDeclName() << NewTy << OldTy;
3810 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3811 return true;
3812 };
3813
3814 return false;
Anders Carlssone80e29c2009-05-14 01:09:04 +00003815}
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003816
Sebastian Redl953d12a2009-07-07 20:29:57 +00003817bool Sema::CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
3818 const CXXMethodDecl *Old)
3819{
3820 return CheckExceptionSpecSubset(diag::err_override_exception_spec,
3821 diag::note_overridden_virtual_function,
3822 Old->getType()->getAsFunctionProtoType(),
3823 Old->getLocation(),
3824 New->getType()->getAsFunctionProtoType(),
3825 New->getLocation());
3826}
3827
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003828/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
3829/// initializer for the declaration 'Dcl'.
3830/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
3831/// static data member of class X, names should be looked up in the scope of
3832/// class X.
3833void Sema::ActOnCXXEnterDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregor84164f02009-08-24 11:57:43 +00003834 AdjustDeclIfTemplate(Dcl);
3835
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003836 Decl *D = Dcl.getAs<Decl>();
3837 // If there is no declaration, there was an error parsing it.
3838 if (D == 0)
3839 return;
3840
3841 // Check whether it is a declaration with a nested name specifier like
3842 // int foo::bar;
3843 if (!D->isOutOfLine())
3844 return;
3845
3846 // C++ [basic.lookup.unqual]p13
3847 //
3848 // A name used in the definition of a static data member of class X
3849 // (after the qualified-id of the static member) is looked up as if the name
3850 // was used in a member function of X.
3851
3852 // Change current context into the context of the initializing declaration.
Argiris Kirtzidisa0b19fe2009-06-17 23:15:40 +00003853 EnterDeclaratorContext(S, D->getDeclContext());
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003854}
3855
3856/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
3857/// initializer for the declaration 'Dcl'.
3858void Sema::ActOnCXXExitDeclInitializer(Scope *S, DeclPtrTy Dcl) {
Douglas Gregor84164f02009-08-24 11:57:43 +00003859 AdjustDeclIfTemplate(Dcl);
3860
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003861 Decl *D = Dcl.getAs<Decl>();
3862 // If there is no declaration, there was an error parsing it.
3863 if (D == 0)
3864 return;
3865
3866 // Check whether it is a declaration with a nested name specifier like
3867 // int foo::bar;
3868 if (!D->isOutOfLine())
3869 return;
3870
3871 assert(S->getEntity() == D->getDeclContext() && "Context imbalance!");
Argiris Kirtzidisa0b19fe2009-06-17 23:15:40 +00003872 ExitDeclaratorContext(S);
Argiris Kirtzidis68370592009-06-17 22:50:06 +00003873}