blob: 8f64e78c522b422180937e0e110bbbadba9d8dc4 [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
104/// ActOnParamDefaultArgument - Check whether the default argument
105/// provided for a function parameter is well-formed. If so, attach it
106/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000107void
Chris Lattner5261d0c2009-03-28 19:18:32 +0000108Sema::ActOnParamDefaultArgument(DeclPtrTy param, SourceLocation EqualLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +0000109 ExprArg defarg) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000110 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Anders Carlssona116e6e2009-06-12 16:51:40 +0000111 UnparsedDefaultArgLocs.erase(Param);
112
Anders Carlssonc154a722009-05-01 19:30:39 +0000113 ExprOwningPtr<Expr> DefaultArg(this, defarg.takeAs<Expr>());
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000114 QualType ParamType = Param->getType();
115
116 // Default arguments are only permitted in C++
117 if (!getLangOptions().CPlusPlus) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000118 Diag(EqualLoc, diag::err_param_default_argument)
119 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000120 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000121 return;
122 }
123
124 // C++ [dcl.fct.default]p5
125 // A default argument expression is implicitly converted (clause
126 // 4) to the parameter type. The default argument expression has
127 // the same semantic constraints as the initializer expression in
128 // a declaration of a variable of the parameter type, using the
129 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000130 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000131 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
132 EqualLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000133 Param->getDeclName(),
134 /*DirectInit=*/false);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000135 if (DefaultArgPtr != DefaultArg.get()) {
136 DefaultArg.take();
137 DefaultArg.reset(DefaultArgPtr);
138 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000139 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000140 return;
141 }
142
Chris Lattner97316c02008-04-10 02:22:51 +0000143 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000144 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000145 if (DefaultArgChecker.Visit(DefaultArg.get())) {
146 Param->setInvalidDecl();
Chris Lattner97316c02008-04-10 02:22:51 +0000147 return;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000148 }
Chris Lattner97316c02008-04-10 02:22:51 +0000149
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000150 // Okay: add the default argument to the parameter
151 Param->setDefaultArg(DefaultArg.take());
152}
153
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000154/// ActOnParamUnparsedDefaultArgument - We've seen a default
155/// argument for a function parameter, but we can't parse it yet
156/// because we're inside a class definition. Note that this default
157/// argument will be parsed later.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000158void Sema::ActOnParamUnparsedDefaultArgument(DeclPtrTy param,
Anders Carlssona116e6e2009-06-12 16:51:40 +0000159 SourceLocation EqualLoc,
160 SourceLocation ArgLoc) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000161 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000162 if (Param)
163 Param->setUnparsedDefaultArg();
Anders Carlssona116e6e2009-06-12 16:51:40 +0000164
165 UnparsedDefaultArgLocs[Param] = ArgLoc;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000166}
167
Douglas Gregor605de8d2008-12-16 21:30:33 +0000168/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
169/// the default argument for the parameter param failed.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000170void Sema::ActOnParamDefaultArgumentError(DeclPtrTy param) {
Anders Carlssona116e6e2009-06-12 16:51:40 +0000171 ParmVarDecl *Param = cast<ParmVarDecl>(param.getAs<Decl>());
172
173 Param->setInvalidDecl();
174
175 UnparsedDefaultArgLocs.erase(Param);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000176}
177
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000178/// CheckExtraCXXDefaultArguments - Check for any extra default
179/// arguments in the declarator, which is not a function declaration
180/// or definition and therefore is not permitted to have default
181/// arguments. This routine should be invoked for every declarator
182/// that is not a function declaration or definition.
183void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
184 // C++ [dcl.fct.default]p3
185 // A default argument expression shall be specified only in the
186 // parameter-declaration-clause of a function declaration or in a
187 // template-parameter (14.1). It shall not be specified for a
188 // parameter pack. If it is specified in a
189 // parameter-declaration-clause, it shall not occur within a
190 // declarator or abstract-declarator of a parameter-declaration.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000191 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000192 DeclaratorChunk &chunk = D.getTypeObject(i);
193 if (chunk.Kind == DeclaratorChunk::Function) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000194 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
195 ParmVarDecl *Param =
196 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000197 if (Param->hasUnparsedDefaultArg()) {
198 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000199 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
200 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
201 delete Toks;
202 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000203 } else if (Param->getDefaultArg()) {
204 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
205 << Param->getDefaultArg()->getSourceRange();
206 Param->setDefaultArg(0);
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000207 }
208 }
209 }
210 }
211}
212
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000213// MergeCXXFunctionDecl - Merge two declarations of the same C++
214// function, once we already know that they have the same
Douglas Gregor083c23e2009-02-16 17:45:42 +0000215// type. Subroutine of MergeFunctionDecl. Returns true if there was an
216// error, false otherwise.
217bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
218 bool Invalid = false;
219
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000220 // C++ [dcl.fct.default]p4:
221 //
222 // For non-template functions, default arguments can be added in
223 // later declarations of a function in the same
224 // scope. Declarations in different scopes have completely
225 // distinct sets of default arguments. That is, declarations in
226 // inner scopes do not acquire default arguments from
227 // declarations in outer scopes, and vice versa. In a given
228 // function declaration, all parameters subsequent to a
229 // parameter with a default argument shall have default
230 // arguments supplied in this or previous declarations. A
231 // default argument shall not be redefined by a later
232 // declaration (not even to the same value).
233 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
234 ParmVarDecl *OldParam = Old->getParamDecl(p);
235 ParmVarDecl *NewParam = New->getParamDecl(p);
236
237 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
238 Diag(NewParam->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000239 diag::err_param_default_argument_redefinition)
240 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000241 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregor083c23e2009-02-16 17:45:42 +0000242 Invalid = true;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000243 } else if (OldParam->getDefaultArg()) {
244 // Merge the old default argument into the new parameter
245 NewParam->setDefaultArg(OldParam->getDefaultArg());
246 }
247 }
248
Douglas Gregor083c23e2009-02-16 17:45:42 +0000249 return Invalid;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000250}
251
252/// CheckCXXDefaultArguments - Verify that the default arguments for a
253/// function declaration are well-formed according to C++
254/// [dcl.fct.default].
255void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
256 unsigned NumParams = FD->getNumParams();
257 unsigned p;
258
259 // Find first parameter with a default argument
260 for (p = 0; p < NumParams; ++p) {
261 ParmVarDecl *Param = FD->getParamDecl(p);
262 if (Param->getDefaultArg())
263 break;
264 }
265
266 // C++ [dcl.fct.default]p4:
267 // In a given function declaration, all parameters
268 // subsequent to a parameter with a default argument shall
269 // have default arguments supplied in this or previous
270 // declarations. A default argument shall not be redefined
271 // by a later declaration (not even to the same value).
272 unsigned LastMissingDefaultArg = 0;
273 for(; p < NumParams; ++p) {
274 ParmVarDecl *Param = FD->getParamDecl(p);
275 if (!Param->getDefaultArg()) {
Douglas Gregor605de8d2008-12-16 21:30:33 +0000276 if (Param->isInvalidDecl())
277 /* We already complained about this parameter. */;
278 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000279 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000280 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000281 << Param->getIdentifier();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000282 else
283 Diag(Param->getLocation(),
284 diag::err_param_default_argument_missing);
285
286 LastMissingDefaultArg = p;
287 }
288 }
289
290 if (LastMissingDefaultArg > 0) {
291 // Some default arguments were missing. Clear out all of the
292 // default arguments up to (and including) the last missing
293 // default argument, so that we leave the function parameters
294 // in a semantically valid state.
295 for (p = 0; p <= LastMissingDefaultArg; ++p) {
296 ParmVarDecl *Param = FD->getParamDecl(p);
Anders Carlssona116e6e2009-06-12 16:51:40 +0000297 if (Param->hasDefaultArg()) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000298 if (!Param->hasUnparsedDefaultArg())
299 Param->getDefaultArg()->Destroy(Context);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000300 Param->setDefaultArg(0);
301 }
302 }
303 }
304}
Douglas Gregorec93f442008-04-13 21:30:24 +0000305
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000306/// isCurrentClassName - Determine whether the identifier II is the
307/// name of the class type currently being defined. In the case of
308/// nested classes, this will only return true if II is the name of
309/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000310bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
311 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000312 CXXRecordDecl *CurDecl;
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000313 if (SS && SS->isSet() && !SS->isInvalid()) {
314 DeclContext *DC = computeDeclContext(*SS);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000315 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
316 } else
317 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
318
319 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000320 return &II == CurDecl->getIdentifier();
321 else
322 return false;
323}
324
Douglas Gregored3a3982009-03-03 04:44:36 +0000325/// \brief Check the validity of a C++ base class specifier.
326///
327/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
328/// and returns NULL otherwise.
329CXXBaseSpecifier *
330Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
331 SourceRange SpecifierRange,
332 bool Virtual, AccessSpecifier Access,
333 QualType BaseType,
334 SourceLocation BaseLoc) {
335 // C++ [class.union]p1:
336 // A union shall not have base classes.
337 if (Class->isUnion()) {
338 Diag(Class->getLocation(), diag::err_base_clause_on_union)
339 << SpecifierRange;
340 return 0;
341 }
342
343 if (BaseType->isDependentType())
344 return new CXXBaseSpecifier(SpecifierRange, Virtual,
345 Class->getTagKind() == RecordDecl::TK_class,
346 Access, BaseType);
347
348 // Base specifiers must be record types.
349 if (!BaseType->isRecordType()) {
350 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
351 return 0;
352 }
353
354 // C++ [class.union]p1:
355 // A union shall not be used as a base class.
356 if (BaseType->isUnionType()) {
357 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
358 return 0;
359 }
360
361 // C++ [class.derived]p2:
362 // The class-name in a base-specifier shall not be an incompletely
363 // defined class.
Douglas Gregorc84d8932009-03-09 16:13:40 +0000364 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
Douglas Gregor375733c2009-03-10 00:06:19 +0000365 SpecifierRange))
Douglas Gregored3a3982009-03-03 04:44:36 +0000366 return 0;
367
368 // If the base class is polymorphic, the new one is, too.
369 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
370 assert(BaseDecl && "Record type has no declaration");
371 BaseDecl = BaseDecl->getDefinition(Context);
372 assert(BaseDecl && "Base type is not incomplete, but has no definition");
373 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
374 Class->setPolymorphic(true);
375
376 // C++ [dcl.init.aggr]p1:
377 // An aggregate is [...] a class with [...] no base classes [...].
378 Class->setAggregate(false);
379 Class->setPOD(false);
380
Anders Carlssonc6363712009-04-16 00:08:20 +0000381 if (Virtual) {
382 // C++ [class.ctor]p5:
383 // A constructor is trivial if its class has no virtual base classes.
384 Class->setHasTrivialConstructor(false);
385 } else {
386 // C++ [class.ctor]p5:
387 // A constructor is trivial if all the direct base classes of its
388 // class have trivial constructors.
389 Class->setHasTrivialConstructor(cast<CXXRecordDecl>(BaseDecl)->
390 hasTrivialConstructor());
391 }
Anders Carlsson39a10db2009-04-17 02:34:54 +0000392
393 // C++ [class.ctor]p3:
394 // A destructor is trivial if all the direct base classes of its class
395 // have trivial destructors.
396 Class->setHasTrivialDestructor(cast<CXXRecordDecl>(BaseDecl)->
397 hasTrivialDestructor());
Anders Carlssonc6363712009-04-16 00:08:20 +0000398
Douglas Gregored3a3982009-03-03 04:44:36 +0000399 // Create the base specifier.
400 // FIXME: Allocate via ASTContext?
401 return new CXXBaseSpecifier(SpecifierRange, Virtual,
402 Class->getTagKind() == RecordDecl::TK_class,
403 Access, BaseType);
404}
405
Douglas Gregorec93f442008-04-13 21:30:24 +0000406/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
407/// one entry in the base class list of a class specifier, for
408/// example:
409/// class foo : public bar, virtual private baz {
410/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000411Sema::BaseResult
Chris Lattner5261d0c2009-03-28 19:18:32 +0000412Sema::ActOnBaseSpecifier(DeclPtrTy classdecl, SourceRange SpecifierRange,
Douglas Gregorabed2172008-10-22 17:49:05 +0000413 bool Virtual, AccessSpecifier Access,
414 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000415 AdjustDeclIfTemplate(classdecl);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000416 CXXRecordDecl *Class = cast<CXXRecordDecl>(classdecl.getAs<Decl>());
Douglas Gregora60c62e2009-02-09 15:09:02 +0000417 QualType BaseType = QualType::getFromOpaquePtr(basetype);
Douglas Gregored3a3982009-03-03 04:44:36 +0000418 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
419 Virtual, Access,
420 BaseType, BaseLoc))
421 return BaseSpec;
422
423 return true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000424}
Douglas Gregorec93f442008-04-13 21:30:24 +0000425
Douglas Gregored3a3982009-03-03 04:44:36 +0000426/// \brief Performs the actual work of attaching the given base class
427/// specifiers to a C++ class.
428bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
429 unsigned NumBases) {
430 if (NumBases == 0)
431 return false;
Douglas Gregorabed2172008-10-22 17:49:05 +0000432
433 // Used to keep track of which base types we have already seen, so
434 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000435 // that the key is always the unqualified canonical type of the base
436 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000437 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
438
439 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000440 unsigned NumGoodBases = 0;
Douglas Gregored3a3982009-03-03 04:44:36 +0000441 bool Invalid = false;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000442 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000443 QualType NewBaseType
Douglas Gregored3a3982009-03-03 04:44:36 +0000444 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor4fd85902008-10-23 18:13:27 +0000445 NewBaseType = NewBaseType.getUnqualifiedType();
446
Douglas Gregorabed2172008-10-22 17:49:05 +0000447 if (KnownBaseTypes[NewBaseType]) {
448 // C++ [class.mi]p3:
449 // A class shall not be specified as a direct base class of a
450 // derived class more than once.
Douglas Gregored3a3982009-03-03 04:44:36 +0000451 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000452 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000453 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregored3a3982009-03-03 04:44:36 +0000454 << Bases[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000455
456 // Delete the duplicate base class specifier; we're going to
457 // overwrite its pointer later.
Douglas Gregored3a3982009-03-03 04:44:36 +0000458 delete Bases[idx];
459
460 Invalid = true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000461 } else {
462 // Okay, add this new base class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000463 KnownBaseTypes[NewBaseType] = Bases[idx];
464 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000465 }
466 }
467
468 // Attach the remaining base class specifiers to the derived class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000469 Class->setBases(Bases, NumGoodBases);
Douglas Gregor4fd85902008-10-23 18:13:27 +0000470
471 // Delete the remaining (good) base class specifiers, since their
472 // data has been copied into the CXXRecordDecl.
473 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregored3a3982009-03-03 04:44:36 +0000474 delete Bases[idx];
475
476 return Invalid;
477}
478
479/// ActOnBaseSpecifiers - Attach the given base specifiers to the
480/// class, after checking whether there are any duplicate base
481/// classes.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000482void Sema::ActOnBaseSpecifiers(DeclPtrTy ClassDecl, BaseTy **Bases,
Douglas Gregored3a3982009-03-03 04:44:36 +0000483 unsigned NumBases) {
484 if (!ClassDecl || !Bases || !NumBases)
485 return;
486
487 AdjustDeclIfTemplate(ClassDecl);
Chris Lattner5261d0c2009-03-28 19:18:32 +0000488 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl.getAs<Decl>()),
Douglas Gregored3a3982009-03-03 04:44:36 +0000489 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregorec93f442008-04-13 21:30:24 +0000490}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000491
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000492//===----------------------------------------------------------------------===//
493// C++ class member Handling
494//===----------------------------------------------------------------------===//
495
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000496/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
497/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
498/// bitfield width if there is one and 'InitExpr' specifies the initializer if
Chris Lattnerd6c78092009-04-12 22:37:57 +0000499/// any.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000500Sema::DeclPtrTy
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000501Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
Sebastian Redla55834a2009-04-12 17:16:29 +0000502 ExprTy *BW, ExprTy *InitExpr, bool Deleted) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000503 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000504 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000505 Expr *BitWidth = static_cast<Expr*>(BW);
506 Expr *Init = static_cast<Expr*>(InitExpr);
507 SourceLocation Loc = D.getIdentifierLoc();
508
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000509 bool isFunc = D.isFunctionDeclarator();
510
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000511 // C++ 9.2p6: A member shall not be declared to have automatic storage
512 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000513 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
514 // data members and cannot be applied to names declared const or static,
515 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000516 switch (DS.getStorageClassSpec()) {
517 case DeclSpec::SCS_unspecified:
518 case DeclSpec::SCS_typedef:
519 case DeclSpec::SCS_static:
520 // FALL THROUGH.
521 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000522 case DeclSpec::SCS_mutable:
523 if (isFunc) {
524 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000525 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000526 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000527 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
528
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000529 // FIXME: It would be nicer if the keyword was ignored only for this
530 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000531 D.getMutableDeclSpec().ClearStorageClassSpecs();
532 } else {
533 QualType T = GetTypeForDeclarator(D, S);
534 diag::kind err = static_cast<diag::kind>(0);
535 if (T->isReferenceType())
536 err = diag::err_mutable_reference;
537 else if (T.isConstQualified())
538 err = diag::err_mutable_const;
539 if (err != 0) {
540 if (DS.getStorageClassSpecLoc().isValid())
541 Diag(DS.getStorageClassSpecLoc(), err);
542 else
543 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000544 // FIXME: It would be nicer if the keyword was ignored only for this
545 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000546 D.getMutableDeclSpec().ClearStorageClassSpecs();
547 }
548 }
549 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000550 default:
551 if (DS.getStorageClassSpecLoc().isValid())
552 Diag(DS.getStorageClassSpecLoc(),
553 diag::err_storageclass_invalid_for_member);
554 else
555 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
556 D.getMutableDeclSpec().ClearStorageClassSpecs();
557 }
558
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000559 if (!isFunc &&
Douglas Gregora60c62e2009-02-09 15:09:02 +0000560 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000561 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000562 // Check also for this case:
563 //
564 // typedef int f();
565 // f a;
566 //
Douglas Gregora60c62e2009-02-09 15:09:02 +0000567 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
568 isFunc = TDType->isFunctionType();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000569 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000570
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000571 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
572 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000573 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000574
575 Decl *Member;
Chris Lattner9cffefc2009-03-05 22:45:59 +0000576 if (isInstField) {
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000577 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
578 AS);
Chris Lattnere384c182009-03-05 23:03:49 +0000579 assert(Member && "HandleField never returns null");
Chris Lattner9cffefc2009-03-05 22:45:59 +0000580 } else {
Chris Lattnera17991f2009-03-29 16:50:03 +0000581 Member = ActOnDeclarator(S, D).getAs<Decl>();
Chris Lattnere384c182009-03-05 23:03:49 +0000582 if (!Member) {
583 if (BitWidth) DeleteExpr(BitWidth);
Chris Lattnera17991f2009-03-29 16:50:03 +0000584 return DeclPtrTy();
Chris Lattnere384c182009-03-05 23:03:49 +0000585 }
Chris Lattner432780c2009-03-05 23:01:03 +0000586
587 // Non-instance-fields can't have a bitfield.
588 if (BitWidth) {
589 if (Member->isInvalidDecl()) {
590 // don't emit another diagnostic.
Douglas Gregor00660582009-03-11 20:22:50 +0000591 } else if (isa<VarDecl>(Member)) {
Chris Lattner432780c2009-03-05 23:01:03 +0000592 // C++ 9.6p3: A bit-field shall not be a static member.
593 // "static member 'A' cannot be a bit-field"
594 Diag(Loc, diag::err_static_not_bitfield)
595 << Name << BitWidth->getSourceRange();
596 } else if (isa<TypedefDecl>(Member)) {
597 // "typedef member 'x' cannot be a bit-field"
598 Diag(Loc, diag::err_typedef_not_bitfield)
599 << Name << BitWidth->getSourceRange();
600 } else {
601 // A function typedef ("typedef int f(); f a;").
602 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
603 Diag(Loc, diag::err_not_integral_type_bitfield)
Douglas Gregor0e518af2009-03-11 18:59:21 +0000604 << Name << cast<ValueDecl>(Member)->getType()
605 << BitWidth->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000606 }
607
608 DeleteExpr(BitWidth);
609 BitWidth = 0;
610 Member->setInvalidDecl();
611 }
Douglas Gregor2f0ecef2009-03-11 20:50:30 +0000612
613 Member->setAccess(AS);
Chris Lattner9cffefc2009-03-05 22:45:59 +0000614 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000615
Douglas Gregor6704b312008-11-17 22:58:34 +0000616 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000617
Douglas Gregor8f53bb72009-03-11 23:00:04 +0000618 if (Init)
Chris Lattner5261d0c2009-03-28 19:18:32 +0000619 AddInitializerToDecl(DeclPtrTy::make(Member), ExprArg(*this, Init), false);
Sebastian Redla55834a2009-04-12 17:16:29 +0000620 if (Deleted) // FIXME: Source location is not very good.
621 SetDeclDeleted(DeclPtrTy::make(Member), D.getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000622
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000623 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000624 FieldCollector->Add(cast<FieldDecl>(Member));
Chris Lattnera17991f2009-03-29 16:50:03 +0000625 return DeclPtrTy();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000626 }
Chris Lattner5261d0c2009-03-28 19:18:32 +0000627 return DeclPtrTy::make(Member);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000628}
629
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000630/// ActOnMemInitializer - Handle a C++ member initializer.
631Sema::MemInitResult
Chris Lattner5261d0c2009-03-28 19:18:32 +0000632Sema::ActOnMemInitializer(DeclPtrTy ConstructorD,
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000633 Scope *S,
634 IdentifierInfo *MemberOrBase,
635 SourceLocation IdLoc,
636 SourceLocation LParenLoc,
637 ExprTy **Args, unsigned NumArgs,
638 SourceLocation *CommaLocs,
639 SourceLocation RParenLoc) {
640 CXXConstructorDecl *Constructor
Chris Lattner5261d0c2009-03-28 19:18:32 +0000641 = dyn_cast<CXXConstructorDecl>(ConstructorD.getAs<Decl>());
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000642 if (!Constructor) {
643 // The user wrote a constructor initializer on a function that is
644 // not a C++ constructor. Ignore the error for now, because we may
645 // have more member initializers coming; we'll diagnose it just
646 // once in ActOnMemInitializers.
647 return true;
648 }
649
650 CXXRecordDecl *ClassDecl = Constructor->getParent();
651
652 // C++ [class.base.init]p2:
653 // Names in a mem-initializer-id are looked up in the scope of the
654 // constructor’s class and, if not found in that scope, are looked
655 // up in the scope containing the constructor’s
656 // definition. [Note: if the constructor’s class contains a member
657 // with the same name as a direct or virtual base class of the
658 // class, a mem-initializer-id naming the member or base class and
659 // composed of a single identifier refers to the class member. A
660 // mem-initializer-id for the hidden base class may be specified
661 // using a qualified name. ]
662 // Look for a member, first.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000663 FieldDecl *Member = 0;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000664 DeclContext::lookup_result Result
665 = ClassDecl->lookup(Context, MemberOrBase);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000666 if (Result.first != Result.second)
667 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000668
669 // FIXME: Handle members of an anonymous union.
670
671 if (Member) {
672 // FIXME: Perform direct initialization of the member.
673 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
674 }
675
676 // It didn't name a member, so see if it names a class.
Douglas Gregor1075a162009-02-04 17:00:24 +0000677 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000678 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000679 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
680 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000681
Douglas Gregora60c62e2009-02-09 15:09:02 +0000682 QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000683 if (!BaseType->isRecordType())
Chris Lattner65cae292008-11-19 08:23:25 +0000684 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattnerb1753422008-11-23 21:45:46 +0000685 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000686
687 // C++ [class.base.init]p2:
688 // [...] Unless the mem-initializer-id names a nonstatic data
689 // member of the constructor’s class or a direct or virtual base
690 // of that class, the mem-initializer is ill-formed. A
691 // mem-initializer-list can initialize a base class using any
692 // name that denotes that base class type.
693
694 // First, check for a direct base class.
695 const CXXBaseSpecifier *DirectBaseSpec = 0;
696 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
697 Base != ClassDecl->bases_end(); ++Base) {
698 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
699 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
700 // We found a direct base of this type. That's what we're
701 // initializing.
702 DirectBaseSpec = &*Base;
703 break;
704 }
705 }
706
707 // Check for a virtual base class.
Mike Stumpe127ae32009-05-16 07:39:55 +0000708 // FIXME: We might be able to short-circuit this if we know in advance that
709 // there are no virtual bases.
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000710 const CXXBaseSpecifier *VirtualBaseSpec = 0;
711 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
712 // We haven't found a base yet; search the class hierarchy for a
713 // virtual base class.
714 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
715 /*DetectVirtual=*/false);
716 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
717 for (BasePaths::paths_iterator Path = Paths.begin();
718 Path != Paths.end(); ++Path) {
719 if (Path->back().Base->isVirtual()) {
720 VirtualBaseSpec = Path->back().Base;
721 break;
722 }
723 }
724 }
725 }
726
727 // C++ [base.class.init]p2:
728 // If a mem-initializer-id is ambiguous because it designates both
729 // a direct non-virtual base class and an inherited virtual base
730 // class, the mem-initializer is ill-formed.
731 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner65cae292008-11-19 08:23:25 +0000732 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
733 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000734
735 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
736}
737
Chris Lattner5261d0c2009-03-28 19:18:32 +0000738void Sema::ActOnMemInitializers(DeclPtrTy ConstructorDecl,
Anders Carlssonc7f87202009-03-25 02:58:17 +0000739 SourceLocation ColonLoc,
740 MemInitTy **MemInits, unsigned NumMemInits) {
741 CXXConstructorDecl *Constructor =
Chris Lattner5261d0c2009-03-28 19:18:32 +0000742 dyn_cast<CXXConstructorDecl>(ConstructorDecl.getAs<Decl>());
Anders Carlssonc7f87202009-03-25 02:58:17 +0000743
744 if (!Constructor) {
745 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
746 return;
747 }
748}
749
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000750namespace {
751 /// PureVirtualMethodCollector - traverses a class and its superclasses
752 /// and determines if it has any pure virtual methods.
753 class VISIBILITY_HIDDEN PureVirtualMethodCollector {
754 ASTContext &Context;
755
Sebastian Redl16ac38f2009-03-22 21:28:55 +0000756 public:
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000757 typedef llvm::SmallVector<const CXXMethodDecl*, 8> MethodList;
Sebastian Redl16ac38f2009-03-22 21:28:55 +0000758
759 private:
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000760 MethodList Methods;
761
762 void Collect(const CXXRecordDecl* RD, MethodList& Methods);
763
764 public:
765 PureVirtualMethodCollector(ASTContext &Ctx, const CXXRecordDecl* RD)
766 : Context(Ctx) {
767
768 MethodList List;
769 Collect(RD, List);
770
771 // Copy the temporary list to methods, and make sure to ignore any
772 // null entries.
773 for (size_t i = 0, e = List.size(); i != e; ++i) {
774 if (List[i])
775 Methods.push_back(List[i]);
776 }
777 }
778
Anders Carlssone1299b32009-03-22 20:18:17 +0000779 bool empty() const { return Methods.empty(); }
780
781 MethodList::const_iterator methods_begin() { return Methods.begin(); }
782 MethodList::const_iterator methods_end() { return Methods.end(); }
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000783 };
784
785 void PureVirtualMethodCollector::Collect(const CXXRecordDecl* RD,
786 MethodList& Methods) {
787 // First, collect the pure virtual methods for the base classes.
788 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(),
789 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) {
790 if (const RecordType *RT = Base->getType()->getAsRecordType()) {
Chris Lattner330a05b2009-03-29 05:01:10 +0000791 const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000792 if (BaseDecl && BaseDecl->isAbstract())
793 Collect(BaseDecl, Methods);
794 }
795 }
796
797 // Next, zero out any pure virtual methods that this class overrides.
Anders Carlsson1eba0ac2009-05-17 00:00:05 +0000798 typedef llvm::SmallPtrSet<const CXXMethodDecl*, 4> MethodSetTy;
799
800 MethodSetTy OverriddenMethods;
801 size_t MethodsSize = Methods.size();
802
803 for (RecordDecl::decl_iterator i = RD->decls_begin(Context),
804 e = RD->decls_end(Context);
805 i != e; ++i) {
806 // Traverse the record, looking for methods.
807 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*i)) {
808 // If the method is pre virtual, add it to the methods vector.
809 if (MD->isPure()) {
810 Methods.push_back(MD);
811 continue;
812 }
813
814 // Otherwise, record all the overridden methods in our set.
815 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
816 E = MD->end_overridden_methods(); I != E; ++I) {
817 // Keep track of the overridden methods.
818 OverriddenMethods.insert(*I);
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000819 }
820 }
821 }
822
Anders Carlsson1eba0ac2009-05-17 00:00:05 +0000823 // Now go through the methods and zero out all the ones we know are
824 // overridden.
825 for (size_t i = 0, e = MethodsSize; i != e; ++i) {
826 if (OverriddenMethods.count(Methods[i]))
827 Methods[i] = 0;
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000828 }
Anders Carlsson1eba0ac2009-05-17 00:00:05 +0000829
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000830 }
831}
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000832
Anders Carlssone1299b32009-03-22 20:18:17 +0000833bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
Anders Carlssonde9e7892009-03-24 17:23:42 +0000834 unsigned DiagID, AbstractDiagSelID SelID,
835 const CXXRecordDecl *CurrentRD) {
Anders Carlssone1299b32009-03-22 20:18:17 +0000836
837 if (!getLangOptions().CPlusPlus)
838 return false;
Anders Carlssonc263c9b2009-03-23 19:10:31 +0000839
840 if (const ArrayType *AT = Context.getAsArrayType(T))
Anders Carlssonde9e7892009-03-24 17:23:42 +0000841 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
842 CurrentRD);
Anders Carlssonce9240e2009-03-24 01:46:45 +0000843
844 if (const PointerType *PT = T->getAsPointerType()) {
845 // Find the innermost pointer type.
846 while (const PointerType *T = PT->getPointeeType()->getAsPointerType())
847 PT = T;
Anders Carlssone1299b32009-03-22 20:18:17 +0000848
Anders Carlssonce9240e2009-03-24 01:46:45 +0000849 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
Anders Carlssonde9e7892009-03-24 17:23:42 +0000850 return RequireNonAbstractType(Loc, AT->getElementType(), DiagID, SelID,
851 CurrentRD);
Anders Carlssonce9240e2009-03-24 01:46:45 +0000852 }
853
Anders Carlssone1299b32009-03-22 20:18:17 +0000854 const RecordType *RT = T->getAsRecordType();
855 if (!RT)
856 return false;
857
858 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
859 if (!RD)
860 return false;
861
Anders Carlssonde9e7892009-03-24 17:23:42 +0000862 if (CurrentRD && CurrentRD != RD)
863 return false;
864
Anders Carlssone1299b32009-03-22 20:18:17 +0000865 if (!RD->isAbstract())
866 return false;
867
Anders Carlssond5a94982009-03-23 17:49:10 +0000868 Diag(Loc, DiagID) << RD->getDeclName() << SelID;
Anders Carlssone1299b32009-03-22 20:18:17 +0000869
870 // Check if we've already emitted the list of pure virtual functions for this
871 // class.
872 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
873 return true;
874
875 PureVirtualMethodCollector Collector(Context, RD);
876
877 for (PureVirtualMethodCollector::MethodList::const_iterator I =
878 Collector.methods_begin(), E = Collector.methods_end(); I != E; ++I) {
879 const CXXMethodDecl *MD = *I;
880
881 Diag(MD->getLocation(), diag::note_pure_virtual_function) <<
882 MD->getDeclName();
883 }
884
885 if (!PureVirtualClassDiagSet)
886 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
887 PureVirtualClassDiagSet->insert(RD);
888
889 return true;
890}
891
Anders Carlsson412c3402009-03-24 01:19:16 +0000892namespace {
893 class VISIBILITY_HIDDEN AbstractClassUsageDiagnoser
894 : public DeclVisitor<AbstractClassUsageDiagnoser, bool> {
895 Sema &SemaRef;
896 CXXRecordDecl *AbstractClass;
897
Anders Carlssonde9e7892009-03-24 17:23:42 +0000898 bool VisitDeclContext(const DeclContext *DC) {
Anders Carlsson412c3402009-03-24 01:19:16 +0000899 bool Invalid = false;
900
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000901 for (CXXRecordDecl::decl_iterator I = DC->decls_begin(SemaRef.Context),
902 E = DC->decls_end(SemaRef.Context); I != E; ++I)
Anders Carlsson412c3402009-03-24 01:19:16 +0000903 Invalid |= Visit(*I);
Anders Carlssonde9e7892009-03-24 17:23:42 +0000904
Anders Carlsson412c3402009-03-24 01:19:16 +0000905 return Invalid;
906 }
Anders Carlssonde9e7892009-03-24 17:23:42 +0000907
908 public:
909 AbstractClassUsageDiagnoser(Sema& SemaRef, CXXRecordDecl *ac)
910 : SemaRef(SemaRef), AbstractClass(ac) {
911 Visit(SemaRef.Context.getTranslationUnitDecl());
912 }
Anders Carlsson412c3402009-03-24 01:19:16 +0000913
Anders Carlssonde9e7892009-03-24 17:23:42 +0000914 bool VisitFunctionDecl(const FunctionDecl *FD) {
915 if (FD->isThisDeclarationADefinition()) {
916 // No need to do the check if we're in a definition, because it requires
917 // that the return/param types are complete.
918 // because that requires
919 return VisitDeclContext(FD);
920 }
921
922 // Check the return type.
923 QualType RTy = FD->getType()->getAsFunctionType()->getResultType();
924 bool Invalid =
925 SemaRef.RequireNonAbstractType(FD->getLocation(), RTy,
926 diag::err_abstract_type_in_decl,
927 Sema::AbstractReturnType,
928 AbstractClass);
929
930 for (FunctionDecl::param_const_iterator I = FD->param_begin(),
931 E = FD->param_end(); I != E; ++I) {
Anders Carlsson412c3402009-03-24 01:19:16 +0000932 const ParmVarDecl *VD = *I;
933 Invalid |=
934 SemaRef.RequireNonAbstractType(VD->getLocation(),
935 VD->getOriginalType(),
936 diag::err_abstract_type_in_decl,
Anders Carlssonde9e7892009-03-24 17:23:42 +0000937 Sema::AbstractParamType,
938 AbstractClass);
Anders Carlsson412c3402009-03-24 01:19:16 +0000939 }
940
941 return Invalid;
942 }
Anders Carlssonde9e7892009-03-24 17:23:42 +0000943
944 bool VisitDecl(const Decl* D) {
945 if (const DeclContext *DC = dyn_cast<DeclContext>(D))
946 return VisitDeclContext(DC);
947
948 return false;
949 }
Anders Carlsson412c3402009-03-24 01:19:16 +0000950 };
951}
952
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000953void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000954 DeclPtrTy TagDecl,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000955 SourceLocation LBrac,
956 SourceLocation RBrac) {
Douglas Gregor3eb20702009-05-11 19:58:34 +0000957 AdjustDeclIfTemplate(TagDecl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000958 ActOnFields(S, RLoc, TagDecl,
Chris Lattner5261d0c2009-03-28 19:18:32 +0000959 (DeclPtrTy*)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000960 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregored3a3982009-03-03 04:44:36 +0000961
Chris Lattner5261d0c2009-03-28 19:18:32 +0000962 CXXRecordDecl *RD = cast<CXXRecordDecl>(TagDecl.getAs<Decl>());
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000963 if (!RD->isAbstract()) {
964 // Collect all the pure virtual methods and see if this is an abstract
965 // class after all.
966 PureVirtualMethodCollector Collector(Context, RD);
967 if (!Collector.empty())
968 RD->setAbstract(true);
969 }
970
Anders Carlssonde9e7892009-03-24 17:23:42 +0000971 if (RD->isAbstract())
972 AbstractClassUsageDiagnoser(*this, RD);
Anders Carlsson412c3402009-03-24 01:19:16 +0000973
Anders Carlsson39a10db2009-04-17 02:34:54 +0000974 if (RD->hasTrivialConstructor() || RD->hasTrivialDestructor()) {
Anders Carlssonc6363712009-04-16 00:08:20 +0000975 for (RecordDecl::field_iterator i = RD->field_begin(Context),
976 e = RD->field_end(Context); i != e; ++i) {
977 // All the nonstatic data members must have trivial constructors.
978 QualType FTy = i->getType();
979 while (const ArrayType *AT = Context.getAsArrayType(FTy))
980 FTy = AT->getElementType();
981
982 if (const RecordType *RT = FTy->getAsRecordType()) {
983 CXXRecordDecl *FieldRD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson39a10db2009-04-17 02:34:54 +0000984
985 if (!FieldRD->hasTrivialConstructor())
Anders Carlssonc6363712009-04-16 00:08:20 +0000986 RD->setHasTrivialConstructor(false);
Anders Carlsson39a10db2009-04-17 02:34:54 +0000987 if (!FieldRD->hasTrivialDestructor())
988 RD->setHasTrivialDestructor(false);
989
990 // If RD has neither a trivial constructor nor a trivial destructor
991 // we don't need to continue checking.
992 if (!RD->hasTrivialConstructor() && !RD->hasTrivialDestructor())
Anders Carlssonc6363712009-04-16 00:08:20 +0000993 break;
Anders Carlssonc6363712009-04-16 00:08:20 +0000994 }
995 }
996 }
997
Douglas Gregor3eb20702009-05-11 19:58:34 +0000998 if (!RD->isDependentType())
Anders Carlsson1dae87f2009-03-22 01:52:17 +0000999 AddImplicitlyDeclaredMembersToClass(RD);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001000}
1001
Douglas Gregore640ab62008-11-03 17:51:48 +00001002/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
1003/// special functions, such as the default constructor, copy
1004/// constructor, or destructor, to the given C++ class (C++
1005/// [special]p1). This routine can only be executed just before the
1006/// definition of the class is complete.
1007void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001008 QualType ClassType = Context.getTypeDeclType(ClassDecl);
1009 ClassType = Context.getCanonicalType(ClassType);
1010
Sebastian Redl2767d882009-05-27 22:11:52 +00001011 // FIXME: Implicit declarations have exception specifications, which are
1012 // the union of the specifications of the implicitly called functions.
1013
Douglas Gregore640ab62008-11-03 17:51:48 +00001014 if (!ClassDecl->hasUserDeclaredConstructor()) {
1015 // C++ [class.ctor]p5:
1016 // A default constructor for a class X is a constructor of class X
1017 // that can be called without an argument. If there is no
1018 // user-declared constructor for class X, a default constructor is
1019 // implicitly declared. An implicitly-declared default constructor
1020 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001021 DeclarationName Name
1022 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001023 CXXConstructorDecl *DefaultCon =
1024 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001025 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +00001026 Context.getFunctionType(Context.VoidTy,
1027 0, 0, false, 0),
1028 /*isExplicit=*/false,
1029 /*isInline=*/true,
1030 /*isImplicitlyDeclared=*/true);
1031 DefaultCon->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001032 DefaultCon->setImplicit();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001033 ClassDecl->addDecl(Context, DefaultCon);
Douglas Gregorb9213832008-12-15 21:24:18 +00001034
1035 // Notify the class that we've added a constructor.
1036 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +00001037 }
1038
1039 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
1040 // C++ [class.copy]p4:
1041 // If the class definition does not explicitly declare a copy
1042 // constructor, one is declared implicitly.
1043
1044 // C++ [class.copy]p5:
1045 // The implicitly-declared copy constructor for a class X will
1046 // have the form
1047 //
1048 // X::X(const X&)
1049 //
1050 // if
1051 bool HasConstCopyConstructor = true;
1052
1053 // -- each direct or virtual base class B of X has a copy
1054 // constructor whose first parameter is of type const B& or
1055 // const volatile B&, and
1056 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1057 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
1058 const CXXRecordDecl *BaseClassDecl
1059 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1060 HasConstCopyConstructor
1061 = BaseClassDecl->hasConstCopyConstructor(Context);
1062 }
1063
1064 // -- for all the nonstatic data members of X that are of a
1065 // class type M (or array thereof), each such class type
1066 // has a copy constructor whose first parameter is of type
1067 // const M& or const volatile M&.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001068 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(Context);
1069 HasConstCopyConstructor && Field != ClassDecl->field_end(Context);
1070 ++Field) {
Douglas Gregore640ab62008-11-03 17:51:48 +00001071 QualType FieldType = (*Field)->getType();
1072 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1073 FieldType = Array->getElementType();
1074 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1075 const CXXRecordDecl *FieldClassDecl
1076 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1077 HasConstCopyConstructor
1078 = FieldClassDecl->hasConstCopyConstructor(Context);
1079 }
1080 }
1081
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001082 // Otherwise, the implicitly declared copy constructor will have
1083 // the form
Douglas Gregore640ab62008-11-03 17:51:48 +00001084 //
1085 // X::X(X&)
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001086 QualType ArgType = ClassType;
Douglas Gregore640ab62008-11-03 17:51:48 +00001087 if (HasConstCopyConstructor)
1088 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +00001089 ArgType = Context.getLValueReferenceType(ArgType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001090
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001091 // An implicitly-declared copy constructor is an inline public
1092 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001093 DeclarationName Name
1094 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +00001095 CXXConstructorDecl *CopyConstructor
1096 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001097 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +00001098 Context.getFunctionType(Context.VoidTy,
1099 &ArgType, 1,
1100 false, 0),
1101 /*isExplicit=*/false,
1102 /*isInline=*/true,
1103 /*isImplicitlyDeclared=*/true);
1104 CopyConstructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001105 CopyConstructor->setImplicit();
Douglas Gregore640ab62008-11-03 17:51:48 +00001106
1107 // Add the parameter to the constructor.
1108 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
1109 ClassDecl->getLocation(),
1110 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001111 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001112 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregore640ab62008-11-03 17:51:48 +00001113
Douglas Gregorb9213832008-12-15 21:24:18 +00001114 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001115 ClassDecl->addDecl(Context, CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +00001116 }
1117
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001118 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
1119 // Note: The following rules are largely analoguous to the copy
1120 // constructor rules. Note that virtual bases are not taken into account
1121 // for determining the argument type of the operator. Note also that
1122 // operators taking an object instead of a reference are allowed.
1123 //
1124 // C++ [class.copy]p10:
1125 // If the class definition does not explicitly declare a copy
1126 // assignment operator, one is declared implicitly.
1127 // The implicitly-defined copy assignment operator for a class X
1128 // will have the form
1129 //
1130 // X& X::operator=(const X&)
1131 //
1132 // if
1133 bool HasConstCopyAssignment = true;
1134
1135 // -- each direct base class B of X has a copy assignment operator
1136 // whose parameter is of type const B&, const volatile B& or B,
1137 // and
1138 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
1139 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
1140 const CXXRecordDecl *BaseClassDecl
1141 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
1142 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
1143 }
1144
1145 // -- for all the nonstatic data members of X that are of a class
1146 // type M (or array thereof), each such class type has a copy
1147 // assignment operator whose parameter is of type const M&,
1148 // const volatile M& or M.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001149 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(Context);
1150 HasConstCopyAssignment && Field != ClassDecl->field_end(Context);
1151 ++Field) {
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001152 QualType FieldType = (*Field)->getType();
1153 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
1154 FieldType = Array->getElementType();
1155 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
1156 const CXXRecordDecl *FieldClassDecl
1157 = cast<CXXRecordDecl>(FieldClassType->getDecl());
1158 HasConstCopyAssignment
1159 = FieldClassDecl->hasConstCopyAssignment(Context);
1160 }
1161 }
1162
1163 // Otherwise, the implicitly declared copy assignment operator will
1164 // have the form
1165 //
1166 // X& X::operator=(X&)
1167 QualType ArgType = ClassType;
Sebastian Redlce6fff02009-03-16 23:22:08 +00001168 QualType RetType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001169 if (HasConstCopyAssignment)
1170 ArgType = ArgType.withConst();
Sebastian Redlce6fff02009-03-16 23:22:08 +00001171 ArgType = Context.getLValueReferenceType(ArgType);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001172
1173 // An implicitly-declared copy assignment operator is an inline public
1174 // member of its class.
1175 DeclarationName Name =
1176 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
1177 CXXMethodDecl *CopyAssignment =
1178 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
1179 Context.getFunctionType(RetType, &ArgType, 1,
1180 false, 0),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001181 /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001182 CopyAssignment->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001183 CopyAssignment->setImplicit();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001184
1185 // Add the parameter to the operator.
1186 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
1187 ClassDecl->getLocation(),
1188 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00001189 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001190 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001191
1192 // Don't call addedAssignmentOperator. There is no way to distinguish an
1193 // implicit from an explicit assignment operator.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001194 ClassDecl->addDecl(Context, CopyAssignment);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001195 }
1196
Douglas Gregorb9213832008-12-15 21:24:18 +00001197 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001198 // C++ [class.dtor]p2:
1199 // If a class has no user-declared destructor, a destructor is
1200 // declared implicitly. An implicitly-declared destructor is an
1201 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001202 DeclarationName Name
1203 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001204 CXXDestructorDecl *Destructor
1205 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001206 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001207 Context.getFunctionType(Context.VoidTy,
1208 0, 0, false, 0),
1209 /*isInline=*/true,
1210 /*isImplicitlyDeclared=*/true);
1211 Destructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001212 Destructor->setImplicit();
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001213 ClassDecl->addDecl(Context, Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001214 }
Douglas Gregore640ab62008-11-03 17:51:48 +00001215}
1216
Douglas Gregora376cbd2009-05-27 23:11:45 +00001217void Sema::ActOnReenterTemplateScope(Scope *S, DeclPtrTy TemplateD) {
1218 TemplateDecl *Template = TemplateD.getAs<TemplateDecl>();
1219 if (!Template)
1220 return;
1221
1222 TemplateParameterList *Params = Template->getTemplateParameters();
1223 for (TemplateParameterList::iterator Param = Params->begin(),
1224 ParamEnd = Params->end();
1225 Param != ParamEnd; ++Param) {
1226 NamedDecl *Named = cast<NamedDecl>(*Param);
1227 if (Named->getDeclName()) {
1228 S->AddDecl(DeclPtrTy::make(Named));
1229 IdResolver.AddDecl(Named);
1230 }
1231 }
1232}
1233
Douglas Gregor605de8d2008-12-16 21:30:33 +00001234/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1235/// parsing a top-level (non-nested) C++ class, and we are now
1236/// parsing those parts of the given Method declaration that could
1237/// not be parsed earlier (C++ [class.mem]p2), such as default
1238/// arguments. This action should enter the scope of the given
1239/// Method declaration as if we had just parsed the qualified method
1240/// name. However, it should not bring the parameters into scope;
1241/// that will be performed by ActOnDelayedCXXMethodParameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001242void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00001243 CXXScopeSpec SS;
Chris Lattner5261d0c2009-03-28 19:18:32 +00001244 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001245 QualType ClassTy
1246 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1247 SS.setScopeRep(
1248 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001249 ActOnCXXEnterDeclaratorScope(S, SS);
1250}
1251
1252/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1253/// C++ method declaration. We're (re-)introducing the given
1254/// function parameter into scope for use in parsing later parts of
1255/// the method declaration. For example, we could see an
1256/// ActOnParamDefaultArgument event for this parameter.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001257void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclPtrTy ParamD) {
1258 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD.getAs<Decl>());
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001259
1260 // If this parameter has an unparsed default argument, clear it out
1261 // to make way for the parsed default argument.
1262 if (Param->hasUnparsedDefaultArg())
1263 Param->setDefaultArg(0);
1264
Chris Lattner5261d0c2009-03-28 19:18:32 +00001265 S->AddDecl(DeclPtrTy::make(Param));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001266 if (Param->getDeclName())
1267 IdResolver.AddDecl(Param);
1268}
1269
1270/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1271/// processing the delayed method declaration for Method. The method
1272/// declaration is now considered finished. There may be a separate
1273/// ActOnStartOfFunctionDef action later (not necessarily
1274/// immediately!) for this method, if it was also defined inside the
1275/// class body.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001276void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclPtrTy MethodD) {
1277 FunctionDecl *Method = cast<FunctionDecl>(MethodD.getAs<Decl>());
Douglas Gregor605de8d2008-12-16 21:30:33 +00001278 CXXScopeSpec SS;
Douglas Gregor1e589cc2009-03-26 23:50:42 +00001279 QualType ClassTy
1280 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
1281 SS.setScopeRep(
1282 NestedNameSpecifier::Create(Context, 0, false, ClassTy.getTypePtr()));
Douglas Gregor605de8d2008-12-16 21:30:33 +00001283 ActOnCXXExitDeclaratorScope(S, SS);
1284
1285 // Now that we have our default arguments, check the constructor
1286 // again. It could produce additional diagnostics or affect whether
1287 // the class has implicitly-declared destructors, among other
1288 // things.
Chris Lattner08da4772009-04-25 08:35:12 +00001289 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
1290 CheckConstructor(Constructor);
Douglas Gregor605de8d2008-12-16 21:30:33 +00001291
1292 // Check the default arguments, which we may have added.
1293 if (!Method->isInvalidDecl())
1294 CheckCXXDefaultArguments(Method);
1295}
1296
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001297/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +00001298/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001299/// R. If there are any errors in the declarator, this routine will
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001300/// emit diagnostics and set the invalid bit to true. In any case, the type
1301/// will be updated to reflect a well-formed type for the constructor and
1302/// returned.
1303QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
1304 FunctionDecl::StorageClass &SC) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001305 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001306
1307 // C++ [class.ctor]p3:
1308 // A constructor shall not be virtual (10.3) or static (9.4). A
1309 // constructor can be invoked for a const, volatile or const
1310 // volatile object. A constructor shall not be declared const,
1311 // volatile, or const volatile (9.3.2).
1312 if (isVirtual) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001313 if (!D.isInvalidType())
1314 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1315 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1316 << SourceRange(D.getIdentifierLoc());
1317 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001318 }
1319 if (SC == FunctionDecl::Static) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001320 if (!D.isInvalidType())
1321 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1322 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1323 << SourceRange(D.getIdentifierLoc());
1324 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001325 SC = FunctionDecl::None;
1326 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001327
1328 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1329 if (FTI.TypeQuals != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001330 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001331 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1332 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001333 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001334 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1335 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001336 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001337 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1338 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001339 }
1340
1341 // Rebuild the function type "R" without any type qualifiers (in
1342 // case any of the errors above fired) and with "void" as the
1343 // return type, since constructors don't have return types. We
1344 // *always* have to do this, because GetTypeForDeclarator will
1345 // put in a result type of "int" when none was specified.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001346 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001347 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1348 Proto->getNumArgs(),
1349 Proto->isVariadic(), 0);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001350}
1351
Douglas Gregor605de8d2008-12-16 21:30:33 +00001352/// CheckConstructor - Checks a fully-formed constructor for
1353/// well-formedness, issuing any diagnostics required. Returns true if
1354/// the constructor declarator is invalid.
Chris Lattner08da4772009-04-25 08:35:12 +00001355void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
Douglas Gregor869cabf2009-03-27 04:38:56 +00001356 CXXRecordDecl *ClassDecl
1357 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
1358 if (!ClassDecl)
Chris Lattner08da4772009-04-25 08:35:12 +00001359 return Constructor->setInvalidDecl();
Douglas Gregor605de8d2008-12-16 21:30:33 +00001360
1361 // C++ [class.copy]p3:
1362 // A declaration of a constructor for a class X is ill-formed if
1363 // its first parameter is of type (optionally cv-qualified) X and
1364 // either there are no other parameters or else all other
1365 // parameters have default arguments.
Douglas Gregor869cabf2009-03-27 04:38:56 +00001366 if (!Constructor->isInvalidDecl() &&
1367 ((Constructor->getNumParams() == 1) ||
1368 (Constructor->getNumParams() > 1 &&
Anders Carlssond2e57d92009-06-06 04:14:07 +00001369 Constructor->getParamDecl(1)->hasDefaultArg()))) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00001370 QualType ParamType = Constructor->getParamDecl(0)->getType();
1371 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1372 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
Douglas Gregor3faaa812009-04-01 23:51:29 +00001373 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
1374 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
Douglas Gregor133d2552009-04-02 01:08:08 +00001375 << CodeModificationHint::CreateInsertion(ParamLoc, " const &");
Chris Lattner08da4772009-04-25 08:35:12 +00001376 Constructor->setInvalidDecl();
Douglas Gregor605de8d2008-12-16 21:30:33 +00001377 }
1378 }
1379
1380 // Notify the class that we've added a constructor.
1381 ClassDecl->addedConstructor(Context, Constructor);
Douglas Gregor605de8d2008-12-16 21:30:33 +00001382}
1383
Anders Carlssonfcfa2442009-04-30 23:18:11 +00001384static inline bool
1385FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
1386 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1387 FTI.ArgInfo[0].Param &&
1388 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType());
1389}
1390
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001391/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1392/// the well-formednes of the destructor declarator @p D with type @p
1393/// R. If there are any errors in the declarator, this routine will
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001394/// emit diagnostics and set the declarator to invalid. Even if this happens,
1395/// will be updated to reflect a well-formed type for the destructor and
1396/// returned.
1397QualType Sema::CheckDestructorDeclarator(Declarator &D,
1398 FunctionDecl::StorageClass& SC) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001399 // C++ [class.dtor]p1:
1400 // [...] A typedef-name that names a class is a class-name
1401 // (7.1.3); however, a typedef-name that names a class shall not
1402 // be used as the identifier in the declarator for a destructor
1403 // declaration.
Douglas Gregora60c62e2009-02-09 15:09:02 +00001404 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001405 if (isa<TypedefType>(DeclaratorType)) {
1406 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregora60c62e2009-02-09 15:09:02 +00001407 << DeclaratorType;
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001408 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001409 }
1410
1411 // C++ [class.dtor]p2:
1412 // A destructor is used to destroy objects of its class type. A
1413 // destructor takes no parameters, and no return type can be
1414 // specified for it (not even void). The address of a destructor
1415 // shall not be taken. A destructor shall not be static. A
1416 // destructor can be invoked for a const, volatile or const
1417 // volatile object. A destructor shall not be declared const,
1418 // volatile or const volatile (9.3.2).
1419 if (SC == FunctionDecl::Static) {
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001420 if (!D.isInvalidType())
1421 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1422 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1423 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001424 SC = FunctionDecl::None;
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001425 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001426 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001427 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001428 // Destructors don't have return types, but the parser will
1429 // happily parse something like:
1430 //
1431 // class X {
1432 // float ~X();
1433 // };
1434 //
1435 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001436 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1437 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1438 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001439 }
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001440
1441 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1442 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001443 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001444 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1445 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001446 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001447 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1448 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001449 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001450 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1451 << "restrict" << SourceRange(D.getIdentifierLoc());
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001452 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001453 }
1454
1455 // Make sure we don't have any parameters.
Anders Carlssonfcfa2442009-04-30 23:18:11 +00001456 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001457 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1458
1459 // Delete the parameters.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001460 FTI.freeArgs();
1461 D.setInvalidType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001462 }
1463
1464 // Make sure the destructor isn't variadic.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001465 if (FTI.isVariadic) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001466 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001467 D.setInvalidType();
1468 }
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001469
1470 // Rebuild the function type "R" without any type qualifiers or
1471 // parameters (in case any of the errors above fired) and with
1472 // "void" as the return type, since destructors don't have return
1473 // types. We *always* have to do this, because GetTypeForDeclarator
1474 // will put in a result type of "int" when none was specified.
Chris Lattnerc82dcd42009-04-25 08:28:21 +00001475 return Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001476}
1477
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001478/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1479/// well-formednes of the conversion function declarator @p D with
1480/// type @p R. If there are any errors in the declarator, this routine
1481/// will emit diagnostics and return true. Otherwise, it will return
1482/// false. Either way, the type @p R will be updated to reflect a
1483/// well-formed type for the conversion operator.
Chris Lattner08da4772009-04-25 08:35:12 +00001484void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001485 FunctionDecl::StorageClass& SC) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001486 // C++ [class.conv.fct]p1:
1487 // Neither parameter types nor return type can be specified. The
1488 // type of a conversion function (8.3.5) is “function taking no
1489 // parameter returning conversion-type-id.”
1490 if (SC == FunctionDecl::Static) {
Chris Lattner08da4772009-04-25 08:35:12 +00001491 if (!D.isInvalidType())
1492 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1493 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1494 << SourceRange(D.getIdentifierLoc());
1495 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001496 SC = FunctionDecl::None;
1497 }
Chris Lattner08da4772009-04-25 08:35:12 +00001498 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001499 // Conversion functions don't have return types, but the parser will
1500 // happily parse something like:
1501 //
1502 // class X {
1503 // float operator bool();
1504 // };
1505 //
1506 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001507 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1508 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1509 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001510 }
1511
1512 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001513 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001514 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1515
1516 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001517 D.getTypeObject(0).Fun.freeArgs();
Chris Lattner08da4772009-04-25 08:35:12 +00001518 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001519 }
1520
1521 // Make sure the conversion function isn't variadic.
Chris Lattner08da4772009-04-25 08:35:12 +00001522 if (R->getAsFunctionProtoType()->isVariadic() && !D.isInvalidType()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001523 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
Chris Lattner08da4772009-04-25 08:35:12 +00001524 D.setInvalidType();
1525 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001526
1527 // C++ [class.conv.fct]p4:
1528 // The conversion-type-id shall not represent a function type nor
1529 // an array type.
1530 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1531 if (ConvType->isArrayType()) {
1532 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1533 ConvType = Context.getPointerType(ConvType);
Chris Lattner08da4772009-04-25 08:35:12 +00001534 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001535 } else if (ConvType->isFunctionType()) {
1536 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1537 ConvType = Context.getPointerType(ConvType);
Chris Lattner08da4772009-04-25 08:35:12 +00001538 D.setInvalidType();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001539 }
1540
1541 // Rebuild the function type "R" without any parameters (in case any
1542 // of the errors above fired) and with the conversion type as the
1543 // return type.
1544 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001545 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001546
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001547 // C++0x explicit conversion operators.
1548 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1549 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1550 diag::warn_explicit_conversion_functions)
1551 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001552}
1553
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001554/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1555/// the declaration of the given C++ conversion function. This routine
1556/// is responsible for recording the conversion function in the C++
1557/// class, if possible.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001558Sema::DeclPtrTy Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001559 assert(Conversion && "Expected to receive a conversion function declaration");
1560
Douglas Gregor98341042008-12-12 08:25:50 +00001561 // Set the lexical context of this conversion function
1562 Conversion->setLexicalDeclContext(CurContext);
1563
1564 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001565
1566 // Make sure we aren't redeclaring the conversion function.
1567 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001568
1569 // C++ [class.conv.fct]p1:
1570 // [...] A conversion function is never used to convert a
1571 // (possibly cv-qualified) object to the (possibly cv-qualified)
1572 // same object type (or a reference to it), to a (possibly
1573 // cv-qualified) base class of that type (or a reference to it),
1574 // or to (possibly cv-qualified) void.
Mike Stumpe127ae32009-05-16 07:39:55 +00001575 // FIXME: Suppress this warning if the conversion function ends up being a
1576 // virtual function that overrides a virtual function in a base class.
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001577 QualType ClassType
1578 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1579 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1580 ConvType = ConvTypeRef->getPointeeType();
1581 if (ConvType->isRecordType()) {
1582 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1583 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001584 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001585 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001586 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001587 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001588 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001589 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001590 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001591 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001592 }
1593
Douglas Gregor853dd392008-12-26 15:00:45 +00001594 if (Conversion->getPreviousDeclaration()) {
1595 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1596 for (OverloadedFunctionDecl::function_iterator
1597 Conv = Conversions->function_begin(),
1598 ConvEnd = Conversions->function_end();
1599 Conv != ConvEnd; ++Conv) {
1600 if (*Conv == Conversion->getPreviousDeclaration()) {
1601 *Conv = Conversion;
Chris Lattner5261d0c2009-03-28 19:18:32 +00001602 return DeclPtrTy::make(Conversion);
Douglas Gregor853dd392008-12-26 15:00:45 +00001603 }
1604 }
1605 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1606 } else
1607 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001608
Chris Lattner5261d0c2009-03-28 19:18:32 +00001609 return DeclPtrTy::make(Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001610}
1611
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001612//===----------------------------------------------------------------------===//
1613// Namespace Handling
1614//===----------------------------------------------------------------------===//
1615
1616/// ActOnStartNamespaceDef - This is called at the start of a namespace
1617/// definition.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001618Sema::DeclPtrTy Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1619 SourceLocation IdentLoc,
1620 IdentifierInfo *II,
1621 SourceLocation LBrace) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001622 NamespaceDecl *Namespc =
1623 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1624 Namespc->setLBracLoc(LBrace);
1625
1626 Scope *DeclRegionScope = NamespcScope->getParent();
1627
1628 if (II) {
1629 // C++ [namespace.def]p2:
1630 // The identifier in an original-namespace-definition shall not have been
1631 // previously defined in the declarative region in which the
1632 // original-namespace-definition appears. The identifier in an
1633 // original-namespace-definition is the name of the namespace. Subsequently
1634 // in that declarative region, it is treated as an original-namespace-name.
1635
Douglas Gregor09be81b2009-02-04 17:27:36 +00001636 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1637 true);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001638
1639 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1640 // This is an extended namespace definition.
1641 // Attach this namespace decl to the chain of extended namespace
1642 // definitions.
1643 OrigNS->setNextNamespace(Namespc);
1644 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001645
Douglas Gregor8acb7272008-12-11 16:49:14 +00001646 // Remove the previous declaration from the scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001647 if (DeclRegionScope->isDeclScope(DeclPtrTy::make(OrigNS))) {
Douglas Gregor39677622008-12-11 20:41:00 +00001648 IdResolver.RemoveDecl(OrigNS);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001649 DeclRegionScope->RemoveDecl(DeclPtrTy::make(OrigNS));
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001650 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001651 } else if (PrevDecl) {
1652 // This is an invalid name redefinition.
1653 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1654 << Namespc->getDeclName();
1655 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1656 Namespc->setInvalidDecl();
1657 // Continue on to push Namespc as current DeclContext and return it.
1658 }
1659
1660 PushOnScopeChains(Namespc, DeclRegionScope);
1661 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001662 // FIXME: Handle anonymous namespaces
1663 }
1664
1665 // Although we could have an invalid decl (i.e. the namespace name is a
1666 // redefinition), push it as current DeclContext and try to continue parsing.
Mike Stumpe127ae32009-05-16 07:39:55 +00001667 // FIXME: We should be able to push Namespc here, so that the each DeclContext
1668 // for the namespace has the declarations that showed up in that particular
1669 // namespace definition.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001670 PushDeclContext(NamespcScope, Namespc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001671 return DeclPtrTy::make(Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001672}
1673
1674/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1675/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001676void Sema::ActOnFinishNamespaceDef(DeclPtrTy D, SourceLocation RBrace) {
1677 Decl *Dcl = D.getAs<Decl>();
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001678 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1679 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1680 Namespc->setRBracLoc(RBrace);
1681 PopDeclContext();
1682}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001683
Chris Lattner5261d0c2009-03-28 19:18:32 +00001684Sema::DeclPtrTy Sema::ActOnUsingDirective(Scope *S,
1685 SourceLocation UsingLoc,
1686 SourceLocation NamespcLoc,
1687 const CXXScopeSpec &SS,
1688 SourceLocation IdentLoc,
1689 IdentifierInfo *NamespcName,
1690 AttributeList *AttrList) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001691 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1692 assert(NamespcName && "Invalid NamespcName.");
1693 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001694 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001695
Douglas Gregor7a7be652009-02-03 19:21:40 +00001696 UsingDirectiveDecl *UDir = 0;
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001697
Douglas Gregor78d70132009-01-14 22:20:51 +00001698 // Lookup namespace name.
Douglas Gregor7a7be652009-02-03 19:21:40 +00001699 LookupResult R = LookupParsedName(S, &SS, NamespcName,
1700 LookupNamespaceName, false);
1701 if (R.isAmbiguous()) {
1702 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001703 return DeclPtrTy();
Douglas Gregor7a7be652009-02-03 19:21:40 +00001704 }
Douglas Gregor09be81b2009-02-04 17:27:36 +00001705 if (NamedDecl *NS = R) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001706 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001707 // C++ [namespace.udir]p1:
1708 // A using-directive specifies that the names in the nominated
1709 // namespace can be used in the scope in which the
1710 // using-directive appears after the using-directive. During
1711 // unqualified name lookup (3.4.1), the names appear as if they
1712 // were declared in the nearest enclosing namespace which
1713 // contains both the using-directive and the nominated
1714 // namespace. [Note: in this context, “contains” means “contains
1715 // directly or indirectly”. ]
1716
1717 // Find enclosing context containing both using-directive and
1718 // nominated namespace.
1719 DeclContext *CommonAncestor = cast<DeclContext>(NS);
1720 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1721 CommonAncestor = CommonAncestor->getParent();
1722
Douglas Gregor1d27d692009-05-30 06:31:56 +00001723 UDir = UsingDirectiveDecl::Create(Context,
1724 CurContext, UsingLoc,
1725 NamespcLoc,
1726 SS.getRange(),
1727 (NestedNameSpecifier *)SS.getScopeRep(),
1728 IdentLoc,
Douglas Gregor7a7be652009-02-03 19:21:40 +00001729 cast<NamespaceDecl>(NS),
1730 CommonAncestor);
1731 PushUsingDirective(S, UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001732 } else {
Chris Lattner954381a2009-01-06 07:24:29 +00001733 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001734 }
1735
Douglas Gregor7a7be652009-02-03 19:21:40 +00001736 // FIXME: We ignore attributes for now.
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001737 delete AttrList;
Chris Lattner5261d0c2009-03-28 19:18:32 +00001738 return DeclPtrTy::make(UDir);
Douglas Gregor7a7be652009-02-03 19:21:40 +00001739}
1740
1741void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1742 // If scope has associated entity, then using directive is at namespace
1743 // or translation unit scope. We add UsingDirectiveDecls, into
1744 // it's lookup structure.
1745 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001746 Ctx->addDecl(Context, UDir);
Douglas Gregor7a7be652009-02-03 19:21:40 +00001747 else
1748 // Otherwise it is block-sope. using-directives will affect lookup
1749 // only to the end of scope.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001750 S->PushUsingDirective(DeclPtrTy::make(UDir));
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001751}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001752
Anders Carlsson7c1c5482009-03-28 23:53:49 +00001753/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
1754/// is a namespace alias, returns the namespace it points to.
1755static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
1756 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
1757 return AD->getNamespace();
1758 return dyn_cast_or_null<NamespaceDecl>(D);
1759}
1760
Chris Lattner5261d0c2009-03-28 19:18:32 +00001761Sema::DeclPtrTy Sema::ActOnNamespaceAliasDef(Scope *S,
Anders Carlsson26de7882009-03-28 22:53:22 +00001762 SourceLocation NamespaceLoc,
Chris Lattner5261d0c2009-03-28 19:18:32 +00001763 SourceLocation AliasLoc,
1764 IdentifierInfo *Alias,
1765 const CXXScopeSpec &SS,
Anders Carlsson26de7882009-03-28 22:53:22 +00001766 SourceLocation IdentLoc,
1767 IdentifierInfo *Ident) {
Anders Carlsson640eb7c2009-03-28 06:23:46 +00001768
Anders Carlsson7c1c5482009-03-28 23:53:49 +00001769 // Lookup the namespace name.
1770 LookupResult R = LookupParsedName(S, &SS, Ident, LookupNamespaceName, false);
1771
Anders Carlsson640eb7c2009-03-28 06:23:46 +00001772 // Check if we have a previous declaration with the same name.
Anders Carlsson1cd05f52009-03-28 23:49:35 +00001773 if (NamedDecl *PrevDecl = LookupName(S, Alias, LookupOrdinaryName, true)) {
Anders Carlsson7c1c5482009-03-28 23:53:49 +00001774 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
1775 // We already have an alias with the same name that points to the same
1776 // namespace, so don't create a new one.
1777 if (!R.isAmbiguous() && AD->getNamespace() == getNamespaceDecl(R))
1778 return DeclPtrTy();
1779 }
1780
Anders Carlsson640eb7c2009-03-28 06:23:46 +00001781 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
1782 diag::err_redefinition_different_kind;
1783 Diag(AliasLoc, DiagID) << Alias;
1784 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001785 return DeclPtrTy();
Anders Carlsson640eb7c2009-03-28 06:23:46 +00001786 }
1787
Anders Carlsson279ebc42009-03-28 06:42:02 +00001788 if (R.isAmbiguous()) {
Anders Carlsson26de7882009-03-28 22:53:22 +00001789 DiagnoseAmbiguousLookup(R, Ident, IdentLoc);
Chris Lattner5261d0c2009-03-28 19:18:32 +00001790 return DeclPtrTy();
Anders Carlsson279ebc42009-03-28 06:42:02 +00001791 }
1792
1793 if (!R) {
1794 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
Chris Lattner5261d0c2009-03-28 19:18:32 +00001795 return DeclPtrTy();
Anders Carlsson279ebc42009-03-28 06:42:02 +00001796 }
1797
Anders Carlssonddb1d8b2009-03-28 22:58:02 +00001798 NamespaceAliasDecl *AliasDecl =
Douglas Gregor8d8ddca2009-05-30 06:48:27 +00001799 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
1800 Alias, SS.getRange(),
1801 (NestedNameSpecifier *)SS.getScopeRep(),
Anders Carlssonddb1d8b2009-03-28 22:58:02 +00001802 IdentLoc, R);
1803
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001804 CurContext->addDecl(Context, AliasDecl);
Anders Carlssonddb1d8b2009-03-28 22:58:02 +00001805 return DeclPtrTy::make(AliasDecl);
Anders Carlsson8cffcd62009-03-28 05:27:17 +00001806}
1807
Anders Carlsson05e59652009-04-16 23:50:50 +00001808void Sema::InitializeVarWithConstructor(VarDecl *VD,
1809 CXXConstructorDecl *Constructor,
1810 QualType DeclInitType,
1811 Expr **Exprs, unsigned NumExprs) {
Anders Carlsson7b7b2552009-05-30 20:56:46 +00001812 Expr *Temp = CXXConstructExpr::Create(Context, DeclInitType, Constructor,
Anders Carlsson6a95cd12009-04-24 05:16:06 +00001813 false, Exprs, NumExprs);
Douglas Gregor4833ff02009-05-26 18:54:04 +00001814 VD->setInit(Context, Temp);
Anders Carlsson05e59652009-04-16 23:50:50 +00001815}
1816
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001817/// AddCXXDirectInitializerToDecl - This action is called immediately after
1818/// ActOnDeclarator, when a C++ direct initializer is present.
1819/// e.g: "int x(1);"
Chris Lattner5261d0c2009-03-28 19:18:32 +00001820void Sema::AddCXXDirectInitializerToDecl(DeclPtrTy Dcl,
1821 SourceLocation LParenLoc,
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001822 MultiExprArg Exprs,
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001823 SourceLocation *CommaLocs,
1824 SourceLocation RParenLoc) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001825 unsigned NumExprs = Exprs.size();
1826 assert(NumExprs != 0 && Exprs.get() && "missing expressions");
Chris Lattner5261d0c2009-03-28 19:18:32 +00001827 Decl *RealDecl = Dcl.getAs<Decl>();
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001828
1829 // If there is no declaration, there was an error parsing it. Just ignore
1830 // the initializer.
Chris Lattner5261d0c2009-03-28 19:18:32 +00001831 if (RealDecl == 0)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001832 return;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001833
1834 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1835 if (!VDecl) {
1836 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1837 RealDecl->setInvalidDecl();
1838 return;
1839 }
1840
Douglas Gregorad7d1812009-03-24 16:43:20 +00001841 // FIXME: Need to handle dependent types and expressions here.
1842
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001843 // We will treat direct-initialization as a copy-initialization:
1844 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001845 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1846 //
1847 // Clients that want to distinguish between the two forms, can check for
1848 // direct initializer using VarDecl::hasCXXDirectInitializer().
1849 // A major benefit is that clients that don't particularly care about which
1850 // exactly form was it (like the CodeGen) can handle both cases without
1851 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001852
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001853 // C++ 8.5p11:
1854 // The form of initialization (using parentheses or '=') is generally
1855 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001856 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001857 QualType DeclInitType = VDecl->getType();
1858 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1859 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001860
Douglas Gregorad7d1812009-03-24 16:43:20 +00001861 // FIXME: This isn't the right place to complete the type.
1862 if (RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
1863 diag::err_typecheck_decl_incomplete_type)) {
1864 VDecl->setInvalidDecl();
1865 return;
1866 }
1867
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001868 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001869 CXXConstructorDecl *Constructor
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001870 = PerformInitializationByConstructor(DeclInitType,
1871 (Expr **)Exprs.get(), NumExprs,
Douglas Gregor6428e762008-11-05 15:29:30 +00001872 VDecl->getLocation(),
1873 SourceRange(VDecl->getLocation(),
1874 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00001875 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00001876 IK_Direct);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001877 if (!Constructor)
Douglas Gregor5870a952008-11-03 20:45:27 +00001878 RealDecl->setInvalidDecl();
Anders Carlsson9c7b4922009-04-15 21:48:18 +00001879 else {
Anders Carlsson9c7b4922009-04-15 21:48:18 +00001880 VDecl->setCXXDirectInitializer(true);
Anders Carlsson05e59652009-04-16 23:50:50 +00001881 InitializeVarWithConstructor(VDecl, Constructor, DeclInitType,
1882 (Expr**)Exprs.release(), NumExprs);
Anders Carlsson9c7b4922009-04-15 21:48:18 +00001883 }
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001884 return;
1885 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001886
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001887 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001888 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1889 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001890 RealDecl->setInvalidDecl();
1891 return;
1892 }
1893
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001894 // Let clients know that initialization was done with a direct initializer.
1895 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001896
1897 assert(NumExprs == 1 && "Expected 1 expression");
1898 // Set the init expression, handles conversions.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00001899 AddInitializerToDecl(Dcl, ExprArg(*this, Exprs.release()[0]),
1900 /*DirectInit=*/true);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001901}
Douglas Gregor81c29152008-10-29 00:13:59 +00001902
Douglas Gregor6428e762008-11-05 15:29:30 +00001903/// PerformInitializationByConstructor - Perform initialization by
1904/// constructor (C++ [dcl.init]p14), which may occur as part of
1905/// direct-initialization or copy-initialization. We are initializing
1906/// an object of type @p ClassType with the given arguments @p
1907/// Args. @p Loc is the location in the source code where the
1908/// initializer occurs (e.g., a declaration, member initializer,
1909/// functional cast, etc.) while @p Range covers the whole
1910/// initialization. @p InitEntity is the entity being initialized,
1911/// which may by the name of a declaration or a type. @p Kind is the
1912/// kind of initialization we're performing, which affects whether
1913/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001914/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001915/// when the initialization fails, emits a diagnostic and returns
1916/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001917CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001918Sema::PerformInitializationByConstructor(QualType ClassType,
1919 Expr **Args, unsigned NumArgs,
1920 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00001921 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00001922 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001923 const RecordType *ClassRec = ClassType->getAsRecordType();
1924 assert(ClassRec && "Can only initialize a class type here");
1925
1926 // C++ [dcl.init]p14:
1927 //
1928 // If the initialization is direct-initialization, or if it is
1929 // copy-initialization where the cv-unqualified version of the
1930 // source type is the same class as, or a derived class of, the
1931 // class of the destination, constructors are considered. The
1932 // applicable constructors are enumerated (13.3.1.3), and the
1933 // best one is chosen through overload resolution (13.3). The
1934 // constructor so selected is called to initialize the object,
1935 // with the initializer expression(s) as its argument(s). If no
1936 // constructor applies, or the overload resolution is ambiguous,
1937 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001938 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1939 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001940
1941 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00001942 DeclarationName ConstructorName
1943 = Context.DeclarationNames.getCXXConstructorName(
1944 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001945 DeclContext::lookup_const_iterator Con, ConEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001946 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(Context, ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001947 Con != ConEnd; ++Con) {
1948 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor6428e762008-11-05 15:29:30 +00001949 if ((Kind == IK_Direct) ||
1950 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1951 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1952 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1953 }
1954
Douglas Gregorb9213832008-12-15 21:24:18 +00001955 // FIXME: When we decide not to synthesize the implicitly-declared
1956 // constructors, we'll need to make them appear here.
1957
Douglas Gregor5870a952008-11-03 20:45:27 +00001958 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001959 switch (BestViableFunction(CandidateSet, Best)) {
1960 case OR_Success:
1961 // We found a constructor. Return it.
1962 return cast<CXXConstructorDecl>(Best->Function);
1963
1964 case OR_No_Viable_Function:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001965 if (InitEntity)
1966 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001967 << InitEntity << Range;
Douglas Gregor538a4c22009-02-02 17:43:21 +00001968 else
1969 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001970 << ClassType << Range;
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00001971 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00001972 return 0;
1973
1974 case OR_Ambiguous:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001975 if (InitEntity)
1976 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1977 else
1978 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00001979 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1980 return 0;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001981
1982 case OR_Deleted:
1983 if (InitEntity)
1984 Diag(Loc, diag::err_ovl_deleted_init)
1985 << Best->Function->isDeleted()
1986 << InitEntity << Range;
1987 else
1988 Diag(Loc, diag::err_ovl_deleted_init)
1989 << Best->Function->isDeleted()
1990 << InitEntity << Range;
1991 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1992 return 0;
Douglas Gregor5870a952008-11-03 20:45:27 +00001993 }
1994
1995 return 0;
1996}
1997
Douglas Gregor81c29152008-10-29 00:13:59 +00001998/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1999/// determine whether they are reference-related,
2000/// reference-compatible, reference-compatible with added
2001/// qualification, or incompatible, for use in C++ initialization by
2002/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2003/// type, and the first type (T1) is the pointee type of the reference
2004/// type being initialized.
2005Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002006Sema::CompareReferenceRelationship(QualType T1, QualType T2,
2007 bool& DerivedToBase) {
Sebastian Redlce6fff02009-03-16 23:22:08 +00002008 assert(!T1->isReferenceType() &&
2009 "T1 must be the pointee type of the reference type");
Douglas Gregor81c29152008-10-29 00:13:59 +00002010 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
2011
2012 T1 = Context.getCanonicalType(T1);
2013 T2 = Context.getCanonicalType(T2);
2014 QualType UnqualT1 = T1.getUnqualifiedType();
2015 QualType UnqualT2 = T2.getUnqualifiedType();
2016
2017 // C++ [dcl.init.ref]p4:
2018 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
2019 // reference-related to “cv2 T2” if T1 is the same type as T2, or
2020 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002021 if (UnqualT1 == UnqualT2)
2022 DerivedToBase = false;
2023 else if (IsDerivedFrom(UnqualT2, UnqualT1))
2024 DerivedToBase = true;
2025 else
Douglas Gregor81c29152008-10-29 00:13:59 +00002026 return Ref_Incompatible;
2027
2028 // At this point, we know that T1 and T2 are reference-related (at
2029 // least).
2030
2031 // C++ [dcl.init.ref]p4:
2032 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
2033 // reference-related to T2 and cv1 is the same cv-qualification
2034 // as, or greater cv-qualification than, cv2. For purposes of
2035 // overload resolution, cases for which cv1 is greater
2036 // cv-qualification than cv2 are identified as
2037 // reference-compatible with added qualification (see 13.3.3.2).
2038 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2039 return Ref_Compatible;
2040 else if (T1.isMoreQualifiedThan(T2))
2041 return Ref_Compatible_With_Added_Qualification;
2042 else
2043 return Ref_Related;
2044}
2045
2046/// CheckReferenceInit - Check the initialization of a reference
2047/// variable with the given initializer (C++ [dcl.init.ref]). Init is
2048/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00002049/// list), and DeclType is the type of the declaration. When ICS is
2050/// non-null, this routine will compute the implicit conversion
2051/// sequence according to C++ [over.ics.ref] and will not produce any
2052/// diagnostics; when ICS is null, it will emit diagnostics when any
2053/// errors are found. Either way, a return value of true indicates
2054/// that there was a failure, a return value of false indicates that
2055/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002056///
2057/// When @p SuppressUserConversions, user-defined conversions are
2058/// suppressed.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002059/// When @p AllowExplicit, we also permit explicit user-defined
2060/// conversion functions.
Sebastian Redla55834a2009-04-12 17:16:29 +00002061/// When @p ForceRValue, we unconditionally treat the initializer as an rvalue.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002062bool
Sebastian Redlbd261962009-04-16 17:51:27 +00002063Sema::CheckReferenceInit(Expr *&Init, QualType DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002064 ImplicitConversionSequence *ICS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002065 bool SuppressUserConversions,
Sebastian Redla55834a2009-04-12 17:16:29 +00002066 bool AllowExplicit, bool ForceRValue) {
Douglas Gregor81c29152008-10-29 00:13:59 +00002067 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2068
2069 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
2070 QualType T2 = Init->getType();
2071
Douglas Gregor45014fd2008-11-10 20:40:00 +00002072 // If the initializer is the address of an overloaded function, try
2073 // to resolve the overloaded function. If all goes well, T2 is the
2074 // type of the resulting function.
Douglas Gregor00fe3f62009-03-13 18:40:31 +00002075 if (Context.getCanonicalType(T2) == Context.OverloadTy) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00002076 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
2077 ICS != 0);
2078 if (Fn) {
2079 // Since we're performing this reference-initialization for
2080 // real, update the initializer with the resulting function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00002081 if (!ICS) {
2082 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
2083 return true;
2084
Douglas Gregor45014fd2008-11-10 20:40:00 +00002085 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregoraa57e862009-02-18 21:56:37 +00002086 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00002087
2088 T2 = Fn->getType();
2089 }
2090 }
2091
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002092 // Compute some basic properties of the types and the initializer.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002093 bool isRValRef = DeclType->isRValueReferenceType();
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002094 bool DerivedToBase = false;
Sebastian Redla55834a2009-04-12 17:16:29 +00002095 Expr::isLvalueResult InitLvalue = ForceRValue ? Expr::LV_InvalidExpression :
2096 Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002097 ReferenceCompareResult RefRelationship
2098 = CompareReferenceRelationship(T1, T2, DerivedToBase);
2099
2100 // Most paths end in a failed conversion.
2101 if (ICS)
2102 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00002103
2104 // C++ [dcl.init.ref]p5:
2105 // A reference to type “cv1 T1” is initialized by an expression
2106 // of type “cv2 T2” as follows:
2107
2108 // -- If the initializer expression
2109
Sebastian Redldfc30332009-03-29 15:27:50 +00002110 // Rvalue references cannot bind to lvalues (N2812).
2111 // There is absolutely no situation where they can. In particular, note that
2112 // this is ill-formed, even if B has a user-defined conversion to A&&:
2113 // B b;
2114 // A&& r = b;
2115 if (isRValRef && InitLvalue == Expr::LV_Valid) {
2116 if (!ICS)
2117 Diag(Init->getSourceRange().getBegin(), diag::err_lvalue_to_rvalue_ref)
2118 << Init->getSourceRange();
2119 return true;
2120 }
2121
Douglas Gregor81c29152008-10-29 00:13:59 +00002122 bool BindsDirectly = false;
2123 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
2124 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002125 //
2126 // Note that the bit-field check is skipped if we are just computing
2127 // the implicit conversion sequence (C++ [over.best.ics]p2).
Douglas Gregor531434b2009-05-02 02:18:30 +00002128 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->getBitField()) &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002129 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00002130 BindsDirectly = true;
2131
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002132 if (ICS) {
2133 // C++ [over.ics.ref]p1:
2134 // When a parameter of reference type binds directly (8.5.3)
2135 // to an argument expression, the implicit conversion sequence
2136 // is the identity conversion, unless the argument expression
2137 // has a type that is a derived class of the parameter type,
2138 // in which case the implicit conversion sequence is a
2139 // derived-to-base Conversion (13.3.3.1).
2140 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2141 ICS->Standard.First = ICK_Identity;
2142 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2143 ICS->Standard.Third = ICK_Identity;
2144 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2145 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00002146 ICS->Standard.ReferenceBinding = true;
2147 ICS->Standard.DirectBinding = true;
Sebastian Redldfc30332009-03-29 15:27:50 +00002148 ICS->Standard.RRefBinding = false;
Sebastian Redld3169132009-04-17 16:30:52 +00002149 ICS->Standard.CopyConstructor = 0;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002150
2151 // Nothing more to do: the inaccessibility/ambiguity check for
2152 // derived-to-base conversions is suppressed when we're
2153 // computing the implicit conversion sequence (C++
2154 // [over.best.ics]p2).
2155 return false;
2156 } else {
2157 // Perform the conversion.
Mike Stumpe127ae32009-05-16 07:39:55 +00002158 // FIXME: Binding to a subobject of the lvalue is going to require more
2159 // AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00002160 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00002161 }
2162 }
2163
2164 // -- has a class type (i.e., T2 is a class type) and can be
2165 // implicitly converted to an lvalue of type “cv3 T3,”
2166 // where “cv1 T1” is reference-compatible with “cv3 T3”
2167 // 92) (this conversion is selected by enumerating the
2168 // applicable conversion functions (13.3.1.6) and choosing
2169 // the best one through overload resolution (13.3)),
Sebastian Redlce6fff02009-03-16 23:22:08 +00002170 if (!isRValRef && !SuppressUserConversions && T2->isRecordType()) {
Douglas Gregore6985fe2008-11-10 16:14:15 +00002171 // FIXME: Look for conversions in base classes!
2172 CXXRecordDecl *T2RecordDecl
2173 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00002174
Douglas Gregore6985fe2008-11-10 16:14:15 +00002175 OverloadCandidateSet CandidateSet;
2176 OverloadedFunctionDecl *Conversions
2177 = T2RecordDecl->getConversionFunctions();
2178 for (OverloadedFunctionDecl::function_iterator Func
2179 = Conversions->function_begin();
2180 Func != Conversions->function_end(); ++Func) {
2181 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
Sebastian Redl16ac38f2009-03-22 21:28:55 +00002182
Douglas Gregore6985fe2008-11-10 16:14:15 +00002183 // If the conversion function doesn't return a reference type,
2184 // it can't be considered for this conversion.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002185 if (Conv->getConversionType()->isLValueReferenceType() &&
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002186 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregore6985fe2008-11-10 16:14:15 +00002187 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
2188 }
2189
2190 OverloadCandidateSet::iterator Best;
2191 switch (BestViableFunction(CandidateSet, Best)) {
2192 case OR_Success:
2193 // This is a direct binding.
2194 BindsDirectly = true;
2195
2196 if (ICS) {
2197 // C++ [over.ics.ref]p1:
2198 //
2199 // [...] If the parameter binds directly to the result of
2200 // applying a conversion function to the argument
2201 // expression, the implicit conversion sequence is a
2202 // user-defined conversion sequence (13.3.3.1.2), with the
2203 // second standard conversion sequence either an identity
2204 // conversion or, if the conversion function returns an
2205 // entity of a type that is a derived class of the parameter
2206 // type, a derived-to-base Conversion.
2207 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
2208 ICS->UserDefined.Before = Best->Conversions[0].Standard;
2209 ICS->UserDefined.After = Best->FinalConversion;
2210 ICS->UserDefined.ConversionFunction = Best->Function;
2211 assert(ICS->UserDefined.After.ReferenceBinding &&
2212 ICS->UserDefined.After.DirectBinding &&
2213 "Expected a direct reference binding!");
2214 return false;
2215 } else {
2216 // Perform the conversion.
Mike Stumpe127ae32009-05-16 07:39:55 +00002217 // FIXME: Binding to a subobject of the lvalue is going to require more
2218 // AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00002219 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00002220 }
2221 break;
2222
2223 case OR_Ambiguous:
2224 assert(false && "Ambiguous reference binding conversions not implemented.");
2225 return true;
2226
2227 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00002228 case OR_Deleted:
2229 // There was no suitable conversion, or we found a deleted
2230 // conversion; continue with other checks.
Douglas Gregore6985fe2008-11-10 16:14:15 +00002231 break;
2232 }
2233 }
2234
Douglas Gregor81c29152008-10-29 00:13:59 +00002235 if (BindsDirectly) {
2236 // C++ [dcl.init.ref]p4:
2237 // [...] In all cases where the reference-related or
2238 // reference-compatible relationship of two types is used to
2239 // establish the validity of a reference binding, and T1 is a
2240 // base class of T2, a program that necessitates such a binding
2241 // is ill-formed if T1 is an inaccessible (clause 11) or
2242 // ambiguous (10.2) base class of T2.
2243 //
2244 // Note that we only check this condition when we're allowed to
2245 // complain about errors, because we should not be checking for
2246 // ambiguity (or inaccessibility) unless the reference binding
2247 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002248 if (DerivedToBase)
2249 return CheckDerivedToBaseConversion(T2, T1,
2250 Init->getSourceRange().getBegin(),
2251 Init->getSourceRange());
2252 else
2253 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00002254 }
2255
2256 // -- Otherwise, the reference shall be to a non-volatile const
Sebastian Redldfc30332009-03-29 15:27:50 +00002257 // type (i.e., cv1 shall be const), or the reference shall be an
2258 // rvalue reference and the initializer expression shall be an rvalue.
Sebastian Redlce6fff02009-03-16 23:22:08 +00002259 if (!isRValRef && T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002260 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00002261 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00002262 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002263 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2264 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00002265 return true;
2266 }
2267
2268 // -- If the initializer expression is an rvalue, with T2 a
2269 // class type, and “cv1 T1” is reference-compatible with
2270 // “cv2 T2,” the reference is bound in one of the
2271 // following ways (the choice is implementation-defined):
2272 //
2273 // -- The reference is bound to the object represented by
2274 // the rvalue (see 3.10) or to a sub-object within that
2275 // object.
2276 //
2277 // -- A temporary of type “cv1 T2” [sic] is created, and
2278 // a constructor is called to copy the entire rvalue
2279 // object into the temporary. The reference is bound to
2280 // the temporary or to a sub-object within the
2281 // temporary.
2282 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002283 // The constructor that would be used to make the copy
2284 // shall be callable whether or not the copy is actually
2285 // done.
2286 //
Sebastian Redldfc30332009-03-29 15:27:50 +00002287 // Note that C++0x [dcl.init.ref]p5 takes away this implementation
Douglas Gregor81c29152008-10-29 00:13:59 +00002288 // freedom, so we will always take the first option and never build
2289 // a temporary in this case. FIXME: We will, however, have to check
2290 // for the presence of a copy constructor in C++98/03 mode.
2291 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002292 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
2293 if (ICS) {
2294 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
2295 ICS->Standard.First = ICK_Identity;
2296 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2297 ICS->Standard.Third = ICK_Identity;
2298 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2299 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00002300 ICS->Standard.ReferenceBinding = true;
Sebastian Redldfc30332009-03-29 15:27:50 +00002301 ICS->Standard.DirectBinding = false;
2302 ICS->Standard.RRefBinding = isRValRef;
Sebastian Redld3169132009-04-17 16:30:52 +00002303 ICS->Standard.CopyConstructor = 0;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002304 } else {
Mike Stumpe127ae32009-05-16 07:39:55 +00002305 // FIXME: Binding to a subobject of the rvalue is going to require more
2306 // AST annotation than this.
Anders Carlsson30c35bf2009-05-19 00:38:24 +00002307 ImpCastExprToType(Init, T1, /*isLvalue=*/false);
Douglas Gregor81c29152008-10-29 00:13:59 +00002308 }
2309 return false;
2310 }
2311
2312 // -- Otherwise, a temporary of type “cv1 T1” is created and
2313 // initialized from the initializer expression using the
2314 // rules for a non-reference copy initialization (8.5). The
2315 // reference is then bound to the temporary. If T1 is
2316 // reference-related to T2, cv1 must be the same
2317 // cv-qualification as, or greater cv-qualification than,
2318 // cv2; otherwise, the program is ill-formed.
2319 if (RefRelationship == Ref_Related) {
2320 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2321 // we would be reference-compatible or reference-compatible with
2322 // added qualification. But that wasn't the case, so the reference
2323 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002324 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00002325 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00002326 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002327 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2328 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00002329 return true;
2330 }
2331
Douglas Gregorb206cc42009-01-30 23:27:23 +00002332 // If at least one of the types is a class type, the types are not
2333 // related, and we aren't allowed any user conversions, the
2334 // reference binding fails. This case is important for breaking
2335 // recursion, since TryImplicitConversion below will attempt to
2336 // create a temporary through the use of a copy constructor.
2337 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2338 (T1->isRecordType() || T2->isRecordType())) {
2339 if (!ICS)
2340 Diag(Init->getSourceRange().getBegin(),
2341 diag::err_typecheck_convert_incompatible)
2342 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2343 return true;
2344 }
2345
Douglas Gregor81c29152008-10-29 00:13:59 +00002346 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002347 if (ICS) {
Sebastian Redldfc30332009-03-29 15:27:50 +00002348 // C++ [over.ics.ref]p2:
2349 //
2350 // When a parameter of reference type is not bound directly to
2351 // an argument expression, the conversion sequence is the one
2352 // required to convert the argument expression to the
2353 // underlying type of the reference according to
2354 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2355 // to copy-initializing a temporary of the underlying type with
2356 // the argument expression. Any difference in top-level
2357 // cv-qualification is subsumed by the initialization itself
2358 // and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002359 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Sebastian Redldfc30332009-03-29 15:27:50 +00002360 // Of course, that's still a reference binding.
2361 if (ICS->ConversionKind == ImplicitConversionSequence::StandardConversion) {
2362 ICS->Standard.ReferenceBinding = true;
2363 ICS->Standard.RRefBinding = isRValRef;
2364 } else if(ICS->ConversionKind ==
2365 ImplicitConversionSequence::UserDefinedConversion) {
2366 ICS->UserDefined.After.ReferenceBinding = true;
2367 ICS->UserDefined.After.RRefBinding = isRValRef;
2368 }
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002369 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2370 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00002371 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002372 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002373}
Douglas Gregore60e5d32008-11-06 22:13:31 +00002374
2375/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2376/// of this overloaded operator is well-formed. If so, returns false;
2377/// otherwise, emits appropriate diagnostics and returns true.
2378bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002379 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00002380 "Expected an overloaded operator declaration");
2381
Douglas Gregore60e5d32008-11-06 22:13:31 +00002382 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2383
2384 // C++ [over.oper]p5:
2385 // The allocation and deallocation functions, operator new,
2386 // operator new[], operator delete and operator delete[], are
2387 // described completely in 3.7.3. The attributes and restrictions
2388 // found in the rest of this subclause do not apply to them unless
2389 // explicitly stated in 3.7.3.
Mike Stumpe127ae32009-05-16 07:39:55 +00002390 // FIXME: Write a separate routine for checking this. For now, just allow it.
Douglas Gregore60e5d32008-11-06 22:13:31 +00002391 if (Op == OO_New || Op == OO_Array_New ||
2392 Op == OO_Delete || Op == OO_Array_Delete)
2393 return false;
2394
2395 // C++ [over.oper]p6:
2396 // An operator function shall either be a non-static member
2397 // function or be a non-member function and have at least one
2398 // parameter whose type is a class, a reference to a class, an
2399 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002400 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2401 if (MethodDecl->isStatic())
2402 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002403 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002404 } else {
2405 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002406 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2407 ParamEnd = FnDecl->param_end();
2408 Param != ParamEnd; ++Param) {
2409 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002410 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2411 ClassOrEnumParam = true;
2412 break;
2413 }
2414 }
2415
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002416 if (!ClassOrEnumParam)
2417 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002418 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00002419 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002420 }
2421
2422 // C++ [over.oper]p8:
2423 // An operator function cannot have default arguments (8.3.6),
2424 // except where explicitly stated below.
2425 //
2426 // Only the function-call operator allows default arguments
2427 // (C++ [over.call]p1).
2428 if (Op != OO_Call) {
2429 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2430 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002431 if ((*Param)->hasUnparsedDefaultArg())
2432 return Diag((*Param)->getLocation(),
2433 diag::err_operator_overload_default_arg)
2434 << FnDecl->getDeclName();
2435 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002436 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00002437 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00002438 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002439 }
2440 }
2441
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002442 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2443 { false, false, false }
2444#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2445 , { Unary, Binary, MemberOnly }
2446#include "clang/Basic/OperatorKinds.def"
2447 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00002448
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002449 bool CanBeUnaryOperator = OperatorUses[Op][0];
2450 bool CanBeBinaryOperator = OperatorUses[Op][1];
2451 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00002452
2453 // C++ [over.oper]p8:
2454 // [...] Operator functions cannot have more or fewer parameters
2455 // than the number required for the corresponding operator, as
2456 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002457 unsigned NumParams = FnDecl->getNumParams()
2458 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002459 if (Op != OO_Call &&
2460 ((NumParams == 1 && !CanBeUnaryOperator) ||
2461 (NumParams == 2 && !CanBeBinaryOperator) ||
2462 (NumParams < 1) || (NumParams > 2))) {
2463 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00002464 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002465 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002466 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002467 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002468 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002469 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00002470 assert(CanBeBinaryOperator &&
2471 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00002472 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002473 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00002474
Chris Lattnerbb002332008-11-21 07:57:12 +00002475 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00002476 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002477 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002478
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002479 // Overloaded operators other than operator() cannot be variadic.
2480 if (Op != OO_Call &&
Douglas Gregor4fa58902009-02-26 23:50:07 +00002481 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002482 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00002483 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002484 }
2485
2486 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002487 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2488 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002489 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00002490 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002491 }
2492
2493 // C++ [over.inc]p1:
2494 // The user-defined function called operator++ implements the
2495 // prefix and postfix ++ operator. If this function is a member
2496 // function with no parameters, or a non-member function with one
2497 // parameter of class or enumeration type, it defines the prefix
2498 // increment operator ++ for objects of that type. If the function
2499 // is a member function with one parameter (which shall be of type
2500 // int) or a non-member function with two parameters (the second
2501 // of which shall be of type int), it defines the postfix
2502 // increment operator ++ for objects of that type.
2503 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2504 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2505 bool ParamIsInt = false;
2506 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2507 ParamIsInt = BT->getKind() == BuiltinType::Int;
2508
Chris Lattnera7021ee2008-11-21 07:50:02 +00002509 if (!ParamIsInt)
2510 return Diag(LastParam->getLocation(),
2511 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002512 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002513 }
2514
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002515 // Notify the class if it got an assignment operator.
2516 if (Op == OO_Equal) {
2517 // Would have returned earlier otherwise.
2518 assert(isa<CXXMethodDecl>(FnDecl) &&
2519 "Overloaded = not member, but not filtered.");
2520 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2521 Method->getParent()->addedAssignmentOperator(Context, Method);
2522 }
2523
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002524 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002525}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002526
Douglas Gregord8028382009-01-05 19:45:36 +00002527/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2528/// linkage specification, including the language and (if present)
2529/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2530/// the location of the language string literal, which is provided
2531/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2532/// the '{' brace. Otherwise, this linkage specification does not
2533/// have any braces.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002534Sema::DeclPtrTy Sema::ActOnStartLinkageSpecification(Scope *S,
2535 SourceLocation ExternLoc,
2536 SourceLocation LangLoc,
2537 const char *Lang,
2538 unsigned StrSize,
2539 SourceLocation LBraceLoc) {
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002540 LinkageSpecDecl::LanguageIDs Language;
2541 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2542 Language = LinkageSpecDecl::lang_c;
2543 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2544 Language = LinkageSpecDecl::lang_cxx;
2545 else {
Douglas Gregord8028382009-01-05 19:45:36 +00002546 Diag(LangLoc, diag::err_bad_language);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002547 return DeclPtrTy();
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002548 }
2549
2550 // FIXME: Add all the various semantics of linkage specifications
2551
Douglas Gregord8028382009-01-05 19:45:36 +00002552 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2553 LangLoc, Language,
2554 LBraceLoc.isValid());
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002555 CurContext->addDecl(Context, D);
Douglas Gregord8028382009-01-05 19:45:36 +00002556 PushDeclContext(S, D);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002557 return DeclPtrTy::make(D);
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002558}
2559
Douglas Gregord8028382009-01-05 19:45:36 +00002560/// ActOnFinishLinkageSpecification - Completely the definition of
2561/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2562/// valid, it's the position of the closing '}' brace in a linkage
2563/// specification that uses braces.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002564Sema::DeclPtrTy Sema::ActOnFinishLinkageSpecification(Scope *S,
2565 DeclPtrTy LinkageSpec,
2566 SourceLocation RBraceLoc) {
Douglas Gregord8028382009-01-05 19:45:36 +00002567 if (LinkageSpec)
2568 PopDeclContext();
2569 return LinkageSpec;
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002570}
2571
Douglas Gregor57420b42009-05-18 20:51:54 +00002572/// \brief Perform semantic analysis for the variable declaration that
2573/// occurs within a C++ catch clause, returning the newly-created
2574/// variable.
2575VarDecl *Sema::BuildExceptionDeclaration(Scope *S, QualType ExDeclType,
2576 IdentifierInfo *Name,
2577 SourceLocation Loc,
2578 SourceRange Range) {
2579 bool Invalid = false;
Sebastian Redl743c8162008-12-22 19:15:10 +00002580
2581 // Arrays and functions decay.
2582 if (ExDeclType->isArrayType())
2583 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2584 else if (ExDeclType->isFunctionType())
2585 ExDeclType = Context.getPointerType(ExDeclType);
2586
2587 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2588 // The exception-declaration shall not denote a pointer or reference to an
2589 // incomplete type, other than [cv] void*.
Sebastian Redl8a8b3512009-03-22 23:49:27 +00002590 // N2844 forbids rvalue references.
Douglas Gregor3b7e9112009-05-18 21:08:14 +00002591 if(!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
Douglas Gregor57420b42009-05-18 20:51:54 +00002592 Diag(Loc, diag::err_catch_rvalue_ref) << Range;
Sebastian Redl8a8b3512009-03-22 23:49:27 +00002593 Invalid = true;
2594 }
Douglas Gregor57420b42009-05-18 20:51:54 +00002595
Sebastian Redl743c8162008-12-22 19:15:10 +00002596 QualType BaseType = ExDeclType;
2597 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002598 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl743c8162008-12-22 19:15:10 +00002599 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2600 BaseType = Ptr->getPointeeType();
2601 Mode = 1;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002602 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl743c8162008-12-22 19:15:10 +00002603 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
Sebastian Redl8a8b3512009-03-22 23:49:27 +00002604 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
Sebastian Redl743c8162008-12-22 19:15:10 +00002605 BaseType = Ref->getPointeeType();
2606 Mode = 2;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002607 DK = diag::err_catch_incomplete_ref;
Sebastian Redl743c8162008-12-22 19:15:10 +00002608 }
Sebastian Redl8a8b3512009-03-22 23:49:27 +00002609 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregor57420b42009-05-18 20:51:54 +00002610 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
Sebastian Redl743c8162008-12-22 19:15:10 +00002611 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00002612
Douglas Gregor57420b42009-05-18 20:51:54 +00002613 if (!Invalid && !ExDeclType->isDependentType() &&
2614 RequireNonAbstractType(Loc, ExDeclType,
2615 diag::err_abstract_type_in_decl,
2616 AbstractVariableType))
Sebastian Redl54198652009-04-27 21:03:30 +00002617 Invalid = true;
2618
Douglas Gregor57420b42009-05-18 20:51:54 +00002619 // FIXME: Need to test for ability to copy-construct and destroy the
2620 // exception variable.
2621
Sebastian Redl237116b2008-12-22 21:35:02 +00002622 // FIXME: Need to check for abstract classes.
2623
Douglas Gregor57420b42009-05-18 20:51:54 +00002624 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, Loc,
2625 Name, ExDeclType, VarDecl::None,
2626 Range.getBegin());
2627
2628 if (Invalid)
2629 ExDecl->setInvalidDecl();
2630
2631 return ExDecl;
2632}
2633
2634/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2635/// handler.
2636Sema::DeclPtrTy Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
2637 QualType ExDeclType = GetTypeForDeclarator(D, S);
2638
2639 bool Invalid = D.isInvalidType();
Sebastian Redl743c8162008-12-22 19:15:10 +00002640 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor09be81b2009-02-04 17:27:36 +00002641 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl743c8162008-12-22 19:15:10 +00002642 // The scope should be freshly made just for us. There is just no way
2643 // it contains any previous declaration.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002644 assert(!S->isDeclScope(DeclPtrTy::make(PrevDecl)));
Sebastian Redl743c8162008-12-22 19:15:10 +00002645 if (PrevDecl->isTemplateParameter()) {
2646 // Maybe we will complain about the shadowed template parameter.
2647 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00002648 }
2649 }
2650
Chris Lattner34c61332009-04-25 08:06:05 +00002651 if (D.getCXXScopeSpec().isSet() && !Invalid) {
Sebastian Redl743c8162008-12-22 19:15:10 +00002652 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2653 << D.getCXXScopeSpec().getRange();
Chris Lattner34c61332009-04-25 08:06:05 +00002654 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00002655 }
2656
Douglas Gregor57420b42009-05-18 20:51:54 +00002657 VarDecl *ExDecl = BuildExceptionDeclaration(S, ExDeclType,
2658 D.getIdentifier(),
2659 D.getIdentifierLoc(),
2660 D.getDeclSpec().getSourceRange());
2661
Chris Lattner34c61332009-04-25 08:06:05 +00002662 if (Invalid)
2663 ExDecl->setInvalidDecl();
2664
Sebastian Redl743c8162008-12-22 19:15:10 +00002665 // Add the exception declaration into this scope.
Sebastian Redl743c8162008-12-22 19:15:10 +00002666 if (II)
Douglas Gregor57420b42009-05-18 20:51:54 +00002667 PushOnScopeChains(ExDecl, S);
2668 else
2669 CurContext->addDecl(Context, ExDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00002670
2671 ProcessDeclAttributes(ExDecl, D);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002672 return DeclPtrTy::make(ExDecl);
Sebastian Redl743c8162008-12-22 19:15:10 +00002673}
Anders Carlssoned691562009-03-14 00:25:26 +00002674
Chris Lattner5261d0c2009-03-28 19:18:32 +00002675Sema::DeclPtrTy Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc,
2676 ExprArg assertexpr,
2677 ExprArg assertmessageexpr) {
Anders Carlssoned691562009-03-14 00:25:26 +00002678 Expr *AssertExpr = (Expr *)assertexpr.get();
2679 StringLiteral *AssertMessage =
2680 cast<StringLiteral>((Expr *)assertmessageexpr.get());
2681
Anders Carlsson8b842c52009-03-14 00:33:21 +00002682 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
2683 llvm::APSInt Value(32);
2684 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
2685 Diag(AssertLoc, diag::err_static_assert_expression_is_not_constant) <<
2686 AssertExpr->getSourceRange();
Chris Lattner5261d0c2009-03-28 19:18:32 +00002687 return DeclPtrTy();
Anders Carlsson8b842c52009-03-14 00:33:21 +00002688 }
Anders Carlssoned691562009-03-14 00:25:26 +00002689
Anders Carlsson8b842c52009-03-14 00:33:21 +00002690 if (Value == 0) {
2691 std::string str(AssertMessage->getStrData(),
2692 AssertMessage->getByteLength());
Anders Carlssonc45057a2009-03-15 18:44:04 +00002693 Diag(AssertLoc, diag::err_static_assert_failed)
2694 << str << AssertExpr->getSourceRange();
Anders Carlsson8b842c52009-03-14 00:33:21 +00002695 }
2696 }
2697
Anders Carlsson0f4942b2009-03-15 17:35:16 +00002698 assertexpr.release();
2699 assertmessageexpr.release();
Anders Carlssoned691562009-03-14 00:25:26 +00002700 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, AssertLoc,
2701 AssertExpr, AssertMessage);
Anders Carlssoned691562009-03-14 00:25:26 +00002702
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002703 CurContext->addDecl(Context, Decl);
Chris Lattner5261d0c2009-03-28 19:18:32 +00002704 return DeclPtrTy::make(Decl);
Anders Carlssoned691562009-03-14 00:25:26 +00002705}
Sebastian Redla8cecf62009-03-24 22:27:57 +00002706
Anders Carlssonb56d8b32009-05-11 22:55:49 +00002707bool Sema::ActOnFriendDecl(Scope *S, SourceLocation FriendLoc, DeclPtrTy Dcl) {
2708 if (!(S->getFlags() & Scope::ClassScope)) {
2709 Diag(FriendLoc, diag::err_friend_decl_outside_class);
2710 return true;
2711 }
2712
2713 return false;
2714}
2715
Chris Lattner5261d0c2009-03-28 19:18:32 +00002716void Sema::SetDeclDeleted(DeclPtrTy dcl, SourceLocation DelLoc) {
2717 Decl *Dcl = dcl.getAs<Decl>();
Sebastian Redla8cecf62009-03-24 22:27:57 +00002718 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
2719 if (!Fn) {
2720 Diag(DelLoc, diag::err_deleted_non_function);
2721 return;
2722 }
2723 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
2724 Diag(DelLoc, diag::err_deleted_decl_not_first);
2725 Diag(Prev->getLocation(), diag::note_previous_declaration);
2726 // If the declaration wasn't the first, we delete the function anyway for
2727 // recovery.
2728 }
2729 Fn->setDeleted();
2730}
Sebastian Redl3b1ef312009-04-27 21:33:24 +00002731
2732static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
2733 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end(); CI != E;
2734 ++CI) {
2735 Stmt *SubStmt = *CI;
2736 if (!SubStmt)
2737 continue;
2738 if (isa<ReturnStmt>(SubStmt))
2739 Self.Diag(SubStmt->getSourceRange().getBegin(),
2740 diag::err_return_in_constructor_handler);
2741 if (!isa<Expr>(SubStmt))
2742 SearchForReturnInStmt(Self, SubStmt);
2743 }
2744}
2745
2746void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
2747 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
2748 CXXCatchStmt *Handler = TryBlock->getHandler(I);
2749 SearchForReturnInStmt(*this, Handler);
2750 }
2751}
Anders Carlssone80e29c2009-05-14 01:09:04 +00002752
2753bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
2754 const CXXMethodDecl *Old) {
2755 QualType NewTy = New->getType()->getAsFunctionType()->getResultType();
2756 QualType OldTy = Old->getType()->getAsFunctionType()->getResultType();
2757
2758 QualType CNewTy = Context.getCanonicalType(NewTy);
2759 QualType COldTy = Context.getCanonicalType(OldTy);
2760
2761 if (CNewTy == COldTy &&
2762 CNewTy.getCVRQualifiers() == COldTy.getCVRQualifiers())
2763 return false;
2764
Anders Carlssonee7177b2009-05-14 19:52:19 +00002765 // Check if the return types are covariant
2766 QualType NewClassTy, OldClassTy;
2767
2768 /// Both types must be pointers or references to classes.
2769 if (PointerType *NewPT = dyn_cast<PointerType>(NewTy)) {
2770 if (PointerType *OldPT = dyn_cast<PointerType>(OldTy)) {
2771 NewClassTy = NewPT->getPointeeType();
2772 OldClassTy = OldPT->getPointeeType();
2773 }
2774 } else if (ReferenceType *NewRT = dyn_cast<ReferenceType>(NewTy)) {
2775 if (ReferenceType *OldRT = dyn_cast<ReferenceType>(OldTy)) {
2776 NewClassTy = NewRT->getPointeeType();
2777 OldClassTy = OldRT->getPointeeType();
2778 }
2779 }
2780
2781 // The return types aren't either both pointers or references to a class type.
2782 if (NewClassTy.isNull()) {
2783 Diag(New->getLocation(),
2784 diag::err_different_return_type_for_overriding_virtual_function)
2785 << New->getDeclName() << NewTy << OldTy;
2786 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2787
2788 return true;
2789 }
Anders Carlssone80e29c2009-05-14 01:09:04 +00002790
Anders Carlssonee7177b2009-05-14 19:52:19 +00002791 if (NewClassTy.getUnqualifiedType() != OldClassTy.getUnqualifiedType()) {
2792 // Check if the new class derives from the old class.
2793 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
2794 Diag(New->getLocation(),
2795 diag::err_covariant_return_not_derived)
2796 << New->getDeclName() << NewTy << OldTy;
2797 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2798 return true;
2799 }
2800
2801 // Check if we the conversion from derived to base is valid.
2802 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
2803 diag::err_covariant_return_inaccessible_base,
2804 diag::err_covariant_return_ambiguous_derived_to_base_conv,
2805 // FIXME: Should this point to the return type?
2806 New->getLocation(), SourceRange(), New->getDeclName())) {
2807 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2808 return true;
2809 }
2810 }
2811
2812 // The qualifiers of the return types must be the same.
2813 if (CNewTy.getCVRQualifiers() != COldTy.getCVRQualifiers()) {
2814 Diag(New->getLocation(),
2815 diag::err_covariant_return_type_different_qualifications)
Anders Carlssone80e29c2009-05-14 01:09:04 +00002816 << New->getDeclName() << NewTy << OldTy;
Anders Carlssonee7177b2009-05-14 19:52:19 +00002817 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2818 return true;
2819 };
2820
2821
2822 // The new class type must have the same or less qualifiers as the old type.
2823 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
2824 Diag(New->getLocation(),
2825 diag::err_covariant_return_type_class_type_more_qualified)
2826 << New->getDeclName() << NewTy << OldTy;
2827 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2828 return true;
2829 };
2830
2831 return false;
Anders Carlssone80e29c2009-05-14 01:09:04 +00002832}