blob: 1c98529fa895bc57cb6a2d43e2ed531f71e4a6bb [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"
Douglas Gregor05904022008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Parse/DeclSpec.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Chris Lattner97316c02008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000025#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner97316c02008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattnerb1856db2008-04-12 23:52:44 +000033namespace {
34 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
35 /// the default argument of a parameter to determine whether it
36 /// contains any ill-formed subexpressions. For example, this will
37 /// diagnose the use of local variables or parameters within the
38 /// default argument expression.
39 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000043
Chris Lattnerb1856db2008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000047
Chris Lattnerb1856db2008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000051 };
Chris Lattner97316c02008-04-10 02:22:51 +000052
Chris Lattnerb1856db2008-04-12 23:52:44 +000053 /// VisitExpr - Visit all of the children of this expression.
54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
55 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000056 for (Stmt::child_iterator I = Node->child_begin(),
57 E = Node->child_end(); I != E; ++I)
58 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000060 }
61
Chris Lattnerb1856db2008-04-12 23:52:44 +000062 /// VisitDeclRefExpr - Visit a reference to a declaration, to
63 /// determine whether this declaration can be used in the default
64 /// argument expression.
65 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000067 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
68 // C++ [dcl.fct.default]p9
69 // Default arguments are evaluated each time the function is
70 // called. The order of evaluation of function arguments is
71 // unspecified. Consequently, parameters of a function shall not
72 // be used in default argument expressions, even if they are not
73 // evaluated. Parameters of a function declared before a default
74 // argument expression are in scope and can hide namespace and
75 // class member names.
76 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000077 diag::err_param_default_argument_references_param)
Chris Lattnerb1753422008-11-23 21:45:46 +000078 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff72a6ebc2008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000083 if (VDecl->isBlockVarDecl())
84 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000085 diag::err_param_default_argument_references_local)
Chris Lattnerb1753422008-11-23 21:45:46 +000086 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +000087 }
Chris Lattner97316c02008-04-10 02:22:51 +000088
Douglas Gregor3c246952008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000091
Douglas Gregora5b022a2008-11-04 14:32:21 +000092 /// VisitCXXThisExpr - Visit a C++ "this" expression.
93 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
94 // C++ [dcl.fct.default]p8:
95 // The keyword this shall not be used in a default argument of a
96 // member function.
97 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000098 diag::err_param_default_argument_references_this)
99 << ThisE->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +0000100 }
Chris Lattner97316c02008-04-10 02:22:51 +0000101}
102
103/// ActOnParamDefaultArgument - Check whether the default argument
104/// provided for a function parameter is well-formed. If so, attach it
105/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000106void
107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
108 ExprTy *defarg) {
109 ParmVarDecl *Param = (ParmVarDecl *)param;
Ted Kremenek0c97e042009-02-07 01:47:29 +0000110 ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000111 QualType ParamType = Param->getType();
112
113 // Default arguments are only permitted in C++
114 if (!getLangOptions().CPlusPlus) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000115 Diag(EqualLoc, diag::err_param_default_argument)
116 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000117 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000118 return;
119 }
120
121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000127 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000128 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
129 EqualLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000130 Param->getDeclName(),
131 /*DirectInit=*/false);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000132 if (DefaultArgPtr != DefaultArg.get()) {
133 DefaultArg.take();
134 DefaultArg.reset(DefaultArgPtr);
135 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000136 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000137 return;
138 }
139
Chris Lattner97316c02008-04-10 02:22:51 +0000140 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000141 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000142 if (DefaultArgChecker.Visit(DefaultArg.get())) {
143 Param->setInvalidDecl();
Chris Lattner97316c02008-04-10 02:22:51 +0000144 return;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000145 }
Chris Lattner97316c02008-04-10 02:22:51 +0000146
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000147 // Okay: add the default argument to the parameter
148 Param->setDefaultArg(DefaultArg.take());
149}
150
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000151/// ActOnParamUnparsedDefaultArgument - We've seen a default
152/// argument for a function parameter, but we can't parse it yet
153/// because we're inside a class definition. Note that this default
154/// argument will be parsed later.
155void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param,
156 SourceLocation EqualLoc) {
157 ParmVarDecl *Param = (ParmVarDecl*)param;
158 if (Param)
159 Param->setUnparsedDefaultArg();
160}
161
Douglas Gregor605de8d2008-12-16 21:30:33 +0000162/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
163/// the default argument for the parameter param failed.
164void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
165 ((ParmVarDecl*)param)->setInvalidDecl();
166}
167
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000168/// CheckExtraCXXDefaultArguments - Check for any extra default
169/// arguments in the declarator, which is not a function declaration
170/// or definition and therefore is not permitted to have default
171/// arguments. This routine should be invoked for every declarator
172/// that is not a function declaration or definition.
173void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
174 // C++ [dcl.fct.default]p3
175 // A default argument expression shall be specified only in the
176 // parameter-declaration-clause of a function declaration or in a
177 // template-parameter (14.1). It shall not be specified for a
178 // parameter pack. If it is specified in a
179 // parameter-declaration-clause, it shall not occur within a
180 // declarator or abstract-declarator of a parameter-declaration.
181 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
182 DeclaratorChunk &chunk = D.getTypeObject(i);
183 if (chunk.Kind == DeclaratorChunk::Function) {
184 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
185 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000186 if (Param->hasUnparsedDefaultArg()) {
187 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000188 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
189 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
190 delete Toks;
191 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000192 } else if (Param->getDefaultArg()) {
193 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
194 << Param->getDefaultArg()->getSourceRange();
195 Param->setDefaultArg(0);
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000196 }
197 }
198 }
199 }
200}
201
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000202// MergeCXXFunctionDecl - Merge two declarations of the same C++
203// function, once we already know that they have the same
Douglas Gregor083c23e2009-02-16 17:45:42 +0000204// type. Subroutine of MergeFunctionDecl. Returns true if there was an
205// error, false otherwise.
206bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
207 bool Invalid = false;
208
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000209 // C++ [dcl.fct.default]p4:
210 //
211 // For non-template functions, default arguments can be added in
212 // later declarations of a function in the same
213 // scope. Declarations in different scopes have completely
214 // distinct sets of default arguments. That is, declarations in
215 // inner scopes do not acquire default arguments from
216 // declarations in outer scopes, and vice versa. In a given
217 // function declaration, all parameters subsequent to a
218 // parameter with a default argument shall have default
219 // arguments supplied in this or previous declarations. A
220 // default argument shall not be redefined by a later
221 // declaration (not even to the same value).
222 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
223 ParmVarDecl *OldParam = Old->getParamDecl(p);
224 ParmVarDecl *NewParam = New->getParamDecl(p);
225
226 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
227 Diag(NewParam->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000228 diag::err_param_default_argument_redefinition)
229 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000230 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregor083c23e2009-02-16 17:45:42 +0000231 Invalid = true;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000232 } else if (OldParam->getDefaultArg()) {
233 // Merge the old default argument into the new parameter
234 NewParam->setDefaultArg(OldParam->getDefaultArg());
235 }
236 }
237
Douglas Gregor083c23e2009-02-16 17:45:42 +0000238 return Invalid;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000239}
240
241/// CheckCXXDefaultArguments - Verify that the default arguments for a
242/// function declaration are well-formed according to C++
243/// [dcl.fct.default].
244void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
245 unsigned NumParams = FD->getNumParams();
246 unsigned p;
247
248 // Find first parameter with a default argument
249 for (p = 0; p < NumParams; ++p) {
250 ParmVarDecl *Param = FD->getParamDecl(p);
251 if (Param->getDefaultArg())
252 break;
253 }
254
255 // C++ [dcl.fct.default]p4:
256 // In a given function declaration, all parameters
257 // subsequent to a parameter with a default argument shall
258 // have default arguments supplied in this or previous
259 // declarations. A default argument shall not be redefined
260 // by a later declaration (not even to the same value).
261 unsigned LastMissingDefaultArg = 0;
262 for(; p < NumParams; ++p) {
263 ParmVarDecl *Param = FD->getParamDecl(p);
264 if (!Param->getDefaultArg()) {
Douglas Gregor605de8d2008-12-16 21:30:33 +0000265 if (Param->isInvalidDecl())
266 /* We already complained about this parameter. */;
267 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000268 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000269 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000270 << Param->getIdentifier();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000271 else
272 Diag(Param->getLocation(),
273 diag::err_param_default_argument_missing);
274
275 LastMissingDefaultArg = p;
276 }
277 }
278
279 if (LastMissingDefaultArg > 0) {
280 // Some default arguments were missing. Clear out all of the
281 // default arguments up to (and including) the last missing
282 // default argument, so that we leave the function parameters
283 // in a semantically valid state.
284 for (p = 0; p <= LastMissingDefaultArg; ++p) {
285 ParmVarDecl *Param = FD->getParamDecl(p);
286 if (Param->getDefaultArg()) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000287 if (!Param->hasUnparsedDefaultArg())
288 Param->getDefaultArg()->Destroy(Context);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000289 Param->setDefaultArg(0);
290 }
291 }
292 }
293}
Douglas Gregorec93f442008-04-13 21:30:24 +0000294
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000295/// isCurrentClassName - Determine whether the identifier II is the
296/// name of the class type currently being defined. In the case of
297/// nested classes, this will only return true if II is the name of
298/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000299bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
300 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000301 CXXRecordDecl *CurDecl;
302 if (SS) {
303 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
304 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
305 } else
306 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
307
308 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000309 return &II == CurDecl->getIdentifier();
310 else
311 return false;
312}
313
Douglas Gregorec93f442008-04-13 21:30:24 +0000314/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
315/// one entry in the base class list of a class specifier, for
316/// example:
317/// class foo : public bar, virtual private baz {
318/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000319Sema::BaseResult
320Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
321 bool Virtual, AccessSpecifier Access,
322 TypeTy *basetype, SourceLocation BaseLoc) {
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000323 CXXRecordDecl *Decl = (CXXRecordDecl*)classdecl;
Douglas Gregora60c62e2009-02-09 15:09:02 +0000324 QualType BaseType = QualType::getFromOpaquePtr(basetype);
Douglas Gregorec93f442008-04-13 21:30:24 +0000325
326 // Base specifiers must be record types.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000327 if (!BaseType->isRecordType())
328 return Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000329
330 // C++ [class.union]p1:
331 // A union shall not be used as a base class.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000332 if (BaseType->isUnionType())
333 return Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000334
335 // C++ [class.union]p1:
336 // A union shall not have base classes.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000337 if (Decl->isUnion())
338 return Diag(Decl->getLocation(), diag::err_base_clause_on_union)
339 << SpecifierRange;
Douglas Gregorec93f442008-04-13 21:30:24 +0000340
341 // C++ [class.derived]p2:
342 // The class-name in a base-specifier shall not be an incompletely
343 // defined class.
Douglas Gregor46fe06e2009-01-19 19:26:10 +0000344 if (DiagnoseIncompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
345 SpecifierRange))
346 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000347
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000348 // If the base class is polymorphic, the new one is, too.
349 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
350 assert(BaseDecl && "Record type has no declaration");
351 BaseDecl = BaseDecl->getDefinition(Context);
352 assert(BaseDecl && "Base type is not incomplete, but has no definition");
Chris Lattner8ba580c2008-11-19 05:08:23 +0000353 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000354 Decl->setPolymorphic(true);
355
356 // C++ [dcl.init.aggr]p1:
357 // An aggregate is [...] a class with [...] no base classes [...].
358 Decl->setAggregate(false);
359 Decl->setPOD(false);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000360
Douglas Gregorabed2172008-10-22 17:49:05 +0000361 // Create the base specifier.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000362 return new CXXBaseSpecifier(SpecifierRange, Virtual,
363 BaseType->isClassType(), Access, BaseType);
Douglas Gregorabed2172008-10-22 17:49:05 +0000364}
Douglas Gregorec93f442008-04-13 21:30:24 +0000365
Douglas Gregorabed2172008-10-22 17:49:05 +0000366/// ActOnBaseSpecifiers - Attach the given base specifiers to the
367/// class, after checking whether there are any duplicate base
368/// classes.
369void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
370 unsigned NumBases) {
371 if (NumBases == 0)
372 return;
373
374 // Used to keep track of which base types we have already seen, so
375 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000376 // that the key is always the unqualified canonical type of the base
377 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000378 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
379
380 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000381 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
382 unsigned NumGoodBases = 0;
383 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000384 QualType NewBaseType
Douglas Gregor4fd85902008-10-23 18:13:27 +0000385 = Context.getCanonicalType(BaseSpecs[idx]->getType());
386 NewBaseType = NewBaseType.getUnqualifiedType();
387
Douglas Gregorabed2172008-10-22 17:49:05 +0000388 if (KnownBaseTypes[NewBaseType]) {
389 // C++ [class.mi]p3:
390 // A class shall not be specified as a direct base class of a
391 // derived class more than once.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000392 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000393 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000394 << KnownBaseTypes[NewBaseType]->getType()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000395 << BaseSpecs[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000396
397 // Delete the duplicate base class specifier; we're going to
398 // overwrite its pointer later.
399 delete BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000400 } else {
401 // Okay, add this new base class.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000402 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
403 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000404 }
405 }
406
407 // Attach the remaining base class specifiers to the derived class.
408 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000409 Decl->setBases(BaseSpecs, NumGoodBases);
410
411 // Delete the remaining (good) base class specifiers, since their
412 // data has been copied into the CXXRecordDecl.
413 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
414 delete BaseSpecs[idx];
Douglas Gregorec93f442008-04-13 21:30:24 +0000415}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000416
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000417//===----------------------------------------------------------------------===//
418// C++ class member Handling
419//===----------------------------------------------------------------------===//
420
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000421/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
422/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
423/// bitfield width if there is one and 'InitExpr' specifies the initializer if
424/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
425/// declarators on it.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000426Sema::DeclTy *
427Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
428 ExprTy *BW, ExprTy *InitExpr,
429 DeclTy *LastInGroup) {
430 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000431 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000432 Expr *BitWidth = static_cast<Expr*>(BW);
433 Expr *Init = static_cast<Expr*>(InitExpr);
434 SourceLocation Loc = D.getIdentifierLoc();
435
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000436 bool isFunc = D.isFunctionDeclarator();
437
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000438 // C++ 9.2p6: A member shall not be declared to have automatic storage
439 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000440 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
441 // data members and cannot be applied to names declared const or static,
442 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000443 switch (DS.getStorageClassSpec()) {
444 case DeclSpec::SCS_unspecified:
445 case DeclSpec::SCS_typedef:
446 case DeclSpec::SCS_static:
447 // FALL THROUGH.
448 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000449 case DeclSpec::SCS_mutable:
450 if (isFunc) {
451 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000452 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000453 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000454 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
455
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000456 // FIXME: It would be nicer if the keyword was ignored only for this
457 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000458 D.getMutableDeclSpec().ClearStorageClassSpecs();
459 } else {
460 QualType T = GetTypeForDeclarator(D, S);
461 diag::kind err = static_cast<diag::kind>(0);
462 if (T->isReferenceType())
463 err = diag::err_mutable_reference;
464 else if (T.isConstQualified())
465 err = diag::err_mutable_const;
466 if (err != 0) {
467 if (DS.getStorageClassSpecLoc().isValid())
468 Diag(DS.getStorageClassSpecLoc(), err);
469 else
470 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000471 // FIXME: It would be nicer if the keyword was ignored only for this
472 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000473 D.getMutableDeclSpec().ClearStorageClassSpecs();
474 }
475 }
476 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000477 default:
478 if (DS.getStorageClassSpecLoc().isValid())
479 Diag(DS.getStorageClassSpecLoc(),
480 diag::err_storageclass_invalid_for_member);
481 else
482 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
483 D.getMutableDeclSpec().ClearStorageClassSpecs();
484 }
485
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000486 if (!isFunc &&
Douglas Gregora60c62e2009-02-09 15:09:02 +0000487 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000488 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000489 // Check also for this case:
490 //
491 // typedef int f();
492 // f a;
493 //
Douglas Gregora60c62e2009-02-09 15:09:02 +0000494 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
495 isFunc = TDType->isFunctionType();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000496 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000497
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000498 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
499 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000500 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000501
502 Decl *Member;
503 bool InvalidDecl = false;
504
505 if (isInstField)
Douglas Gregor8acb7272008-12-11 16:49:14 +0000506 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext),
507 Loc, D, BitWidth));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000508 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000509 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000510
511 if (!Member) return LastInGroup;
512
Douglas Gregor6704b312008-11-17 22:58:34 +0000513 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000514
515 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
516 // specific methods. Use a wrapper class that can be used with all C++ class
517 // member decls.
518 CXXClassMemberWrapper(Member).setAccess(AS);
519
Douglas Gregor15e04622008-11-05 16:20:31 +0000520 // C++ [dcl.init.aggr]p1:
521 // An aggregate is an array or a class (clause 9) with [...] no
522 // private or protected non-static data members (clause 11).
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000523 // A POD must be an aggregate.
524 if (isInstField && (AS == AS_private || AS == AS_protected)) {
525 CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext);
526 Record->setAggregate(false);
527 Record->setPOD(false);
528 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000529
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000530 if (DS.isVirtualSpecified()) {
531 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
532 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
533 InvalidDecl = true;
534 } else {
Sebastian Redl83faa292009-01-09 19:57:06 +0000535 cast<CXXMethodDecl>(Member)->setVirtual();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000536 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
537 CurClass->setAggregate(false);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000538 CurClass->setPOD(false);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000539 CurClass->setPolymorphic(true);
540 }
541 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000542
Sebastian Redl83faa292009-01-09 19:57:06 +0000543 // FIXME: The above definition of virtual is not sufficient. A function is
544 // also virtual if it overrides an already virtual function. This is important
545 // to do here because it decides the validity of a pure specifier.
546
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000547 if (BitWidth) {
548 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
549 // constant-expression be a value equal to zero.
550 // FIXME: Check this.
551
552 if (D.isFunctionDeclarator()) {
553 // FIXME: Emit diagnostic about only constructors taking base initializers
554 // or something similar, when constructor support is in place.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000555 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000556 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000557 InvalidDecl = true;
558
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000559 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000560 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000561 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000562 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000563 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000564 InvalidDecl = true;
565 }
566
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000567 } else if (isa<FunctionDecl>(Member)) {
568 // A function typedef ("typedef int f(); f a;").
569 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000570 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000571 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000572 InvalidDecl = true;
573
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000574 } else if (isa<TypedefDecl>(Member)) {
575 // "cannot declare 'A' to be a bit-field type"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000576 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000577 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000578 InvalidDecl = true;
579
580 } else {
581 assert(isa<CXXClassVarDecl>(Member) &&
582 "Didn't we cover all member kinds?");
583 // C++ 9.6p3: A bit-field shall not be a static member.
584 // "static member 'A' cannot be a bit-field"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000585 Diag(Loc, diag::err_static_not_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000586 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000587 InvalidDecl = true;
588 }
589 }
590
591 if (Init) {
592 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
593 // if it declares a static member of const integral or const enumeration
594 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000595 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
596 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000597 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000598 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000599 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
600 CVD->getType()->isIntegralType()) {
601 // constant-initializer
602 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000603 InvalidDecl = true;
604
605 } else {
606 // not const integral.
Chris Lattner77d52da2008-11-20 06:06:08 +0000607 Diag(Loc, diag::err_member_initialization)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000608 << Name << Init->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000609 InvalidDecl = true;
610 }
611
612 } else {
Sebastian Redl83faa292009-01-09 19:57:06 +0000613 // not static member. perhaps virtual function?
614 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
Sebastian Redl54e4be92009-01-09 22:29:03 +0000615 // With declarators parsed the way they are, the parser cannot
616 // distinguish between a normal initializer and a pure-specifier.
617 // Thus this grotesque test.
Sebastian Redl83faa292009-01-09 19:57:06 +0000618 IntegerLiteral *IL;
619 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
620 Context.getCanonicalType(IL->getType()) == Context.IntTy) {
621 if (MD->isVirtual())
622 MD->setPure();
623 else {
624 Diag(Loc, diag::err_non_virtual_pure)
625 << Name << Init->getSourceRange();
626 InvalidDecl = true;
627 }
628 } else {
629 Diag(Loc, diag::err_member_function_initialization)
630 << Name << Init->getSourceRange();
631 InvalidDecl = true;
632 }
633 } else {
634 Diag(Loc, diag::err_member_initialization)
635 << Name << Init->getSourceRange();
636 InvalidDecl = true;
637 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000638 }
639 }
640
641 if (InvalidDecl)
642 Member->setInvalidDecl();
643
644 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000645 FieldCollector->Add(cast<FieldDecl>(Member));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000646 return LastInGroup;
647 }
648 return Member;
649}
650
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000651/// ActOnMemInitializer - Handle a C++ member initializer.
652Sema::MemInitResult
653Sema::ActOnMemInitializer(DeclTy *ConstructorD,
654 Scope *S,
655 IdentifierInfo *MemberOrBase,
656 SourceLocation IdLoc,
657 SourceLocation LParenLoc,
658 ExprTy **Args, unsigned NumArgs,
659 SourceLocation *CommaLocs,
660 SourceLocation RParenLoc) {
661 CXXConstructorDecl *Constructor
662 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
663 if (!Constructor) {
664 // The user wrote a constructor initializer on a function that is
665 // not a C++ constructor. Ignore the error for now, because we may
666 // have more member initializers coming; we'll diagnose it just
667 // once in ActOnMemInitializers.
668 return true;
669 }
670
671 CXXRecordDecl *ClassDecl = Constructor->getParent();
672
673 // C++ [class.base.init]p2:
674 // Names in a mem-initializer-id are looked up in the scope of the
675 // constructor’s class and, if not found in that scope, are looked
676 // up in the scope containing the constructor’s
677 // definition. [Note: if the constructor’s class contains a member
678 // with the same name as a direct or virtual base class of the
679 // class, a mem-initializer-id naming the member or base class and
680 // composed of a single identifier refers to the class member. A
681 // mem-initializer-id for the hidden base class may be specified
682 // using a qualified name. ]
683 // Look for a member, first.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000684 FieldDecl *Member = 0;
Steve Naroffab63fd62009-01-08 17:28:14 +0000685 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000686 if (Result.first != Result.second)
687 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000688
689 // FIXME: Handle members of an anonymous union.
690
691 if (Member) {
692 // FIXME: Perform direct initialization of the member.
693 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
694 }
695
696 // It didn't name a member, so see if it names a class.
Douglas Gregor1075a162009-02-04 17:00:24 +0000697 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000698 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000699 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
700 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000701
Douglas Gregora60c62e2009-02-09 15:09:02 +0000702 QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000703 if (!BaseType->isRecordType())
Chris Lattner65cae292008-11-19 08:23:25 +0000704 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattnerb1753422008-11-23 21:45:46 +0000705 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000706
707 // C++ [class.base.init]p2:
708 // [...] Unless the mem-initializer-id names a nonstatic data
709 // member of the constructor’s class or a direct or virtual base
710 // of that class, the mem-initializer is ill-formed. A
711 // mem-initializer-list can initialize a base class using any
712 // name that denotes that base class type.
713
714 // First, check for a direct base class.
715 const CXXBaseSpecifier *DirectBaseSpec = 0;
716 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
717 Base != ClassDecl->bases_end(); ++Base) {
718 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
719 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
720 // We found a direct base of this type. That's what we're
721 // initializing.
722 DirectBaseSpec = &*Base;
723 break;
724 }
725 }
726
727 // Check for a virtual base class.
728 // FIXME: We might be able to short-circuit this if we know in
729 // advance that there are no virtual bases.
730 const CXXBaseSpecifier *VirtualBaseSpec = 0;
731 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
732 // We haven't found a base yet; search the class hierarchy for a
733 // virtual base class.
734 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
735 /*DetectVirtual=*/false);
736 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
737 for (BasePaths::paths_iterator Path = Paths.begin();
738 Path != Paths.end(); ++Path) {
739 if (Path->back().Base->isVirtual()) {
740 VirtualBaseSpec = Path->back().Base;
741 break;
742 }
743 }
744 }
745 }
746
747 // C++ [base.class.init]p2:
748 // If a mem-initializer-id is ambiguous because it designates both
749 // a direct non-virtual base class and an inherited virtual base
750 // class, the mem-initializer is ill-formed.
751 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner65cae292008-11-19 08:23:25 +0000752 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
753 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000754
755 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
756}
757
758
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000759void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
760 DeclTy *TagDecl,
761 SourceLocation LBrac,
762 SourceLocation RBrac) {
Douglas Gregor279272e2009-02-04 19:02:06 +0000763 AdjustDeclIfTemplate(TagDecl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000764 ActOnFields(S, RLoc, TagDecl,
765 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000766 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000767 AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000768}
769
Douglas Gregore640ab62008-11-03 17:51:48 +0000770/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
771/// special functions, such as the default constructor, copy
772/// constructor, or destructor, to the given C++ class (C++
773/// [special]p1). This routine can only be executed just before the
774/// definition of the class is complete.
775void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000776 QualType ClassType = Context.getTypeDeclType(ClassDecl);
777 ClassType = Context.getCanonicalType(ClassType);
778
Douglas Gregore640ab62008-11-03 17:51:48 +0000779 if (!ClassDecl->hasUserDeclaredConstructor()) {
780 // C++ [class.ctor]p5:
781 // A default constructor for a class X is a constructor of class X
782 // that can be called without an argument. If there is no
783 // user-declared constructor for class X, a default constructor is
784 // implicitly declared. An implicitly-declared default constructor
785 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000786 DeclarationName Name
787 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000788 CXXConstructorDecl *DefaultCon =
789 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000790 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000791 Context.getFunctionType(Context.VoidTy,
792 0, 0, false, 0),
793 /*isExplicit=*/false,
794 /*isInline=*/true,
795 /*isImplicitlyDeclared=*/true);
796 DefaultCon->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000797 DefaultCon->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000798 ClassDecl->addDecl(DefaultCon);
Douglas Gregorb9213832008-12-15 21:24:18 +0000799
800 // Notify the class that we've added a constructor.
801 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +0000802 }
803
804 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
805 // C++ [class.copy]p4:
806 // If the class definition does not explicitly declare a copy
807 // constructor, one is declared implicitly.
808
809 // C++ [class.copy]p5:
810 // The implicitly-declared copy constructor for a class X will
811 // have the form
812 //
813 // X::X(const X&)
814 //
815 // if
816 bool HasConstCopyConstructor = true;
817
818 // -- each direct or virtual base class B of X has a copy
819 // constructor whose first parameter is of type const B& or
820 // const volatile B&, and
821 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
822 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
823 const CXXRecordDecl *BaseClassDecl
824 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
825 HasConstCopyConstructor
826 = BaseClassDecl->hasConstCopyConstructor(Context);
827 }
828
829 // -- for all the nonstatic data members of X that are of a
830 // class type M (or array thereof), each such class type
831 // has a copy constructor whose first parameter is of type
832 // const M& or const volatile M&.
833 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
834 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
835 QualType FieldType = (*Field)->getType();
836 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
837 FieldType = Array->getElementType();
838 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
839 const CXXRecordDecl *FieldClassDecl
840 = cast<CXXRecordDecl>(FieldClassType->getDecl());
841 HasConstCopyConstructor
842 = FieldClassDecl->hasConstCopyConstructor(Context);
843 }
844 }
845
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000846 // Otherwise, the implicitly declared copy constructor will have
847 // the form
Douglas Gregore640ab62008-11-03 17:51:48 +0000848 //
849 // X::X(X&)
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000850 QualType ArgType = ClassType;
Douglas Gregore640ab62008-11-03 17:51:48 +0000851 if (HasConstCopyConstructor)
852 ArgType = ArgType.withConst();
853 ArgType = Context.getReferenceType(ArgType);
854
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000855 // An implicitly-declared copy constructor is an inline public
856 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000857 DeclarationName Name
858 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000859 CXXConstructorDecl *CopyConstructor
860 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000861 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000862 Context.getFunctionType(Context.VoidTy,
863 &ArgType, 1,
864 false, 0),
865 /*isExplicit=*/false,
866 /*isInline=*/true,
867 /*isImplicitlyDeclared=*/true);
868 CopyConstructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000869 CopyConstructor->setImplicit();
Douglas Gregore640ab62008-11-03 17:51:48 +0000870
871 // Add the parameter to the constructor.
872 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
873 ClassDecl->getLocation(),
874 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000875 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000876 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregore640ab62008-11-03 17:51:48 +0000877
Douglas Gregorb9213832008-12-15 21:24:18 +0000878 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000879 ClassDecl->addDecl(CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +0000880 }
881
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000882 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
883 // Note: The following rules are largely analoguous to the copy
884 // constructor rules. Note that virtual bases are not taken into account
885 // for determining the argument type of the operator. Note also that
886 // operators taking an object instead of a reference are allowed.
887 //
888 // C++ [class.copy]p10:
889 // If the class definition does not explicitly declare a copy
890 // assignment operator, one is declared implicitly.
891 // The implicitly-defined copy assignment operator for a class X
892 // will have the form
893 //
894 // X& X::operator=(const X&)
895 //
896 // if
897 bool HasConstCopyAssignment = true;
898
899 // -- each direct base class B of X has a copy assignment operator
900 // whose parameter is of type const B&, const volatile B& or B,
901 // and
902 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
903 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
904 const CXXRecordDecl *BaseClassDecl
905 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
906 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
907 }
908
909 // -- for all the nonstatic data members of X that are of a class
910 // type M (or array thereof), each such class type has a copy
911 // assignment operator whose parameter is of type const M&,
912 // const volatile M& or M.
913 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
914 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
915 QualType FieldType = (*Field)->getType();
916 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
917 FieldType = Array->getElementType();
918 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
919 const CXXRecordDecl *FieldClassDecl
920 = cast<CXXRecordDecl>(FieldClassType->getDecl());
921 HasConstCopyAssignment
922 = FieldClassDecl->hasConstCopyAssignment(Context);
923 }
924 }
925
926 // Otherwise, the implicitly declared copy assignment operator will
927 // have the form
928 //
929 // X& X::operator=(X&)
930 QualType ArgType = ClassType;
931 QualType RetType = Context.getReferenceType(ArgType);
932 if (HasConstCopyAssignment)
933 ArgType = ArgType.withConst();
934 ArgType = Context.getReferenceType(ArgType);
935
936 // An implicitly-declared copy assignment operator is an inline public
937 // member of its class.
938 DeclarationName Name =
939 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
940 CXXMethodDecl *CopyAssignment =
941 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
942 Context.getFunctionType(RetType, &ArgType, 1,
943 false, 0),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000944 /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000945 CopyAssignment->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000946 CopyAssignment->setImplicit();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000947
948 // Add the parameter to the operator.
949 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
950 ClassDecl->getLocation(),
951 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000952 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000953 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000954
955 // Don't call addedAssignmentOperator. There is no way to distinguish an
956 // implicit from an explicit assignment operator.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000957 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000958 }
959
Douglas Gregorb9213832008-12-15 21:24:18 +0000960 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000961 // C++ [class.dtor]p2:
962 // If a class has no user-declared destructor, a destructor is
963 // declared implicitly. An implicitly-declared destructor is an
964 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000965 DeclarationName Name
966 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000967 CXXDestructorDecl *Destructor
968 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000969 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000970 Context.getFunctionType(Context.VoidTy,
971 0, 0, false, 0),
972 /*isInline=*/true,
973 /*isImplicitlyDeclared=*/true);
974 Destructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000975 Destructor->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000976 ClassDecl->addDecl(Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000977 }
Douglas Gregore640ab62008-11-03 17:51:48 +0000978}
979
Douglas Gregor605de8d2008-12-16 21:30:33 +0000980/// ActOnStartDelayedCXXMethodDeclaration - We have completed
981/// parsing a top-level (non-nested) C++ class, and we are now
982/// parsing those parts of the given Method declaration that could
983/// not be parsed earlier (C++ [class.mem]p2), such as default
984/// arguments. This action should enter the scope of the given
985/// Method declaration as if we had just parsed the qualified method
986/// name. However, it should not bring the parameters into scope;
987/// that will be performed by ActOnDelayedCXXMethodParameter.
988void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
989 CXXScopeSpec SS;
990 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
991 ActOnCXXEnterDeclaratorScope(S, SS);
992}
993
994/// ActOnDelayedCXXMethodParameter - We've already started a delayed
995/// C++ method declaration. We're (re-)introducing the given
996/// function parameter into scope for use in parsing later parts of
997/// the method declaration. For example, we could see an
998/// ActOnParamDefaultArgument event for this parameter.
999void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1000 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001001
1002 // If this parameter has an unparsed default argument, clear it out
1003 // to make way for the parsed default argument.
1004 if (Param->hasUnparsedDefaultArg())
1005 Param->setDefaultArg(0);
1006
Douglas Gregor605de8d2008-12-16 21:30:33 +00001007 S->AddDecl(Param);
1008 if (Param->getDeclName())
1009 IdResolver.AddDecl(Param);
1010}
1011
1012/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1013/// processing the delayed method declaration for Method. The method
1014/// declaration is now considered finished. There may be a separate
1015/// ActOnStartOfFunctionDef action later (not necessarily
1016/// immediately!) for this method, if it was also defined inside the
1017/// class body.
1018void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1019 FunctionDecl *Method = (FunctionDecl*)MethodD;
1020 CXXScopeSpec SS;
1021 SS.setScopeRep(Method->getDeclContext());
1022 ActOnCXXExitDeclaratorScope(S, SS);
1023
1024 // Now that we have our default arguments, check the constructor
1025 // again. It could produce additional diagnostics or affect whether
1026 // the class has implicitly-declared destructors, among other
1027 // things.
1028 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1029 if (CheckConstructor(Constructor))
1030 Constructor->setInvalidDecl();
1031 }
1032
1033 // Check the default arguments, which we may have added.
1034 if (!Method->isInvalidDecl())
1035 CheckCXXDefaultArguments(Method);
1036}
1037
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001038/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +00001039/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001040/// R. If there are any errors in the declarator, this routine will
1041/// emit diagnostics and return true. Otherwise, it will return
1042/// false. Either way, the type @p R will be updated to reflect a
1043/// well-formed type for the constructor.
1044bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1045 FunctionDecl::StorageClass& SC) {
1046 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1047 bool isInvalid = false;
1048
1049 // C++ [class.ctor]p3:
1050 // A constructor shall not be virtual (10.3) or static (9.4). A
1051 // constructor can be invoked for a const, volatile or const
1052 // volatile object. A constructor shall not be declared const,
1053 // volatile, or const volatile (9.3.2).
1054 if (isVirtual) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001055 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1056 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1057 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001058 isInvalid = true;
1059 }
1060 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001061 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1062 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1063 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001064 isInvalid = true;
1065 SC = FunctionDecl::None;
1066 }
1067 if (D.getDeclSpec().hasTypeSpecifier()) {
1068 // Constructors don't have return types, but the parser will
1069 // happily parse something like:
1070 //
1071 // class X {
1072 // float X(float);
1073 // };
1074 //
1075 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001076 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1077 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1078 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001079 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00001080 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001081 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1082 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001083 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1084 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001085 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001086 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1087 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001088 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001089 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1090 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001091 }
1092
1093 // Rebuild the function type "R" without any type qualifiers (in
1094 // case any of the errors above fired) and with "void" as the
1095 // return type, since constructors don't have return types. We
1096 // *always* have to do this, because GetTypeForDeclarator will
1097 // put in a result type of "int" when none was specified.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001098 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001099 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1100 Proto->getNumArgs(),
1101 Proto->isVariadic(),
1102 0);
1103
1104 return isInvalid;
1105}
1106
Douglas Gregor605de8d2008-12-16 21:30:33 +00001107/// CheckConstructor - Checks a fully-formed constructor for
1108/// well-formedness, issuing any diagnostics required. Returns true if
1109/// the constructor declarator is invalid.
1110bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1111 if (Constructor->isInvalidDecl())
1112 return true;
1113
1114 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1115 bool Invalid = false;
1116
1117 // C++ [class.copy]p3:
1118 // A declaration of a constructor for a class X is ill-formed if
1119 // its first parameter is of type (optionally cv-qualified) X and
1120 // either there are no other parameters or else all other
1121 // parameters have default arguments.
1122 if ((Constructor->getNumParams() == 1) ||
1123 (Constructor->getNumParams() > 1 &&
1124 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1125 QualType ParamType = Constructor->getParamDecl(0)->getType();
1126 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1127 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1128 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1129 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1130 Invalid = true;
1131 }
1132 }
1133
1134 // Notify the class that we've added a constructor.
1135 ClassDecl->addedConstructor(Context, Constructor);
1136
1137 return Invalid;
1138}
1139
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001140/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1141/// the well-formednes of the destructor declarator @p D with type @p
1142/// R. If there are any errors in the declarator, this routine will
1143/// emit diagnostics and return true. Otherwise, it will return
1144/// false. Either way, the type @p R will be updated to reflect a
1145/// well-formed type for the destructor.
1146bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1147 FunctionDecl::StorageClass& SC) {
1148 bool isInvalid = false;
1149
1150 // C++ [class.dtor]p1:
1151 // [...] A typedef-name that names a class is a class-name
1152 // (7.1.3); however, a typedef-name that names a class shall not
1153 // be used as the identifier in the declarator for a destructor
1154 // declaration.
Douglas Gregora60c62e2009-02-09 15:09:02 +00001155 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1156 if (DeclaratorType->getAsTypedefType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001157 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregora60c62e2009-02-09 15:09:02 +00001158 << DeclaratorType;
Douglas Gregorbd19fdb2008-11-10 14:41:22 +00001159 isInvalid = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001160 }
1161
1162 // C++ [class.dtor]p2:
1163 // A destructor is used to destroy objects of its class type. A
1164 // destructor takes no parameters, and no return type can be
1165 // specified for it (not even void). The address of a destructor
1166 // shall not be taken. A destructor shall not be static. A
1167 // destructor can be invoked for a const, volatile or const
1168 // volatile object. A destructor shall not be declared const,
1169 // volatile or const volatile (9.3.2).
1170 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001171 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1172 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1173 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001174 isInvalid = true;
1175 SC = FunctionDecl::None;
1176 }
1177 if (D.getDeclSpec().hasTypeSpecifier()) {
1178 // Destructors don't have return types, but the parser will
1179 // happily parse something like:
1180 //
1181 // class X {
1182 // float ~X();
1183 // };
1184 //
1185 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001186 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1187 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1188 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001189 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00001190 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001191 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1192 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001193 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1194 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001195 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001196 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1197 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001198 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001199 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1200 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001201 }
1202
1203 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001204 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001205 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1206
1207 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001208 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001209 }
1210
1211 // Make sure the destructor isn't variadic.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001212 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001213 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1214
1215 // Rebuild the function type "R" without any type qualifiers or
1216 // parameters (in case any of the errors above fired) and with
1217 // "void" as the return type, since destructors don't have return
1218 // types. We *always* have to do this, because GetTypeForDeclarator
1219 // will put in a result type of "int" when none was specified.
1220 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1221
1222 return isInvalid;
1223}
1224
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001225/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1226/// well-formednes of the conversion function declarator @p D with
1227/// type @p R. If there are any errors in the declarator, this routine
1228/// will emit diagnostics and return true. Otherwise, it will return
1229/// false. Either way, the type @p R will be updated to reflect a
1230/// well-formed type for the conversion operator.
1231bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1232 FunctionDecl::StorageClass& SC) {
1233 bool isInvalid = false;
1234
1235 // C++ [class.conv.fct]p1:
1236 // Neither parameter types nor return type can be specified. The
1237 // type of a conversion function (8.3.5) is “function taking no
1238 // parameter returning conversion-type-id.”
1239 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001240 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1241 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1242 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001243 isInvalid = true;
1244 SC = FunctionDecl::None;
1245 }
1246 if (D.getDeclSpec().hasTypeSpecifier()) {
1247 // Conversion functions don't have return types, but the parser will
1248 // happily parse something like:
1249 //
1250 // class X {
1251 // float operator bool();
1252 // };
1253 //
1254 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001255 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1256 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1257 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001258 }
1259
1260 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001261 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001262 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1263
1264 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001265 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001266 }
1267
1268 // Make sure the conversion function isn't variadic.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001269 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001270 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1271
1272 // C++ [class.conv.fct]p4:
1273 // The conversion-type-id shall not represent a function type nor
1274 // an array type.
1275 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1276 if (ConvType->isArrayType()) {
1277 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1278 ConvType = Context.getPointerType(ConvType);
1279 } else if (ConvType->isFunctionType()) {
1280 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1281 ConvType = Context.getPointerType(ConvType);
1282 }
1283
1284 // Rebuild the function type "R" without any parameters (in case any
1285 // of the errors above fired) and with the conversion type as the
1286 // return type.
1287 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001288 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001289
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001290 // C++0x explicit conversion operators.
1291 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1292 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1293 diag::warn_explicit_conversion_functions)
1294 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1295
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001296 return isInvalid;
1297}
1298
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001299/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1300/// the declaration of the given C++ conversion function. This routine
1301/// is responsible for recording the conversion function in the C++
1302/// class, if possible.
1303Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1304 assert(Conversion && "Expected to receive a conversion function declaration");
1305
Douglas Gregor98341042008-12-12 08:25:50 +00001306 // Set the lexical context of this conversion function
1307 Conversion->setLexicalDeclContext(CurContext);
1308
1309 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001310
1311 // Make sure we aren't redeclaring the conversion function.
1312 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001313
1314 // C++ [class.conv.fct]p1:
1315 // [...] A conversion function is never used to convert a
1316 // (possibly cv-qualified) object to the (possibly cv-qualified)
1317 // same object type (or a reference to it), to a (possibly
1318 // cv-qualified) base class of that type (or a reference to it),
1319 // or to (possibly cv-qualified) void.
1320 // FIXME: Suppress this warning if the conversion function ends up
1321 // being a virtual function that overrides a virtual function in a
1322 // base class.
1323 QualType ClassType
1324 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1325 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1326 ConvType = ConvTypeRef->getPointeeType();
1327 if (ConvType->isRecordType()) {
1328 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1329 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001330 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001331 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001332 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001333 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001334 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001335 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001336 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001337 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001338 }
1339
Douglas Gregor853dd392008-12-26 15:00:45 +00001340 if (Conversion->getPreviousDeclaration()) {
1341 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1342 for (OverloadedFunctionDecl::function_iterator
1343 Conv = Conversions->function_begin(),
1344 ConvEnd = Conversions->function_end();
1345 Conv != ConvEnd; ++Conv) {
1346 if (*Conv == Conversion->getPreviousDeclaration()) {
1347 *Conv = Conversion;
1348 return (DeclTy *)Conversion;
1349 }
1350 }
1351 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1352 } else
1353 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001354
1355 return (DeclTy *)Conversion;
1356}
1357
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001358//===----------------------------------------------------------------------===//
1359// Namespace Handling
1360//===----------------------------------------------------------------------===//
1361
1362/// ActOnStartNamespaceDef - This is called at the start of a namespace
1363/// definition.
1364Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1365 SourceLocation IdentLoc,
1366 IdentifierInfo *II,
1367 SourceLocation LBrace) {
1368 NamespaceDecl *Namespc =
1369 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1370 Namespc->setLBracLoc(LBrace);
1371
1372 Scope *DeclRegionScope = NamespcScope->getParent();
1373
1374 if (II) {
1375 // C++ [namespace.def]p2:
1376 // The identifier in an original-namespace-definition shall not have been
1377 // previously defined in the declarative region in which the
1378 // original-namespace-definition appears. The identifier in an
1379 // original-namespace-definition is the name of the namespace. Subsequently
1380 // in that declarative region, it is treated as an original-namespace-name.
1381
Douglas Gregor09be81b2009-02-04 17:27:36 +00001382 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1383 true);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001384
1385 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1386 // This is an extended namespace definition.
1387 // Attach this namespace decl to the chain of extended namespace
1388 // definitions.
1389 OrigNS->setNextNamespace(Namespc);
1390 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001391
Douglas Gregor8acb7272008-12-11 16:49:14 +00001392 // Remove the previous declaration from the scope.
1393 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor39677622008-12-11 20:41:00 +00001394 IdResolver.RemoveDecl(OrigNS);
1395 DeclRegionScope->RemoveDecl(OrigNS);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001396 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001397 } else if (PrevDecl) {
1398 // This is an invalid name redefinition.
1399 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1400 << Namespc->getDeclName();
1401 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1402 Namespc->setInvalidDecl();
1403 // Continue on to push Namespc as current DeclContext and return it.
1404 }
1405
1406 PushOnScopeChains(Namespc, DeclRegionScope);
1407 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001408 // FIXME: Handle anonymous namespaces
1409 }
1410
1411 // Although we could have an invalid decl (i.e. the namespace name is a
1412 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001413 // FIXME: We should be able to push Namespc here, so that the
1414 // each DeclContext for the namespace has the declarations
1415 // that showed up in that particular namespace definition.
1416 PushDeclContext(NamespcScope, Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001417 return Namespc;
1418}
1419
1420/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1421/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1422void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1423 Decl *Dcl = static_cast<Decl *>(D);
1424 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1425 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1426 Namespc->setRBracLoc(RBrace);
1427 PopDeclContext();
1428}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001429
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001430Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1431 SourceLocation UsingLoc,
1432 SourceLocation NamespcLoc,
1433 const CXXScopeSpec &SS,
1434 SourceLocation IdentLoc,
1435 IdentifierInfo *NamespcName,
1436 AttributeList *AttrList) {
1437 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1438 assert(NamespcName && "Invalid NamespcName.");
1439 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001440 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001441
Douglas Gregor7a7be652009-02-03 19:21:40 +00001442 UsingDirectiveDecl *UDir = 0;
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001443
Douglas Gregor78d70132009-01-14 22:20:51 +00001444 // Lookup namespace name.
Douglas Gregor7a7be652009-02-03 19:21:40 +00001445 LookupResult R = LookupParsedName(S, &SS, NamespcName,
1446 LookupNamespaceName, false);
1447 if (R.isAmbiguous()) {
1448 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1449 return 0;
1450 }
Douglas Gregor09be81b2009-02-04 17:27:36 +00001451 if (NamedDecl *NS = R) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001452 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001453 // C++ [namespace.udir]p1:
1454 // A using-directive specifies that the names in the nominated
1455 // namespace can be used in the scope in which the
1456 // using-directive appears after the using-directive. During
1457 // unqualified name lookup (3.4.1), the names appear as if they
1458 // were declared in the nearest enclosing namespace which
1459 // contains both the using-directive and the nominated
1460 // namespace. [Note: in this context, “contains” means “contains
1461 // directly or indirectly”. ]
1462
1463 // Find enclosing context containing both using-directive and
1464 // nominated namespace.
1465 DeclContext *CommonAncestor = cast<DeclContext>(NS);
1466 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1467 CommonAncestor = CommonAncestor->getParent();
1468
1469 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1470 NamespcLoc, IdentLoc,
1471 cast<NamespaceDecl>(NS),
1472 CommonAncestor);
1473 PushUsingDirective(S, UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001474 } else {
Chris Lattner954381a2009-01-06 07:24:29 +00001475 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001476 }
1477
Douglas Gregor7a7be652009-02-03 19:21:40 +00001478 // FIXME: We ignore attributes for now.
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001479 delete AttrList;
Douglas Gregor7a7be652009-02-03 19:21:40 +00001480 return UDir;
1481}
1482
1483void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1484 // If scope has associated entity, then using directive is at namespace
1485 // or translation unit scope. We add UsingDirectiveDecls, into
1486 // it's lookup structure.
1487 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1488 Ctx->addDecl(UDir);
1489 else
1490 // Otherwise it is block-sope. using-directives will affect lookup
1491 // only to the end of scope.
1492 S->PushUsingDirective(UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001493}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001494
1495/// AddCXXDirectInitializerToDecl - This action is called immediately after
1496/// ActOnDeclarator, when a C++ direct initializer is present.
1497/// e.g: "int x(1);"
1498void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1499 ExprTy **ExprTys, unsigned NumExprs,
1500 SourceLocation *CommaLocs,
1501 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001502 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001503 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001504
1505 // If there is no declaration, there was an error parsing it. Just ignore
1506 // the initializer.
1507 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +00001508 for (unsigned i = 0; i != NumExprs; ++i)
Ted Kremenek0c97e042009-02-07 01:47:29 +00001509 static_cast<Expr *>(ExprTys[i])->Destroy(Context);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001510 return;
1511 }
1512
1513 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1514 if (!VDecl) {
1515 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1516 RealDecl->setInvalidDecl();
1517 return;
1518 }
1519
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001520 // We will treat direct-initialization as a copy-initialization:
1521 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001522 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1523 //
1524 // Clients that want to distinguish between the two forms, can check for
1525 // direct initializer using VarDecl::hasCXXDirectInitializer().
1526 // A major benefit is that clients that don't particularly care about which
1527 // exactly form was it (like the CodeGen) can handle both cases without
1528 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001529
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001530 // C++ 8.5p11:
1531 // The form of initialization (using parentheses or '=') is generally
1532 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001533 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001534 QualType DeclInitType = VDecl->getType();
1535 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1536 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001537
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001538 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001539 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +00001540 = PerformInitializationByConstructor(DeclInitType,
1541 (Expr **)ExprTys, NumExprs,
1542 VDecl->getLocation(),
1543 SourceRange(VDecl->getLocation(),
1544 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00001545 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00001546 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +00001547 if (!Constructor) {
1548 RealDecl->setInvalidDecl();
1549 }
Douglas Gregor6428e762008-11-05 15:29:30 +00001550
1551 // Let clients know that initialization was done with a direct
1552 // initializer.
1553 VDecl->setCXXDirectInitializer(true);
1554
1555 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1556 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001557 return;
1558 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001559
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001560 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001561 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1562 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001563 RealDecl->setInvalidDecl();
1564 return;
1565 }
1566
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001567 // Let clients know that initialization was done with a direct initializer.
1568 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001569
1570 assert(NumExprs == 1 && "Expected 1 expression");
1571 // Set the init expression, handles conversions.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001572 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001573}
Douglas Gregor81c29152008-10-29 00:13:59 +00001574
Douglas Gregor6428e762008-11-05 15:29:30 +00001575/// PerformInitializationByConstructor - Perform initialization by
1576/// constructor (C++ [dcl.init]p14), which may occur as part of
1577/// direct-initialization or copy-initialization. We are initializing
1578/// an object of type @p ClassType with the given arguments @p
1579/// Args. @p Loc is the location in the source code where the
1580/// initializer occurs (e.g., a declaration, member initializer,
1581/// functional cast, etc.) while @p Range covers the whole
1582/// initialization. @p InitEntity is the entity being initialized,
1583/// which may by the name of a declaration or a type. @p Kind is the
1584/// kind of initialization we're performing, which affects whether
1585/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001586/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001587/// when the initialization fails, emits a diagnostic and returns
1588/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001589CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001590Sema::PerformInitializationByConstructor(QualType ClassType,
1591 Expr **Args, unsigned NumArgs,
1592 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00001593 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00001594 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001595 const RecordType *ClassRec = ClassType->getAsRecordType();
1596 assert(ClassRec && "Can only initialize a class type here");
1597
1598 // C++ [dcl.init]p14:
1599 //
1600 // If the initialization is direct-initialization, or if it is
1601 // copy-initialization where the cv-unqualified version of the
1602 // source type is the same class as, or a derived class of, the
1603 // class of the destination, constructors are considered. The
1604 // applicable constructors are enumerated (13.3.1.3), and the
1605 // best one is chosen through overload resolution (13.3). The
1606 // constructor so selected is called to initialize the object,
1607 // with the initializer expression(s) as its argument(s). If no
1608 // constructor applies, or the overload resolution is ambiguous,
1609 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001610 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1611 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001612
1613 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00001614 DeclarationName ConstructorName
1615 = Context.DeclarationNames.getCXXConstructorName(
1616 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001617 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00001618 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001619 Con != ConEnd; ++Con) {
1620 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor6428e762008-11-05 15:29:30 +00001621 if ((Kind == IK_Direct) ||
1622 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1623 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1624 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1625 }
1626
Douglas Gregorb9213832008-12-15 21:24:18 +00001627 // FIXME: When we decide not to synthesize the implicitly-declared
1628 // constructors, we'll need to make them appear here.
1629
Douglas Gregor5870a952008-11-03 20:45:27 +00001630 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001631 switch (BestViableFunction(CandidateSet, Best)) {
1632 case OR_Success:
1633 // We found a constructor. Return it.
1634 return cast<CXXConstructorDecl>(Best->Function);
1635
1636 case OR_No_Viable_Function:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001637 if (InitEntity)
1638 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001639 << InitEntity << Range;
Douglas Gregor538a4c22009-02-02 17:43:21 +00001640 else
1641 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001642 << ClassType << Range;
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00001643 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00001644 return 0;
1645
1646 case OR_Ambiguous:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001647 if (InitEntity)
1648 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1649 else
1650 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00001651 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1652 return 0;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001653
1654 case OR_Deleted:
1655 if (InitEntity)
1656 Diag(Loc, diag::err_ovl_deleted_init)
1657 << Best->Function->isDeleted()
1658 << InitEntity << Range;
1659 else
1660 Diag(Loc, diag::err_ovl_deleted_init)
1661 << Best->Function->isDeleted()
1662 << InitEntity << Range;
1663 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1664 return 0;
Douglas Gregor5870a952008-11-03 20:45:27 +00001665 }
1666
1667 return 0;
1668}
1669
Douglas Gregor81c29152008-10-29 00:13:59 +00001670/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1671/// determine whether they are reference-related,
1672/// reference-compatible, reference-compatible with added
1673/// qualification, or incompatible, for use in C++ initialization by
1674/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1675/// type, and the first type (T1) is the pointee type of the reference
1676/// type being initialized.
1677Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001678Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1679 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001680 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1681 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1682
1683 T1 = Context.getCanonicalType(T1);
1684 T2 = Context.getCanonicalType(T2);
1685 QualType UnqualT1 = T1.getUnqualifiedType();
1686 QualType UnqualT2 = T2.getUnqualifiedType();
1687
1688 // C++ [dcl.init.ref]p4:
1689 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1690 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1691 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001692 if (UnqualT1 == UnqualT2)
1693 DerivedToBase = false;
1694 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1695 DerivedToBase = true;
1696 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001697 return Ref_Incompatible;
1698
1699 // At this point, we know that T1 and T2 are reference-related (at
1700 // least).
1701
1702 // C++ [dcl.init.ref]p4:
1703 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1704 // reference-related to T2 and cv1 is the same cv-qualification
1705 // as, or greater cv-qualification than, cv2. For purposes of
1706 // overload resolution, cases for which cv1 is greater
1707 // cv-qualification than cv2 are identified as
1708 // reference-compatible with added qualification (see 13.3.3.2).
1709 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1710 return Ref_Compatible;
1711 else if (T1.isMoreQualifiedThan(T2))
1712 return Ref_Compatible_With_Added_Qualification;
1713 else
1714 return Ref_Related;
1715}
1716
1717/// CheckReferenceInit - Check the initialization of a reference
1718/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1719/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001720/// list), and DeclType is the type of the declaration. When ICS is
1721/// non-null, this routine will compute the implicit conversion
1722/// sequence according to C++ [over.ics.ref] and will not produce any
1723/// diagnostics; when ICS is null, it will emit diagnostics when any
1724/// errors are found. Either way, a return value of true indicates
1725/// that there was a failure, a return value of false indicates that
1726/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001727///
1728/// When @p SuppressUserConversions, user-defined conversions are
1729/// suppressed.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001730/// When @p AllowExplicit, we also permit explicit user-defined
1731/// conversion functions.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001732bool
1733Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001734 ImplicitConversionSequence *ICS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001735 bool SuppressUserConversions,
1736 bool AllowExplicit) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001737 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1738
1739 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1740 QualType T2 = Init->getType();
1741
Douglas Gregor45014fd2008-11-10 20:40:00 +00001742 // If the initializer is the address of an overloaded function, try
1743 // to resolve the overloaded function. If all goes well, T2 is the
1744 // type of the resulting function.
1745 if (T2->isOverloadType()) {
1746 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1747 ICS != 0);
1748 if (Fn) {
1749 // Since we're performing this reference-initialization for
1750 // real, update the initializer with the resulting function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00001751 if (!ICS) {
1752 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
1753 return true;
1754
Douglas Gregor45014fd2008-11-10 20:40:00 +00001755 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregoraa57e862009-02-18 21:56:37 +00001756 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00001757
1758 T2 = Fn->getType();
1759 }
1760 }
1761
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001762 // Compute some basic properties of the types and the initializer.
1763 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001764 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001765 ReferenceCompareResult RefRelationship
1766 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1767
1768 // Most paths end in a failed conversion.
1769 if (ICS)
1770 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001771
1772 // C++ [dcl.init.ref]p5:
1773 // A reference to type “cv1 T1” is initialized by an expression
1774 // of type “cv2 T2” as follows:
1775
1776 // -- If the initializer expression
1777
1778 bool BindsDirectly = false;
1779 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1780 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001781 //
1782 // Note that the bit-field check is skipped if we are just computing
1783 // the implicit conversion sequence (C++ [over.best.ics]p2).
1784 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1785 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001786 BindsDirectly = true;
1787
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001788 if (ICS) {
1789 // C++ [over.ics.ref]p1:
1790 // When a parameter of reference type binds directly (8.5.3)
1791 // to an argument expression, the implicit conversion sequence
1792 // is the identity conversion, unless the argument expression
1793 // has a type that is a derived class of the parameter type,
1794 // in which case the implicit conversion sequence is a
1795 // derived-to-base Conversion (13.3.3.1).
1796 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1797 ICS->Standard.First = ICK_Identity;
1798 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1799 ICS->Standard.Third = ICK_Identity;
1800 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1801 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001802 ICS->Standard.ReferenceBinding = true;
1803 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001804
1805 // Nothing more to do: the inaccessibility/ambiguity check for
1806 // derived-to-base conversions is suppressed when we're
1807 // computing the implicit conversion sequence (C++
1808 // [over.best.ics]p2).
1809 return false;
1810 } else {
1811 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001812 // FIXME: Binding to a subobject of the lvalue is going to require
1813 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001814 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001815 }
1816 }
1817
1818 // -- has a class type (i.e., T2 is a class type) and can be
1819 // implicitly converted to an lvalue of type “cv3 T3,”
1820 // where “cv1 T1” is reference-compatible with “cv3 T3”
1821 // 92) (this conversion is selected by enumerating the
1822 // applicable conversion functions (13.3.1.6) and choosing
1823 // the best one through overload resolution (13.3)),
Douglas Gregore6985fe2008-11-10 16:14:15 +00001824 if (!SuppressUserConversions && T2->isRecordType()) {
1825 // FIXME: Look for conversions in base classes!
1826 CXXRecordDecl *T2RecordDecl
1827 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00001828
Douglas Gregore6985fe2008-11-10 16:14:15 +00001829 OverloadCandidateSet CandidateSet;
1830 OverloadedFunctionDecl *Conversions
1831 = T2RecordDecl->getConversionFunctions();
1832 for (OverloadedFunctionDecl::function_iterator Func
1833 = Conversions->function_begin();
1834 Func != Conversions->function_end(); ++Func) {
1835 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1836
1837 // If the conversion function doesn't return a reference type,
1838 // it can't be considered for this conversion.
1839 // FIXME: This will change when we support rvalue references.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001840 if (Conv->getConversionType()->isReferenceType() &&
1841 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregore6985fe2008-11-10 16:14:15 +00001842 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1843 }
1844
1845 OverloadCandidateSet::iterator Best;
1846 switch (BestViableFunction(CandidateSet, Best)) {
1847 case OR_Success:
1848 // This is a direct binding.
1849 BindsDirectly = true;
1850
1851 if (ICS) {
1852 // C++ [over.ics.ref]p1:
1853 //
1854 // [...] If the parameter binds directly to the result of
1855 // applying a conversion function to the argument
1856 // expression, the implicit conversion sequence is a
1857 // user-defined conversion sequence (13.3.3.1.2), with the
1858 // second standard conversion sequence either an identity
1859 // conversion or, if the conversion function returns an
1860 // entity of a type that is a derived class of the parameter
1861 // type, a derived-to-base Conversion.
1862 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1863 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1864 ICS->UserDefined.After = Best->FinalConversion;
1865 ICS->UserDefined.ConversionFunction = Best->Function;
1866 assert(ICS->UserDefined.After.ReferenceBinding &&
1867 ICS->UserDefined.After.DirectBinding &&
1868 "Expected a direct reference binding!");
1869 return false;
1870 } else {
1871 // Perform the conversion.
1872 // FIXME: Binding to a subobject of the lvalue is going to require
1873 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001874 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00001875 }
1876 break;
1877
1878 case OR_Ambiguous:
1879 assert(false && "Ambiguous reference binding conversions not implemented.");
1880 return true;
1881
1882 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001883 case OR_Deleted:
1884 // There was no suitable conversion, or we found a deleted
1885 // conversion; continue with other checks.
Douglas Gregore6985fe2008-11-10 16:14:15 +00001886 break;
1887 }
1888 }
1889
Douglas Gregor81c29152008-10-29 00:13:59 +00001890 if (BindsDirectly) {
1891 // C++ [dcl.init.ref]p4:
1892 // [...] In all cases where the reference-related or
1893 // reference-compatible relationship of two types is used to
1894 // establish the validity of a reference binding, and T1 is a
1895 // base class of T2, a program that necessitates such a binding
1896 // is ill-formed if T1 is an inaccessible (clause 11) or
1897 // ambiguous (10.2) base class of T2.
1898 //
1899 // Note that we only check this condition when we're allowed to
1900 // complain about errors, because we should not be checking for
1901 // ambiguity (or inaccessibility) unless the reference binding
1902 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001903 if (DerivedToBase)
1904 return CheckDerivedToBaseConversion(T2, T1,
1905 Init->getSourceRange().getBegin(),
1906 Init->getSourceRange());
1907 else
1908 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001909 }
1910
1911 // -- Otherwise, the reference shall be to a non-volatile const
1912 // type (i.e., cv1 shall be const).
1913 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001914 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001915 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001916 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001917 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1918 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001919 return true;
1920 }
1921
1922 // -- If the initializer expression is an rvalue, with T2 a
1923 // class type, and “cv1 T1” is reference-compatible with
1924 // “cv2 T2,” the reference is bound in one of the
1925 // following ways (the choice is implementation-defined):
1926 //
1927 // -- The reference is bound to the object represented by
1928 // the rvalue (see 3.10) or to a sub-object within that
1929 // object.
1930 //
1931 // -- A temporary of type “cv1 T2” [sic] is created, and
1932 // a constructor is called to copy the entire rvalue
1933 // object into the temporary. The reference is bound to
1934 // the temporary or to a sub-object within the
1935 // temporary.
1936 //
Douglas Gregor81c29152008-10-29 00:13:59 +00001937 // The constructor that would be used to make the copy
1938 // shall be callable whether or not the copy is actually
1939 // done.
1940 //
1941 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1942 // freedom, so we will always take the first option and never build
1943 // a temporary in this case. FIXME: We will, however, have to check
1944 // for the presence of a copy constructor in C++98/03 mode.
1945 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001946 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1947 if (ICS) {
1948 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1949 ICS->Standard.First = ICK_Identity;
1950 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1951 ICS->Standard.Third = ICK_Identity;
1952 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1953 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001954 ICS->Standard.ReferenceBinding = true;
1955 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001956 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001957 // FIXME: Binding to a subobject of the rvalue is going to require
1958 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001959 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001960 }
1961 return false;
1962 }
1963
1964 // -- Otherwise, a temporary of type “cv1 T1” is created and
1965 // initialized from the initializer expression using the
1966 // rules for a non-reference copy initialization (8.5). The
1967 // reference is then bound to the temporary. If T1 is
1968 // reference-related to T2, cv1 must be the same
1969 // cv-qualification as, or greater cv-qualification than,
1970 // cv2; otherwise, the program is ill-formed.
1971 if (RefRelationship == Ref_Related) {
1972 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1973 // we would be reference-compatible or reference-compatible with
1974 // added qualification. But that wasn't the case, so the reference
1975 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001976 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001977 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001978 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001979 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1980 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001981 return true;
1982 }
1983
Douglas Gregorb206cc42009-01-30 23:27:23 +00001984 // If at least one of the types is a class type, the types are not
1985 // related, and we aren't allowed any user conversions, the
1986 // reference binding fails. This case is important for breaking
1987 // recursion, since TryImplicitConversion below will attempt to
1988 // create a temporary through the use of a copy constructor.
1989 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
1990 (T1->isRecordType() || T2->isRecordType())) {
1991 if (!ICS)
1992 Diag(Init->getSourceRange().getBegin(),
1993 diag::err_typecheck_convert_incompatible)
1994 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
1995 return true;
1996 }
1997
Douglas Gregor81c29152008-10-29 00:13:59 +00001998 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001999 if (ICS) {
2000 /// C++ [over.ics.ref]p2:
2001 ///
2002 /// When a parameter of reference type is not bound directly to
2003 /// an argument expression, the conversion sequence is the one
2004 /// required to convert the argument expression to the
2005 /// underlying type of the reference according to
2006 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
2007 /// to copy-initializing a temporary of the underlying type with
2008 /// the argument expression. Any difference in top-level
2009 /// cv-qualification is subsumed by the initialization itself
2010 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002011 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002012 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2013 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00002014 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002015 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002016}
Douglas Gregore60e5d32008-11-06 22:13:31 +00002017
2018/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2019/// of this overloaded operator is well-formed. If so, returns false;
2020/// otherwise, emits appropriate diagnostics and returns true.
2021bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002022 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00002023 "Expected an overloaded operator declaration");
2024
Douglas Gregore60e5d32008-11-06 22:13:31 +00002025 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2026
2027 // C++ [over.oper]p5:
2028 // The allocation and deallocation functions, operator new,
2029 // operator new[], operator delete and operator delete[], are
2030 // described completely in 3.7.3. The attributes and restrictions
2031 // found in the rest of this subclause do not apply to them unless
2032 // explicitly stated in 3.7.3.
2033 // FIXME: Write a separate routine for checking this. For now, just
2034 // allow it.
2035 if (Op == OO_New || Op == OO_Array_New ||
2036 Op == OO_Delete || Op == OO_Array_Delete)
2037 return false;
2038
2039 // C++ [over.oper]p6:
2040 // An operator function shall either be a non-static member
2041 // function or be a non-member function and have at least one
2042 // parameter whose type is a class, a reference to a class, an
2043 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002044 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2045 if (MethodDecl->isStatic())
2046 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002047 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002048 } else {
2049 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002050 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2051 ParamEnd = FnDecl->param_end();
2052 Param != ParamEnd; ++Param) {
2053 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002054 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2055 ClassOrEnumParam = true;
2056 break;
2057 }
2058 }
2059
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002060 if (!ClassOrEnumParam)
2061 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002062 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00002063 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002064 }
2065
2066 // C++ [over.oper]p8:
2067 // An operator function cannot have default arguments (8.3.6),
2068 // except where explicitly stated below.
2069 //
2070 // Only the function-call operator allows default arguments
2071 // (C++ [over.call]p1).
2072 if (Op != OO_Call) {
2073 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2074 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002075 if ((*Param)->hasUnparsedDefaultArg())
2076 return Diag((*Param)->getLocation(),
2077 diag::err_operator_overload_default_arg)
2078 << FnDecl->getDeclName();
2079 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002080 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00002081 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00002082 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002083 }
2084 }
2085
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002086 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2087 { false, false, false }
2088#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2089 , { Unary, Binary, MemberOnly }
2090#include "clang/Basic/OperatorKinds.def"
2091 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00002092
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002093 bool CanBeUnaryOperator = OperatorUses[Op][0];
2094 bool CanBeBinaryOperator = OperatorUses[Op][1];
2095 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00002096
2097 // C++ [over.oper]p8:
2098 // [...] Operator functions cannot have more or fewer parameters
2099 // than the number required for the corresponding operator, as
2100 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002101 unsigned NumParams = FnDecl->getNumParams()
2102 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002103 if (Op != OO_Call &&
2104 ((NumParams == 1 && !CanBeUnaryOperator) ||
2105 (NumParams == 2 && !CanBeBinaryOperator) ||
2106 (NumParams < 1) || (NumParams > 2))) {
2107 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00002108 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002109 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002110 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002111 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002112 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002113 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00002114 assert(CanBeBinaryOperator &&
2115 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00002116 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002117 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00002118
Chris Lattnerbb002332008-11-21 07:57:12 +00002119 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00002120 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002121 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002122
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002123 // Overloaded operators other than operator() cannot be variadic.
2124 if (Op != OO_Call &&
Douglas Gregor4fa58902009-02-26 23:50:07 +00002125 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002126 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00002127 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002128 }
2129
2130 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002131 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2132 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002133 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00002134 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002135 }
2136
2137 // C++ [over.inc]p1:
2138 // The user-defined function called operator++ implements the
2139 // prefix and postfix ++ operator. If this function is a member
2140 // function with no parameters, or a non-member function with one
2141 // parameter of class or enumeration type, it defines the prefix
2142 // increment operator ++ for objects of that type. If the function
2143 // is a member function with one parameter (which shall be of type
2144 // int) or a non-member function with two parameters (the second
2145 // of which shall be of type int), it defines the postfix
2146 // increment operator ++ for objects of that type.
2147 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2148 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2149 bool ParamIsInt = false;
2150 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2151 ParamIsInt = BT->getKind() == BuiltinType::Int;
2152
Chris Lattnera7021ee2008-11-21 07:50:02 +00002153 if (!ParamIsInt)
2154 return Diag(LastParam->getLocation(),
2155 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002156 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002157 }
2158
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002159 // Notify the class if it got an assignment operator.
2160 if (Op == OO_Equal) {
2161 // Would have returned earlier otherwise.
2162 assert(isa<CXXMethodDecl>(FnDecl) &&
2163 "Overloaded = not member, but not filtered.");
2164 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2165 Method->getParent()->addedAssignmentOperator(Context, Method);
2166 }
2167
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002168 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002169}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002170
Douglas Gregord8028382009-01-05 19:45:36 +00002171/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2172/// linkage specification, including the language and (if present)
2173/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2174/// the location of the language string literal, which is provided
2175/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2176/// the '{' brace. Otherwise, this linkage specification does not
2177/// have any braces.
2178Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2179 SourceLocation ExternLoc,
2180 SourceLocation LangLoc,
2181 const char *Lang,
2182 unsigned StrSize,
2183 SourceLocation LBraceLoc) {
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002184 LinkageSpecDecl::LanguageIDs Language;
2185 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2186 Language = LinkageSpecDecl::lang_c;
2187 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2188 Language = LinkageSpecDecl::lang_cxx;
2189 else {
Douglas Gregord8028382009-01-05 19:45:36 +00002190 Diag(LangLoc, diag::err_bad_language);
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002191 return 0;
2192 }
2193
2194 // FIXME: Add all the various semantics of linkage specifications
2195
Douglas Gregord8028382009-01-05 19:45:36 +00002196 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2197 LangLoc, Language,
2198 LBraceLoc.isValid());
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002199 CurContext->addDecl(D);
Douglas Gregord8028382009-01-05 19:45:36 +00002200 PushDeclContext(S, D);
2201 return D;
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002202}
2203
Douglas Gregord8028382009-01-05 19:45:36 +00002204/// ActOnFinishLinkageSpecification - Completely the definition of
2205/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2206/// valid, it's the position of the closing '}' brace in a linkage
2207/// specification that uses braces.
2208Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2209 DeclTy *LinkageSpec,
2210 SourceLocation RBraceLoc) {
2211 if (LinkageSpec)
2212 PopDeclContext();
2213 return LinkageSpec;
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002214}
2215
Sebastian Redl743c8162008-12-22 19:15:10 +00002216/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2217/// handler.
2218Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2219{
2220 QualType ExDeclType = GetTypeForDeclarator(D, S);
2221 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2222
2223 bool Invalid = false;
2224
2225 // Arrays and functions decay.
2226 if (ExDeclType->isArrayType())
2227 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2228 else if (ExDeclType->isFunctionType())
2229 ExDeclType = Context.getPointerType(ExDeclType);
2230
2231 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2232 // The exception-declaration shall not denote a pointer or reference to an
2233 // incomplete type, other than [cv] void*.
2234 QualType BaseType = ExDeclType;
2235 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002236 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl743c8162008-12-22 19:15:10 +00002237 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2238 BaseType = Ptr->getPointeeType();
2239 Mode = 1;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002240 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl743c8162008-12-22 19:15:10 +00002241 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2242 BaseType = Ref->getPointeeType();
2243 Mode = 2;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002244 DK = diag::err_catch_incomplete_ref;
Sebastian Redl743c8162008-12-22 19:15:10 +00002245 }
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002246 if ((Mode == 0 || !BaseType->isVoidType()) &&
2247 DiagnoseIncompleteType(Begin, BaseType, DK))
Sebastian Redl743c8162008-12-22 19:15:10 +00002248 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00002249
Sebastian Redl237116b2008-12-22 21:35:02 +00002250 // FIXME: Need to test for ability to copy-construct and destroy the
2251 // exception variable.
2252 // FIXME: Need to check for abstract classes.
2253
Sebastian Redl743c8162008-12-22 19:15:10 +00002254 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor09be81b2009-02-04 17:27:36 +00002255 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl743c8162008-12-22 19:15:10 +00002256 // The scope should be freshly made just for us. There is just no way
2257 // it contains any previous declaration.
2258 assert(!S->isDeclScope(PrevDecl));
2259 if (PrevDecl->isTemplateParameter()) {
2260 // Maybe we will complain about the shadowed template parameter.
2261 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2262
2263 }
2264 }
2265
2266 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002267 II, ExDeclType, VarDecl::None, Begin);
Sebastian Redl743c8162008-12-22 19:15:10 +00002268 if (D.getInvalidType() || Invalid)
2269 ExDecl->setInvalidDecl();
2270
2271 if (D.getCXXScopeSpec().isSet()) {
2272 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2273 << D.getCXXScopeSpec().getRange();
2274 ExDecl->setInvalidDecl();
2275 }
2276
2277 // Add the exception declaration into this scope.
2278 S->AddDecl(ExDecl);
2279 if (II)
2280 IdResolver.AddDecl(ExDecl);
2281
2282 ProcessDeclAttributes(ExDecl, D);
2283 return ExDecl;
2284}