blob: e2a8bb4347e9bd95adc8d558843c3480098fed95 [file] [log] [blame]
Chris Lattner3d1cee32008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregor7ad83902008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregore37ac4f2008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor02189362008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner8123a952008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar12bc6922008-08-11 03:27:53 +000021#include "clang/Parse/DeclSpec.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Chris Lattner8123a952008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorf8268ae2008-10-22 17:49:05 +000025#include <map>
Chris Lattner3d1cee32008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner8123a952008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattner9e979552008-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 Lattnerb77792e2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattner9e979552008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner8123a952008-04-10 02:22:51 +000043
Chris Lattner9e979552008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner8123a952008-04-10 02:22:51 +000047
Chris Lattner9e979552008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregor796da182008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattner9e979552008-04-12 23:52:44 +000051 };
Chris Lattner8123a952008-04-10 02:22:51 +000052
Chris Lattner9e979552008-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 Lattnerb77792e2008-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 Lattner9e979552008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner8123a952008-04-10 02:22:51 +000060 }
61
Chris Lattner9e979552008-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 Gregor8e9bebd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattner9e979552008-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 Lattnerfa25bbb2008-11-19 05:08:23 +000077 diag::err_param_default_argument_references_param)
Chris Lattner08631c52008-11-23 21:45:46 +000078 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff248a7532008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattner9e979552008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff248a7532008-04-15 22:42:06 +000083 if (VDecl->isBlockVarDecl())
84 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +000085 diag::err_param_default_argument_references_local)
Chris Lattner08631c52008-11-23 21:45:46 +000086 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +000087 }
Chris Lattner8123a952008-04-10 02:22:51 +000088
Douglas Gregor3996f232008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattner9e979552008-04-12 23:52:44 +000091
Douglas Gregor796da182008-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 Lattnerfa25bbb2008-11-19 05:08:23 +000098 diag::err_param_default_argument_references_this)
99 << ThisE->getSourceRange();
Chris Lattner9e979552008-04-12 23:52:44 +0000100 }
Chris Lattner8123a952008-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 Lattner3d1cee32008-04-08 05:04:30 +0000106void
107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
108 ExprTy *defarg) {
109 ParmVarDecl *Param = (ParmVarDecl *)param;
Ted Kremenek8189cde2009-02-07 01:47:29 +0000110 ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000111 QualType ParamType = Param->getType();
112
113 // Default arguments are only permitted in C++
114 if (!getLangOptions().CPlusPlus) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000115 Diag(EqualLoc, diag::err_param_default_argument)
116 << DefaultArg->getSourceRange();
Douglas Gregor72b505b2008-12-16 21:30:33 +0000117 Param->setInvalidDecl();
Chris Lattner3d1cee32008-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 Lattner3d1cee32008-04-08 05:04:30 +0000127 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor61366e92008-12-24 00:01:03 +0000128 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
129 EqualLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000130 Param->getDeclName(),
131 /*DirectInit=*/false);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000132 if (DefaultArgPtr != DefaultArg.get()) {
133 DefaultArg.take();
134 DefaultArg.reset(DefaultArgPtr);
135 }
Douglas Gregoreb704f22008-11-04 13:57:51 +0000136 if (DefaultInitFailed) {
Chris Lattner3d1cee32008-04-08 05:04:30 +0000137 return;
138 }
139
Chris Lattner8123a952008-04-10 02:22:51 +0000140 // Check that the default argument is well-formed
Chris Lattner9e979552008-04-12 23:52:44 +0000141 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor72b505b2008-12-16 21:30:33 +0000142 if (DefaultArgChecker.Visit(DefaultArg.get())) {
143 Param->setInvalidDecl();
Chris Lattner8123a952008-04-10 02:22:51 +0000144 return;
Douglas Gregor72b505b2008-12-16 21:30:33 +0000145 }
Chris Lattner8123a952008-04-10 02:22:51 +0000146
Chris Lattner3d1cee32008-04-08 05:04:30 +0000147 // Okay: add the default argument to the parameter
148 Param->setDefaultArg(DefaultArg.take());
149}
150
Douglas Gregor61366e92008-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 Gregor72b505b2008-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 Gregor6d6eb572008-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 Gregor61366e92008-12-24 00:01:03 +0000186 if (Param->hasUnparsedDefaultArg()) {
187 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor72b505b2008-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 Gregor61366e92008-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 Gregor6d6eb572008-05-07 04:49:29 +0000196 }
197 }
198 }
199 }
200}
201
Chris Lattner3d1cee32008-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 Gregorcda9c672009-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 Lattner3d1cee32008-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000228 diag::err_param_default_argument_redefinition)
229 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000230 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000231 Invalid = true;
Chris Lattner3d1cee32008-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 Gregorcda9c672009-02-16 17:45:42 +0000238 return Invalid;
Chris Lattner3d1cee32008-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 Gregor72b505b2008-12-16 21:30:33 +0000265 if (Param->isInvalidDecl())
266 /* We already complained about this parameter. */;
267 else if (Param->getIdentifier())
Chris Lattner3d1cee32008-04-08 05:04:30 +0000268 Diag(Param->getLocation(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000269 diag::err_param_default_argument_missing_name)
Chris Lattner43b628c2008-11-19 07:32:16 +0000270 << Param->getIdentifier();
Chris Lattner3d1cee32008-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 Gregor61366e92008-12-24 00:01:03 +0000287 if (!Param->hasUnparsedDefaultArg())
288 Param->getDefaultArg()->Destroy(Context);
Chris Lattner3d1cee32008-04-08 05:04:30 +0000289 Param->setDefaultArg(0);
290 }
291 }
292 }
293}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000294
Douglas Gregorb48fe382008-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.
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000299bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
300 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-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 Gregorb48fe382008-10-31 09:07:45 +0000309 return &II == CurDecl->getIdentifier();
310 else
311 return false;
312}
313
Douglas Gregor2943aed2009-03-03 04:44:36 +0000314/// \brief Check the validity of a C++ base class specifier.
315///
316/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
317/// and returns NULL otherwise.
318CXXBaseSpecifier *
319Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
320 SourceRange SpecifierRange,
321 bool Virtual, AccessSpecifier Access,
322 QualType BaseType,
323 SourceLocation BaseLoc) {
324 // C++ [class.union]p1:
325 // A union shall not have base classes.
326 if (Class->isUnion()) {
327 Diag(Class->getLocation(), diag::err_base_clause_on_union)
328 << SpecifierRange;
329 return 0;
330 }
331
332 if (BaseType->isDependentType())
333 return new CXXBaseSpecifier(SpecifierRange, Virtual,
334 Class->getTagKind() == RecordDecl::TK_class,
335 Access, BaseType);
336
337 // Base specifiers must be record types.
338 if (!BaseType->isRecordType()) {
339 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
340 return 0;
341 }
342
343 // C++ [class.union]p1:
344 // A union shall not be used as a base class.
345 if (BaseType->isUnionType()) {
346 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
347 return 0;
348 }
349
350 // C++ [class.derived]p2:
351 // The class-name in a base-specifier shall not be an incompletely
352 // defined class.
353 if (DiagnoseIncompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
354 SpecifierRange))
355 return 0;
356
357 // If the base class is polymorphic, the new one is, too.
358 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
359 assert(BaseDecl && "Record type has no declaration");
360 BaseDecl = BaseDecl->getDefinition(Context);
361 assert(BaseDecl && "Base type is not incomplete, but has no definition");
362 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
363 Class->setPolymorphic(true);
364
365 // C++ [dcl.init.aggr]p1:
366 // An aggregate is [...] a class with [...] no base classes [...].
367 Class->setAggregate(false);
368 Class->setPOD(false);
369
370 // Create the base specifier.
371 // FIXME: Allocate via ASTContext?
372 return new CXXBaseSpecifier(SpecifierRange, Virtual,
373 Class->getTagKind() == RecordDecl::TK_class,
374 Access, BaseType);
375}
376
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000377/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
378/// one entry in the base class list of a class specifier, for
379/// example:
380/// class foo : public bar, virtual private baz {
381/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000382Sema::BaseResult
383Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
384 bool Virtual, AccessSpecifier Access,
385 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000386 CXXRecordDecl *Class = (CXXRecordDecl*)classdecl;
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000387 QualType BaseType = QualType::getFromOpaquePtr(basetype);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000388 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
389 Virtual, Access,
390 BaseType, BaseLoc))
391 return BaseSpec;
392
393 return true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000394}
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000395
Douglas Gregor2943aed2009-03-03 04:44:36 +0000396/// \brief Performs the actual work of attaching the given base class
397/// specifiers to a C++ class.
398bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
399 unsigned NumBases) {
400 if (NumBases == 0)
401 return false;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000402
403 // Used to keep track of which base types we have already seen, so
404 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor57c856b2008-10-23 18:13:27 +0000405 // that the key is always the unqualified canonical type of the base
406 // class.
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000407 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
408
409 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor57c856b2008-10-23 18:13:27 +0000410 unsigned NumGoodBases = 0;
Douglas Gregor2943aed2009-03-03 04:44:36 +0000411 bool Invalid = false;
Douglas Gregor57c856b2008-10-23 18:13:27 +0000412 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000413 QualType NewBaseType
Douglas Gregor2943aed2009-03-03 04:44:36 +0000414 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor57c856b2008-10-23 18:13:27 +0000415 NewBaseType = NewBaseType.getUnqualifiedType();
416
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000417 if (KnownBaseTypes[NewBaseType]) {
418 // C++ [class.mi]p3:
419 // A class shall not be specified as a direct base class of a
420 // derived class more than once.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000421 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000422 diag::err_duplicate_base_class)
Chris Lattnerd1625842008-11-24 06:25:27 +0000423 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregor2943aed2009-03-03 04:44:36 +0000424 << Bases[idx]->getSourceRange();
Douglas Gregor57c856b2008-10-23 18:13:27 +0000425
426 // Delete the duplicate base class specifier; we're going to
427 // overwrite its pointer later.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000428 delete Bases[idx];
429
430 Invalid = true;
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000431 } else {
432 // Okay, add this new base class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000433 KnownBaseTypes[NewBaseType] = Bases[idx];
434 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorf8268ae2008-10-22 17:49:05 +0000435 }
436 }
437
438 // Attach the remaining base class specifiers to the derived class.
Douglas Gregor2943aed2009-03-03 04:44:36 +0000439 Class->setBases(Bases, NumGoodBases);
Douglas Gregor57c856b2008-10-23 18:13:27 +0000440
441 // Delete the remaining (good) base class specifiers, since their
442 // data has been copied into the CXXRecordDecl.
443 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregor2943aed2009-03-03 04:44:36 +0000444 delete Bases[idx];
445
446 return Invalid;
447}
448
449/// ActOnBaseSpecifiers - Attach the given base specifiers to the
450/// class, after checking whether there are any duplicate base
451/// classes.
452void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
453 unsigned NumBases) {
454 if (!ClassDecl || !Bases || !NumBases)
455 return;
456
457 AdjustDeclIfTemplate(ClassDecl);
458 AttachBaseSpecifiers(cast<CXXRecordDecl>((Decl*)ClassDecl),
459 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregore37ac4f2008-04-13 21:30:24 +0000460}
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000461
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000462//===----------------------------------------------------------------------===//
463// C++ class member Handling
464//===----------------------------------------------------------------------===//
465
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000466/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
467/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
468/// bitfield width if there is one and 'InitExpr' specifies the initializer if
469/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
470/// declarators on it.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000471Sema::DeclTy *
472Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
473 ExprTy *BW, ExprTy *InitExpr,
474 DeclTy *LastInGroup) {
475 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor10bd3682008-11-17 22:58:34 +0000476 DeclarationName Name = GetNameForDeclarator(D);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000477 Expr *BitWidth = static_cast<Expr*>(BW);
478 Expr *Init = static_cast<Expr*>(InitExpr);
479 SourceLocation Loc = D.getIdentifierLoc();
480
Sebastian Redl669d5d72008-11-14 23:42:31 +0000481 bool isFunc = D.isFunctionDeclarator();
482
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000483 // C++ 9.2p6: A member shall not be declared to have automatic storage
484 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000485 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
486 // data members and cannot be applied to names declared const or static,
487 // and cannot be applied to reference members.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000488 switch (DS.getStorageClassSpec()) {
489 case DeclSpec::SCS_unspecified:
490 case DeclSpec::SCS_typedef:
491 case DeclSpec::SCS_static:
492 // FALL THROUGH.
493 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +0000494 case DeclSpec::SCS_mutable:
495 if (isFunc) {
496 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000497 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl669d5d72008-11-14 23:42:31 +0000498 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000499 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
500
Sebastian Redla11f42f2008-11-17 23:24:37 +0000501 // FIXME: It would be nicer if the keyword was ignored only for this
502 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000503 D.getMutableDeclSpec().ClearStorageClassSpecs();
504 } else {
505 QualType T = GetTypeForDeclarator(D, S);
506 diag::kind err = static_cast<diag::kind>(0);
507 if (T->isReferenceType())
508 err = diag::err_mutable_reference;
509 else if (T.isConstQualified())
510 err = diag::err_mutable_const;
511 if (err != 0) {
512 if (DS.getStorageClassSpecLoc().isValid())
513 Diag(DS.getStorageClassSpecLoc(), err);
514 else
515 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redla11f42f2008-11-17 23:24:37 +0000516 // FIXME: It would be nicer if the keyword was ignored only for this
517 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl669d5d72008-11-14 23:42:31 +0000518 D.getMutableDeclSpec().ClearStorageClassSpecs();
519 }
520 }
521 break;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000522 default:
523 if (DS.getStorageClassSpecLoc().isValid())
524 Diag(DS.getStorageClassSpecLoc(),
525 diag::err_storageclass_invalid_for_member);
526 else
527 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
528 D.getMutableDeclSpec().ClearStorageClassSpecs();
529 }
530
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000531 if (!isFunc &&
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000532 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argyrios Kyrtzidisd6caa9e2008-10-15 20:23:22 +0000533 D.getNumTypeObjects() == 0) {
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000534 // Check also for this case:
535 //
536 // typedef int f();
537 // f a;
538 //
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000539 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
540 isFunc = TDType->isFunctionType();
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000541 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000542
Sebastian Redl669d5d72008-11-14 23:42:31 +0000543 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
544 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argyrios Kyrtzidisde933f02008-10-08 22:20:31 +0000545 !isFunc);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000546
547 Decl *Member;
Chris Lattner24793662009-03-05 22:45:59 +0000548 if (isInstField) {
Chris Lattner6f8ce142009-03-05 23:03:49 +0000549 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth);
550 assert(Member && "HandleField never returns null");
Chris Lattner24793662009-03-05 22:45:59 +0000551 } else {
Daniel Dunbar914701e2008-08-05 16:28:08 +0000552 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Chris Lattner6f8ce142009-03-05 23:03:49 +0000553 if (!Member) {
554 if (BitWidth) DeleteExpr(BitWidth);
555 return LastInGroup;
556 }
Chris Lattner8b963ef2009-03-05 23:01:03 +0000557
558 // Non-instance-fields can't have a bitfield.
559 if (BitWidth) {
560 if (Member->isInvalidDecl()) {
561 // don't emit another diagnostic.
562 } else if (isa<CXXClassVarDecl>(Member)) {
563 // C++ 9.6p3: A bit-field shall not be a static member.
564 // "static member 'A' cannot be a bit-field"
565 Diag(Loc, diag::err_static_not_bitfield)
566 << Name << BitWidth->getSourceRange();
567 } else if (isa<TypedefDecl>(Member)) {
568 // "typedef member 'x' cannot be a bit-field"
569 Diag(Loc, diag::err_typedef_not_bitfield)
570 << Name << BitWidth->getSourceRange();
571 } else {
572 // A function typedef ("typedef int f(); f a;").
573 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
574 Diag(Loc, diag::err_not_integral_type_bitfield)
575 << Name << BitWidth->getSourceRange();
576 }
577
578 DeleteExpr(BitWidth);
579 BitWidth = 0;
580 Member->setInvalidDecl();
581 }
Chris Lattner24793662009-03-05 22:45:59 +0000582 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000583
Douglas Gregor10bd3682008-11-17 22:58:34 +0000584 assert((Name || isInstField) && "No identifier for non-field ?");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000585
586 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
587 // specific methods. Use a wrapper class that can be used with all C++ class
588 // member decls.
589 CXXClassMemberWrapper(Member).setAccess(AS);
590
Douglas Gregor64bffa92008-11-05 16:20:31 +0000591 // C++ [dcl.init.aggr]p1:
592 // An aggregate is an array or a class (clause 9) with [...] no
593 // private or protected non-static data members (clause 11).
Sebastian Redl64b45f72009-01-05 20:52:13 +0000594 // A POD must be an aggregate.
595 if (isInstField && (AS == AS_private || AS == AS_protected)) {
596 CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext);
597 Record->setAggregate(false);
598 Record->setPOD(false);
599 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000600
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000601 if (DS.isVirtualSpecified()) {
602 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
603 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
Chris Lattner8b963ef2009-03-05 23:01:03 +0000604 Member->setInvalidDecl();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000605 } else {
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000606 cast<CXXMethodDecl>(Member)->setVirtual();
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000607 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
608 CurClass->setAggregate(false);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000609 CurClass->setPOD(false);
Sebastian Redld93f0dd2008-11-06 15:59:35 +0000610 CurClass->setPolymorphic(true);
611 }
612 }
Douglas Gregor64bffa92008-11-05 16:20:31 +0000613
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000614 // FIXME: The above definition of virtual is not sufficient. A function is
615 // also virtual if it overrides an already virtual function. This is important
616 // to do here because it decides the validity of a pure specifier.
617
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000618 if (Init) {
619 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
620 // if it declares a static member of const integral or const enumeration
621 // type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000622 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
623 // ...static member of...
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000624 CVD->setInit(Init);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000625 // ...const integral or const enumeration type.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000626 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
627 CVD->getType()->isIntegralType()) {
628 // constant-initializer
629 if (CheckForConstantInitializer(Init, CVD->getType()))
Chris Lattner8b963ef2009-03-05 23:01:03 +0000630 Member->setInvalidDecl();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000631
632 } else {
633 // not const integral.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000634 Diag(Loc, diag::err_member_initialization)
Anders Carlssona75023d2008-12-06 20:05:35 +0000635 << Name << Init->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000636 Member->setInvalidDecl();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000637 }
638
639 } else {
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000640 // not static member. perhaps virtual function?
641 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
Sebastian Redlc9b580a2009-01-09 22:29:03 +0000642 // With declarators parsed the way they are, the parser cannot
643 // distinguish between a normal initializer and a pure-specifier.
644 // Thus this grotesque test.
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000645 IntegerLiteral *IL;
646 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
647 Context.getCanonicalType(IL->getType()) == Context.IntTy) {
648 if (MD->isVirtual())
649 MD->setPure();
650 else {
651 Diag(Loc, diag::err_non_virtual_pure)
652 << Name << Init->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000653 Member->setInvalidDecl();
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000654 }
655 } else {
656 Diag(Loc, diag::err_member_function_initialization)
657 << Name << Init->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000658 Member->setInvalidDecl();
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000659 }
660 } else {
661 Diag(Loc, diag::err_member_initialization)
662 << Name << Init->getSourceRange();
Chris Lattner8b963ef2009-03-05 23:01:03 +0000663 Member->setInvalidDecl();
Sebastian Redl9ba73ad2009-01-09 19:57:06 +0000664 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000665 }
666 }
667
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000668 if (isInstField) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000669 FieldCollector->Add(cast<FieldDecl>(Member));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000670 return LastInGroup;
671 }
672 return Member;
673}
674
Douglas Gregor7ad83902008-11-05 04:29:56 +0000675/// ActOnMemInitializer - Handle a C++ member initializer.
676Sema::MemInitResult
677Sema::ActOnMemInitializer(DeclTy *ConstructorD,
678 Scope *S,
679 IdentifierInfo *MemberOrBase,
680 SourceLocation IdLoc,
681 SourceLocation LParenLoc,
682 ExprTy **Args, unsigned NumArgs,
683 SourceLocation *CommaLocs,
684 SourceLocation RParenLoc) {
685 CXXConstructorDecl *Constructor
686 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
687 if (!Constructor) {
688 // The user wrote a constructor initializer on a function that is
689 // not a C++ constructor. Ignore the error for now, because we may
690 // have more member initializers coming; we'll diagnose it just
691 // once in ActOnMemInitializers.
692 return true;
693 }
694
695 CXXRecordDecl *ClassDecl = Constructor->getParent();
696
697 // C++ [class.base.init]p2:
698 // Names in a mem-initializer-id are looked up in the scope of the
699 // constructor’s class and, if not found in that scope, are looked
700 // up in the scope containing the constructor’s
701 // definition. [Note: if the constructor’s class contains a member
702 // with the same name as a direct or virtual base class of the
703 // class, a mem-initializer-id naming the member or base class and
704 // composed of a single identifier refers to the class member. A
705 // mem-initializer-id for the hidden base class may be specified
706 // using a qualified name. ]
707 // Look for a member, first.
Douglas Gregor44b43212008-12-11 16:49:14 +0000708 FieldDecl *Member = 0;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000709 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor44b43212008-12-11 16:49:14 +0000710 if (Result.first != Result.second)
711 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000712
713 // FIXME: Handle members of an anonymous union.
714
715 if (Member) {
716 // FIXME: Perform direct initialization of the member.
717 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
718 }
719
720 // It didn't name a member, so see if it names a class.
Douglas Gregorb696ea32009-02-04 17:00:24 +0000721 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000722 if (!BaseTy)
Chris Lattner3c73c412008-11-19 08:23:25 +0000723 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
724 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000725
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000726 QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000727 if (!BaseType->isRecordType())
Chris Lattner3c73c412008-11-19 08:23:25 +0000728 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattner08631c52008-11-23 21:45:46 +0000729 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000730
731 // C++ [class.base.init]p2:
732 // [...] Unless the mem-initializer-id names a nonstatic data
733 // member of the constructor’s class or a direct or virtual base
734 // of that class, the mem-initializer is ill-formed. A
735 // mem-initializer-list can initialize a base class using any
736 // name that denotes that base class type.
737
738 // First, check for a direct base class.
739 const CXXBaseSpecifier *DirectBaseSpec = 0;
740 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
741 Base != ClassDecl->bases_end(); ++Base) {
742 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
743 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
744 // We found a direct base of this type. That's what we're
745 // initializing.
746 DirectBaseSpec = &*Base;
747 break;
748 }
749 }
750
751 // Check for a virtual base class.
752 // FIXME: We might be able to short-circuit this if we know in
753 // advance that there are no virtual bases.
754 const CXXBaseSpecifier *VirtualBaseSpec = 0;
755 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
756 // We haven't found a base yet; search the class hierarchy for a
757 // virtual base class.
758 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
759 /*DetectVirtual=*/false);
760 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
761 for (BasePaths::paths_iterator Path = Paths.begin();
762 Path != Paths.end(); ++Path) {
763 if (Path->back().Base->isVirtual()) {
764 VirtualBaseSpec = Path->back().Base;
765 break;
766 }
767 }
768 }
769 }
770
771 // C++ [base.class.init]p2:
772 // If a mem-initializer-id is ambiguous because it designates both
773 // a direct non-virtual base class and an inherited virtual base
774 // class, the mem-initializer is ill-formed.
775 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner3c73c412008-11-19 08:23:25 +0000776 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
777 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregor7ad83902008-11-05 04:29:56 +0000778
779 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
780}
781
782
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000783void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
784 DeclTy *TagDecl,
785 SourceLocation LBrac,
786 SourceLocation RBrac) {
Douglas Gregor2943aed2009-03-03 04:44:36 +0000787 TemplateDecl *Template = AdjustDeclIfTemplate(TagDecl);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000788 ActOnFields(S, RLoc, TagDecl,
789 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +0000790 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregor2943aed2009-03-03 04:44:36 +0000791
792 if (!Template)
793 AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000794}
795
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000796/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
797/// special functions, such as the default constructor, copy
798/// constructor, or destructor, to the given C++ class (C++
799/// [special]p1). This routine can only be executed just before the
800/// definition of the class is complete.
801void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000802 QualType ClassType = Context.getTypeDeclType(ClassDecl);
803 ClassType = Context.getCanonicalType(ClassType);
804
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000805 if (!ClassDecl->hasUserDeclaredConstructor()) {
806 // C++ [class.ctor]p5:
807 // A default constructor for a class X is a constructor of class X
808 // that can be called without an argument. If there is no
809 // user-declared constructor for class X, a default constructor is
810 // implicitly declared. An implicitly-declared default constructor
811 // is an inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000812 DeclarationName Name
813 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000814 CXXConstructorDecl *DefaultCon =
815 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000816 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000817 Context.getFunctionType(Context.VoidTy,
818 0, 0, false, 0),
819 /*isExplicit=*/false,
820 /*isInline=*/true,
821 /*isImplicitlyDeclared=*/true);
822 DefaultCon->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000823 DefaultCon->setImplicit();
Douglas Gregor482b77d2009-01-12 23:27:07 +0000824 ClassDecl->addDecl(DefaultCon);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000825
826 // Notify the class that we've added a constructor.
827 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000828 }
829
830 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
831 // C++ [class.copy]p4:
832 // If the class definition does not explicitly declare a copy
833 // constructor, one is declared implicitly.
834
835 // C++ [class.copy]p5:
836 // The implicitly-declared copy constructor for a class X will
837 // have the form
838 //
839 // X::X(const X&)
840 //
841 // if
842 bool HasConstCopyConstructor = true;
843
844 // -- each direct or virtual base class B of X has a copy
845 // constructor whose first parameter is of type const B& or
846 // const volatile B&, and
847 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
848 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
849 const CXXRecordDecl *BaseClassDecl
850 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
851 HasConstCopyConstructor
852 = BaseClassDecl->hasConstCopyConstructor(Context);
853 }
854
855 // -- for all the nonstatic data members of X that are of a
856 // class type M (or array thereof), each such class type
857 // has a copy constructor whose first parameter is of type
858 // const M& or const volatile M&.
859 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
860 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
861 QualType FieldType = (*Field)->getType();
862 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
863 FieldType = Array->getElementType();
864 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
865 const CXXRecordDecl *FieldClassDecl
866 = cast<CXXRecordDecl>(FieldClassType->getDecl());
867 HasConstCopyConstructor
868 = FieldClassDecl->hasConstCopyConstructor(Context);
869 }
870 }
871
Sebastian Redl64b45f72009-01-05 20:52:13 +0000872 // Otherwise, the implicitly declared copy constructor will have
873 // the form
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000874 //
875 // X::X(X&)
Sebastian Redl64b45f72009-01-05 20:52:13 +0000876 QualType ArgType = ClassType;
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000877 if (HasConstCopyConstructor)
878 ArgType = ArgType.withConst();
879 ArgType = Context.getReferenceType(ArgType);
880
Sebastian Redl64b45f72009-01-05 20:52:13 +0000881 // An implicitly-declared copy constructor is an inline public
882 // member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000883 DeclarationName Name
884 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000885 CXXConstructorDecl *CopyConstructor
886 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000887 ClassDecl->getLocation(), Name,
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000888 Context.getFunctionType(Context.VoidTy,
889 &ArgType, 1,
890 false, 0),
891 /*isExplicit=*/false,
892 /*isInline=*/true,
893 /*isImplicitlyDeclared=*/true);
894 CopyConstructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000895 CopyConstructor->setImplicit();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000896
897 // Add the parameter to the constructor.
898 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
899 ClassDecl->getLocation(),
900 /*IdentifierInfo=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000901 ArgType, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000902 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000903
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000904 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor482b77d2009-01-12 23:27:07 +0000905 ClassDecl->addDecl(CopyConstructor);
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000906 }
907
Sebastian Redl64b45f72009-01-05 20:52:13 +0000908 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
909 // Note: The following rules are largely analoguous to the copy
910 // constructor rules. Note that virtual bases are not taken into account
911 // for determining the argument type of the operator. Note also that
912 // operators taking an object instead of a reference are allowed.
913 //
914 // C++ [class.copy]p10:
915 // If the class definition does not explicitly declare a copy
916 // assignment operator, one is declared implicitly.
917 // The implicitly-defined copy assignment operator for a class X
918 // will have the form
919 //
920 // X& X::operator=(const X&)
921 //
922 // if
923 bool HasConstCopyAssignment = true;
924
925 // -- each direct base class B of X has a copy assignment operator
926 // whose parameter is of type const B&, const volatile B& or B,
927 // and
928 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
929 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
930 const CXXRecordDecl *BaseClassDecl
931 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
932 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
933 }
934
935 // -- for all the nonstatic data members of X that are of a class
936 // type M (or array thereof), each such class type has a copy
937 // assignment operator whose parameter is of type const M&,
938 // const volatile M& or M.
939 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
940 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
941 QualType FieldType = (*Field)->getType();
942 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
943 FieldType = Array->getElementType();
944 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
945 const CXXRecordDecl *FieldClassDecl
946 = cast<CXXRecordDecl>(FieldClassType->getDecl());
947 HasConstCopyAssignment
948 = FieldClassDecl->hasConstCopyAssignment(Context);
949 }
950 }
951
952 // Otherwise, the implicitly declared copy assignment operator will
953 // have the form
954 //
955 // X& X::operator=(X&)
956 QualType ArgType = ClassType;
957 QualType RetType = Context.getReferenceType(ArgType);
958 if (HasConstCopyAssignment)
959 ArgType = ArgType.withConst();
960 ArgType = Context.getReferenceType(ArgType);
961
962 // An implicitly-declared copy assignment operator is an inline public
963 // member of its class.
964 DeclarationName Name =
965 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
966 CXXMethodDecl *CopyAssignment =
967 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
968 Context.getFunctionType(RetType, &ArgType, 1,
969 false, 0),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000970 /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000971 CopyAssignment->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000972 CopyAssignment->setImplicit();
Sebastian Redl64b45f72009-01-05 20:52:13 +0000973
974 // Add the parameter to the operator.
975 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
976 ClassDecl->getLocation(),
977 /*IdentifierInfo=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000978 ArgType, VarDecl::None, 0);
Ted Kremenekfc767612009-01-14 00:42:25 +0000979 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000980
981 // Don't call addedAssignmentOperator. There is no way to distinguish an
982 // implicit from an explicit assignment operator.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000983 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000984 }
985
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000986 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor42a552f2008-11-05 20:51:48 +0000987 // C++ [class.dtor]p2:
988 // If a class has no user-declared destructor, a destructor is
989 // declared implicitly. An implicitly-declared destructor is an
990 // inline public member of its class.
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000991 DeclarationName Name
992 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000993 CXXDestructorDecl *Destructor
994 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000995 ClassDecl->getLocation(), Name,
Douglas Gregor42a552f2008-11-05 20:51:48 +0000996 Context.getFunctionType(Context.VoidTy,
997 0, 0, false, 0),
998 /*isInline=*/true,
999 /*isImplicitlyDeclared=*/true);
1000 Destructor->setAccess(AS_public);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001001 Destructor->setImplicit();
Douglas Gregor482b77d2009-01-12 23:27:07 +00001002 ClassDecl->addDecl(Destructor);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001003 }
Douglas Gregor396b7cd2008-11-03 17:51:48 +00001004}
1005
Douglas Gregor72b505b2008-12-16 21:30:33 +00001006/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1007/// parsing a top-level (non-nested) C++ class, and we are now
1008/// parsing those parts of the given Method declaration that could
1009/// not be parsed earlier (C++ [class.mem]p2), such as default
1010/// arguments. This action should enter the scope of the given
1011/// Method declaration as if we had just parsed the qualified method
1012/// name. However, it should not bring the parameters into scope;
1013/// that will be performed by ActOnDelayedCXXMethodParameter.
1014void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
1015 CXXScopeSpec SS;
1016 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
1017 ActOnCXXEnterDeclaratorScope(S, SS);
1018}
1019
1020/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1021/// C++ method declaration. We're (re-)introducing the given
1022/// function parameter into scope for use in parsing later parts of
1023/// the method declaration. For example, we could see an
1024/// ActOnParamDefaultArgument event for this parameter.
1025void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1026 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor61366e92008-12-24 00:01:03 +00001027
1028 // If this parameter has an unparsed default argument, clear it out
1029 // to make way for the parsed default argument.
1030 if (Param->hasUnparsedDefaultArg())
1031 Param->setDefaultArg(0);
1032
Douglas Gregor72b505b2008-12-16 21:30:33 +00001033 S->AddDecl(Param);
1034 if (Param->getDeclName())
1035 IdResolver.AddDecl(Param);
1036}
1037
1038/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1039/// processing the delayed method declaration for Method. The method
1040/// declaration is now considered finished. There may be a separate
1041/// ActOnStartOfFunctionDef action later (not necessarily
1042/// immediately!) for this method, if it was also defined inside the
1043/// class body.
1044void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1045 FunctionDecl *Method = (FunctionDecl*)MethodD;
1046 CXXScopeSpec SS;
1047 SS.setScopeRep(Method->getDeclContext());
1048 ActOnCXXExitDeclaratorScope(S, SS);
1049
1050 // Now that we have our default arguments, check the constructor
1051 // again. It could produce additional diagnostics or affect whether
1052 // the class has implicitly-declared destructors, among other
1053 // things.
1054 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1055 if (CheckConstructor(Constructor))
1056 Constructor->setInvalidDecl();
1057 }
1058
1059 // Check the default arguments, which we may have added.
1060 if (!Method->isInvalidDecl())
1061 CheckCXXDefaultArguments(Method);
1062}
1063
Douglas Gregor42a552f2008-11-05 20:51:48 +00001064/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor72b505b2008-12-16 21:30:33 +00001065/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor42a552f2008-11-05 20:51:48 +00001066/// R. If there are any errors in the declarator, this routine will
1067/// emit diagnostics and return true. Otherwise, it will return
1068/// false. Either way, the type @p R will be updated to reflect a
1069/// well-formed type for the constructor.
1070bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1071 FunctionDecl::StorageClass& SC) {
1072 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1073 bool isInvalid = false;
1074
1075 // C++ [class.ctor]p3:
1076 // A constructor shall not be virtual (10.3) or static (9.4). A
1077 // constructor can be invoked for a const, volatile or const
1078 // volatile object. A constructor shall not be declared const,
1079 // volatile, or const volatile (9.3.2).
1080 if (isVirtual) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001081 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1082 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1083 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001084 isInvalid = true;
1085 }
1086 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001087 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1088 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1089 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001090 isInvalid = true;
1091 SC = FunctionDecl::None;
1092 }
1093 if (D.getDeclSpec().hasTypeSpecifier()) {
1094 // Constructors don't have return types, but the parser will
1095 // happily parse something like:
1096 //
1097 // class X {
1098 // float X(float);
1099 // };
1100 //
1101 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001102 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1103 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1104 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001105 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001106 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001107 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1108 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001109 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1110 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001111 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001112 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1113 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001114 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001115 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1116 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001117 }
1118
1119 // Rebuild the function type "R" without any type qualifiers (in
1120 // case any of the errors above fired) and with "void" as the
1121 // return type, since constructors don't have return types. We
1122 // *always* have to do this, because GetTypeForDeclarator will
1123 // put in a result type of "int" when none was specified.
Douglas Gregor72564e72009-02-26 23:50:07 +00001124 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001125 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1126 Proto->getNumArgs(),
1127 Proto->isVariadic(),
1128 0);
1129
1130 return isInvalid;
1131}
1132
Douglas Gregor72b505b2008-12-16 21:30:33 +00001133/// CheckConstructor - Checks a fully-formed constructor for
1134/// well-formedness, issuing any diagnostics required. Returns true if
1135/// the constructor declarator is invalid.
1136bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1137 if (Constructor->isInvalidDecl())
1138 return true;
1139
1140 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1141 bool Invalid = false;
1142
1143 // C++ [class.copy]p3:
1144 // A declaration of a constructor for a class X is ill-formed if
1145 // its first parameter is of type (optionally cv-qualified) X and
1146 // either there are no other parameters or else all other
1147 // parameters have default arguments.
1148 if ((Constructor->getNumParams() == 1) ||
1149 (Constructor->getNumParams() > 1 &&
1150 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1151 QualType ParamType = Constructor->getParamDecl(0)->getType();
1152 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1153 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1154 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1155 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1156 Invalid = true;
1157 }
1158 }
1159
1160 // Notify the class that we've added a constructor.
1161 ClassDecl->addedConstructor(Context, Constructor);
1162
1163 return Invalid;
1164}
1165
Douglas Gregor42a552f2008-11-05 20:51:48 +00001166/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1167/// the well-formednes of the destructor declarator @p D with type @p
1168/// R. If there are any errors in the declarator, this routine will
1169/// emit diagnostics and return true. Otherwise, it will return
1170/// false. Either way, the type @p R will be updated to reflect a
1171/// well-formed type for the destructor.
1172bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1173 FunctionDecl::StorageClass& SC) {
1174 bool isInvalid = false;
1175
1176 // C++ [class.dtor]p1:
1177 // [...] A typedef-name that names a class is a class-name
1178 // (7.1.3); however, a typedef-name that names a class shall not
1179 // be used as the identifier in the declarator for a destructor
1180 // declaration.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001181 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1182 if (DeclaratorType->getAsTypedefType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001183 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001184 << DeclaratorType;
Douglas Gregor55c60952008-11-10 14:41:22 +00001185 isInvalid = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001186 }
1187
1188 // C++ [class.dtor]p2:
1189 // A destructor is used to destroy objects of its class type. A
1190 // destructor takes no parameters, and no return type can be
1191 // specified for it (not even void). The address of a destructor
1192 // shall not be taken. A destructor shall not be static. A
1193 // destructor can be invoked for a const, volatile or const
1194 // volatile object. A destructor shall not be declared const,
1195 // volatile or const volatile (9.3.2).
1196 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001197 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1198 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1199 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001200 isInvalid = true;
1201 SC = FunctionDecl::None;
1202 }
1203 if (D.getDeclSpec().hasTypeSpecifier()) {
1204 // Destructors don't have return types, but the parser will
1205 // happily parse something like:
1206 //
1207 // class X {
1208 // float ~X();
1209 // };
1210 //
1211 // The return type will be eliminated later.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001212 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1213 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1214 << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001215 }
Douglas Gregor72564e72009-02-26 23:50:07 +00001216 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001217 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1218 if (FTI.TypeQuals & QualType::Const)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001219 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1220 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001221 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001222 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1223 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001224 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001225 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1226 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001227 }
1228
1229 // Make sure we don't have any parameters.
Douglas Gregor72564e72009-02-26 23:50:07 +00001230 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor42a552f2008-11-05 20:51:48 +00001231 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1232
1233 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00001234 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001235 }
1236
1237 // Make sure the destructor isn't variadic.
Douglas Gregor72564e72009-02-26 23:50:07 +00001238 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor42a552f2008-11-05 20:51:48 +00001239 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1240
1241 // Rebuild the function type "R" without any type qualifiers or
1242 // parameters (in case any of the errors above fired) and with
1243 // "void" as the return type, since destructors don't have return
1244 // types. We *always* have to do this, because GetTypeForDeclarator
1245 // will put in a result type of "int" when none was specified.
1246 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1247
1248 return isInvalid;
1249}
1250
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001251/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1252/// well-formednes of the conversion function declarator @p D with
1253/// type @p R. If there are any errors in the declarator, this routine
1254/// will emit diagnostics and return true. Otherwise, it will return
1255/// false. Either way, the type @p R will be updated to reflect a
1256/// well-formed type for the conversion operator.
1257bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1258 FunctionDecl::StorageClass& SC) {
1259 bool isInvalid = false;
1260
1261 // C++ [class.conv.fct]p1:
1262 // Neither parameter types nor return type can be specified. The
1263 // type of a conversion function (8.3.5) is “function taking no
1264 // parameter returning conversion-type-id.”
1265 if (SC == FunctionDecl::Static) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001266 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1267 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1268 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001269 isInvalid = true;
1270 SC = FunctionDecl::None;
1271 }
1272 if (D.getDeclSpec().hasTypeSpecifier()) {
1273 // Conversion functions don't have return types, but the parser will
1274 // happily parse something like:
1275 //
1276 // class X {
1277 // float operator bool();
1278 // };
1279 //
1280 // The return type will be changed later anyway.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001281 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1282 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1283 << SourceRange(D.getIdentifierLoc());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001284 }
1285
1286 // Make sure we don't have any parameters.
Douglas Gregor72564e72009-02-26 23:50:07 +00001287 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001288 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1289
1290 // Delete the parameters.
Chris Lattner1833a832009-01-20 21:06:38 +00001291 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001292 }
1293
1294 // Make sure the conversion function isn't variadic.
Douglas Gregor72564e72009-02-26 23:50:07 +00001295 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001296 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1297
1298 // C++ [class.conv.fct]p4:
1299 // The conversion-type-id shall not represent a function type nor
1300 // an array type.
1301 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1302 if (ConvType->isArrayType()) {
1303 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1304 ConvType = Context.getPointerType(ConvType);
1305 } else if (ConvType->isFunctionType()) {
1306 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1307 ConvType = Context.getPointerType(ConvType);
1308 }
1309
1310 // Rebuild the function type "R" without any parameters (in case any
1311 // of the errors above fired) and with the conversion type as the
1312 // return type.
1313 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor72564e72009-02-26 23:50:07 +00001314 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001315
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001316 // C++0x explicit conversion operators.
1317 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1318 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1319 diag::warn_explicit_conversion_functions)
1320 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1321
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001322 return isInvalid;
1323}
1324
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001325/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1326/// the declaration of the given C++ conversion function. This routine
1327/// is responsible for recording the conversion function in the C++
1328/// class, if possible.
1329Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1330 assert(Conversion && "Expected to receive a conversion function declaration");
1331
Douglas Gregor9d350972008-12-12 08:25:50 +00001332 // Set the lexical context of this conversion function
1333 Conversion->setLexicalDeclContext(CurContext);
1334
1335 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001336
1337 // Make sure we aren't redeclaring the conversion function.
1338 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001339
1340 // C++ [class.conv.fct]p1:
1341 // [...] A conversion function is never used to convert a
1342 // (possibly cv-qualified) object to the (possibly cv-qualified)
1343 // same object type (or a reference to it), to a (possibly
1344 // cv-qualified) base class of that type (or a reference to it),
1345 // or to (possibly cv-qualified) void.
1346 // FIXME: Suppress this warning if the conversion function ends up
1347 // being a virtual function that overrides a virtual function in a
1348 // base class.
1349 QualType ClassType
1350 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1351 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1352 ConvType = ConvTypeRef->getPointeeType();
1353 if (ConvType->isRecordType()) {
1354 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1355 if (ConvType == ClassType)
Chris Lattner5dc266a2008-11-20 06:13:02 +00001356 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001357 << ClassType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001358 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner5dc266a2008-11-20 06:13:02 +00001359 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001360 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001361 } else if (ConvType->isVoidType()) {
Chris Lattner5dc266a2008-11-20 06:13:02 +00001362 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattnerd1625842008-11-24 06:25:27 +00001363 << ClassType << ConvType;
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001364 }
1365
Douglas Gregor70316a02008-12-26 15:00:45 +00001366 if (Conversion->getPreviousDeclaration()) {
1367 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1368 for (OverloadedFunctionDecl::function_iterator
1369 Conv = Conversions->function_begin(),
1370 ConvEnd = Conversions->function_end();
1371 Conv != ConvEnd; ++Conv) {
1372 if (*Conv == Conversion->getPreviousDeclaration()) {
1373 *Conv = Conversion;
1374 return (DeclTy *)Conversion;
1375 }
1376 }
1377 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1378 } else
1379 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001380
1381 return (DeclTy *)Conversion;
1382}
1383
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001384//===----------------------------------------------------------------------===//
1385// Namespace Handling
1386//===----------------------------------------------------------------------===//
1387
1388/// ActOnStartNamespaceDef - This is called at the start of a namespace
1389/// definition.
1390Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1391 SourceLocation IdentLoc,
1392 IdentifierInfo *II,
1393 SourceLocation LBrace) {
1394 NamespaceDecl *Namespc =
1395 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1396 Namespc->setLBracLoc(LBrace);
1397
1398 Scope *DeclRegionScope = NamespcScope->getParent();
1399
1400 if (II) {
1401 // C++ [namespace.def]p2:
1402 // The identifier in an original-namespace-definition shall not have been
1403 // previously defined in the declarative region in which the
1404 // original-namespace-definition appears. The identifier in an
1405 // original-namespace-definition is the name of the namespace. Subsequently
1406 // in that declarative region, it is treated as an original-namespace-name.
1407
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001408 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1409 true);
Douglas Gregor44b43212008-12-11 16:49:14 +00001410
1411 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1412 // This is an extended namespace definition.
1413 // Attach this namespace decl to the chain of extended namespace
1414 // definitions.
1415 OrigNS->setNextNamespace(Namespc);
1416 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001417
Douglas Gregor44b43212008-12-11 16:49:14 +00001418 // Remove the previous declaration from the scope.
1419 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregore267ff32008-12-11 20:41:00 +00001420 IdResolver.RemoveDecl(OrigNS);
1421 DeclRegionScope->RemoveDecl(OrigNS);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001422 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001423 } else if (PrevDecl) {
1424 // This is an invalid name redefinition.
1425 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1426 << Namespc->getDeclName();
1427 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1428 Namespc->setInvalidDecl();
1429 // Continue on to push Namespc as current DeclContext and return it.
1430 }
1431
1432 PushOnScopeChains(Namespc, DeclRegionScope);
1433 } else {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001434 // FIXME: Handle anonymous namespaces
1435 }
1436
1437 // Although we could have an invalid decl (i.e. the namespace name is a
1438 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor44b43212008-12-11 16:49:14 +00001439 // FIXME: We should be able to push Namespc here, so that the
1440 // each DeclContext for the namespace has the declarations
1441 // that showed up in that particular namespace definition.
1442 PushDeclContext(NamespcScope, Namespc);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001443 return Namespc;
1444}
1445
1446/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1447/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1448void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1449 Decl *Dcl = static_cast<Decl *>(D);
1450 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1451 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1452 Namespc->setRBracLoc(RBrace);
1453 PopDeclContext();
1454}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001455
Douglas Gregorf780abc2008-12-30 03:27:21 +00001456Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1457 SourceLocation UsingLoc,
1458 SourceLocation NamespcLoc,
1459 const CXXScopeSpec &SS,
1460 SourceLocation IdentLoc,
1461 IdentifierInfo *NamespcName,
1462 AttributeList *AttrList) {
1463 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1464 assert(NamespcName && "Invalid NamespcName.");
1465 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001466 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregorf780abc2008-12-30 03:27:21 +00001467
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001468 UsingDirectiveDecl *UDir = 0;
Douglas Gregorf780abc2008-12-30 03:27:21 +00001469
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001470 // Lookup namespace name.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001471 LookupResult R = LookupParsedName(S, &SS, NamespcName,
1472 LookupNamespaceName, false);
1473 if (R.isAmbiguous()) {
1474 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1475 return 0;
1476 }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001477 if (NamedDecl *NS = R) {
Douglas Gregorf780abc2008-12-30 03:27:21 +00001478 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001479 // C++ [namespace.udir]p1:
1480 // A using-directive specifies that the names in the nominated
1481 // namespace can be used in the scope in which the
1482 // using-directive appears after the using-directive. During
1483 // unqualified name lookup (3.4.1), the names appear as if they
1484 // were declared in the nearest enclosing namespace which
1485 // contains both the using-directive and the nominated
1486 // namespace. [Note: in this context, “contains” means “contains
1487 // directly or indirectly”. ]
1488
1489 // Find enclosing context containing both using-directive and
1490 // nominated namespace.
1491 DeclContext *CommonAncestor = cast<DeclContext>(NS);
1492 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1493 CommonAncestor = CommonAncestor->getParent();
1494
1495 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1496 NamespcLoc, IdentLoc,
1497 cast<NamespaceDecl>(NS),
1498 CommonAncestor);
1499 PushUsingDirective(S, UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00001500 } else {
Chris Lattneread013e2009-01-06 07:24:29 +00001501 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregorf780abc2008-12-30 03:27:21 +00001502 }
1503
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001504 // FIXME: We ignore attributes for now.
Douglas Gregorf780abc2008-12-30 03:27:21 +00001505 delete AttrList;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001506 return UDir;
1507}
1508
1509void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1510 // If scope has associated entity, then using directive is at namespace
1511 // or translation unit scope. We add UsingDirectiveDecls, into
1512 // it's lookup structure.
1513 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1514 Ctx->addDecl(UDir);
1515 else
1516 // Otherwise it is block-sope. using-directives will affect lookup
1517 // only to the end of scope.
1518 S->PushUsingDirective(UDir);
Douglas Gregorf780abc2008-12-30 03:27:21 +00001519}
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001520
1521/// AddCXXDirectInitializerToDecl - This action is called immediately after
1522/// ActOnDeclarator, when a C++ direct initializer is present.
1523/// e.g: "int x(1);"
1524void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1525 ExprTy **ExprTys, unsigned NumExprs,
1526 SourceLocation *CommaLocs,
1527 SourceLocation RParenLoc) {
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001528 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001529 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001530
1531 // If there is no declaration, there was an error parsing it. Just ignore
1532 // the initializer.
1533 if (RealDecl == 0) {
Ted Kremenek15f61392008-10-06 20:35:04 +00001534 for (unsigned i = 0; i != NumExprs; ++i)
Ted Kremenek8189cde2009-02-07 01:47:29 +00001535 static_cast<Expr *>(ExprTys[i])->Destroy(Context);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001536 return;
1537 }
1538
1539 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1540 if (!VDecl) {
1541 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1542 RealDecl->setInvalidDecl();
1543 return;
1544 }
1545
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001546 // We will treat direct-initialization as a copy-initialization:
1547 // int x(1); -as-> int x = 1;
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001548 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1549 //
1550 // Clients that want to distinguish between the two forms, can check for
1551 // direct initializer using VarDecl::hasCXXDirectInitializer().
1552 // A major benefit is that clients that don't particularly care about which
1553 // exactly form was it (like the CodeGen) can handle both cases without
1554 // special case code.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001555
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001556 // C++ 8.5p11:
1557 // The form of initialization (using parentheses or '=') is generally
1558 // insignificant, but does matter when the entity being initialized has a
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001559 // class type.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001560 QualType DeclInitType = VDecl->getType();
1561 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1562 DeclInitType = Array->getElementType();
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001563
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001564 if (VDecl->getType()->isRecordType()) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001565 CXXConstructorDecl *Constructor
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001566 = PerformInitializationByConstructor(DeclInitType,
1567 (Expr **)ExprTys, NumExprs,
1568 VDecl->getLocation(),
1569 SourceRange(VDecl->getLocation(),
1570 RParenLoc),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001571 VDecl->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001572 IK_Direct);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001573 if (!Constructor) {
1574 RealDecl->setInvalidDecl();
1575 }
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001576
1577 // Let clients know that initialization was done with a direct
1578 // initializer.
1579 VDecl->setCXXDirectInitializer(true);
1580
1581 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1582 // the initializer.
Argyrios Kyrtzidis06ad1f52008-10-06 18:37:09 +00001583 return;
1584 }
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001585
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001586 if (NumExprs > 1) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001587 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1588 << SourceRange(VDecl->getLocation(), RParenLoc);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001589 RealDecl->setInvalidDecl();
1590 return;
1591 }
1592
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001593 // Let clients know that initialization was done with a direct initializer.
1594 VDecl->setCXXDirectInitializer(true);
Argyrios Kyrtzidisce8e2922008-10-06 23:08:37 +00001595
1596 assert(NumExprs == 1 && "Expected 1 expression");
1597 // Set the init expression, handles conversions.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001598 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
Argyrios Kyrtzidis73a0d882008-10-06 17:10:33 +00001599}
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001600
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001601/// PerformInitializationByConstructor - Perform initialization by
1602/// constructor (C++ [dcl.init]p14), which may occur as part of
1603/// direct-initialization or copy-initialization. We are initializing
1604/// an object of type @p ClassType with the given arguments @p
1605/// Args. @p Loc is the location in the source code where the
1606/// initializer occurs (e.g., a declaration, member initializer,
1607/// functional cast, etc.) while @p Range covers the whole
1608/// initialization. @p InitEntity is the entity being initialized,
1609/// which may by the name of a declaration or a type. @p Kind is the
1610/// kind of initialization we're performing, which affects whether
1611/// explicit constructors will be considered. When successful, returns
Douglas Gregor18fe5682008-11-03 20:45:27 +00001612/// the constructor that will be used to perform the initialization;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001613/// when the initialization fails, emits a diagnostic and returns
1614/// null.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001615CXXConstructorDecl *
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001616Sema::PerformInitializationByConstructor(QualType ClassType,
1617 Expr **Args, unsigned NumArgs,
1618 SourceLocation Loc, SourceRange Range,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001619 DeclarationName InitEntity,
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001620 InitializationKind Kind) {
Douglas Gregor18fe5682008-11-03 20:45:27 +00001621 const RecordType *ClassRec = ClassType->getAsRecordType();
1622 assert(ClassRec && "Can only initialize a class type here");
1623
1624 // C++ [dcl.init]p14:
1625 //
1626 // If the initialization is direct-initialization, or if it is
1627 // copy-initialization where the cv-unqualified version of the
1628 // source type is the same class as, or a derived class of, the
1629 // class of the destination, constructors are considered. The
1630 // applicable constructors are enumerated (13.3.1.3), and the
1631 // best one is chosen through overload resolution (13.3). The
1632 // constructor so selected is called to initialize the object,
1633 // with the initializer expression(s) as its argument(s). If no
1634 // constructor applies, or the overload resolution is ambiguous,
1635 // the initialization is ill-formed.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001636 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1637 OverloadCandidateSet CandidateSet;
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001638
1639 // Add constructors to the overload set.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001640 DeclarationName ConstructorName
1641 = Context.DeclarationNames.getCXXConstructorName(
1642 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001643 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroff0701bbb2009-01-08 17:28:14 +00001644 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001645 Con != ConEnd; ++Con) {
1646 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001647 if ((Kind == IK_Direct) ||
1648 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1649 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1650 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1651 }
1652
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001653 // FIXME: When we decide not to synthesize the implicitly-declared
1654 // constructors, we'll need to make them appear here.
1655
Douglas Gregor18fe5682008-11-03 20:45:27 +00001656 OverloadCandidateSet::iterator Best;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001657 switch (BestViableFunction(CandidateSet, Best)) {
1658 case OR_Success:
1659 // We found a constructor. Return it.
1660 return cast<CXXConstructorDecl>(Best->Function);
1661
1662 case OR_No_Viable_Function:
Douglas Gregor87fd7032009-02-02 17:43:21 +00001663 if (InitEntity)
1664 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00001665 << InitEntity << Range;
Douglas Gregor87fd7032009-02-02 17:43:21 +00001666 else
1667 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4330d652009-02-17 07:29:20 +00001668 << ClassType << Range;
Sebastian Redle4c452c2008-11-22 13:44:36 +00001669 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001670 return 0;
1671
1672 case OR_Ambiguous:
Douglas Gregor87fd7032009-02-02 17:43:21 +00001673 if (InitEntity)
1674 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1675 else
1676 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001677 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1678 return 0;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001679
1680 case OR_Deleted:
1681 if (InitEntity)
1682 Diag(Loc, diag::err_ovl_deleted_init)
1683 << Best->Function->isDeleted()
1684 << InitEntity << Range;
1685 else
1686 Diag(Loc, diag::err_ovl_deleted_init)
1687 << Best->Function->isDeleted()
1688 << InitEntity << Range;
1689 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1690 return 0;
Douglas Gregor18fe5682008-11-03 20:45:27 +00001691 }
1692
1693 return 0;
1694}
1695
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001696/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1697/// determine whether they are reference-related,
1698/// reference-compatible, reference-compatible with added
1699/// qualification, or incompatible, for use in C++ initialization by
1700/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1701/// type, and the first type (T1) is the pointee type of the reference
1702/// type being initialized.
1703Sema::ReferenceCompareResult
Douglas Gregor15da57e2008-10-29 02:00:59 +00001704Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1705 bool& DerivedToBase) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001706 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1707 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1708
1709 T1 = Context.getCanonicalType(T1);
1710 T2 = Context.getCanonicalType(T2);
1711 QualType UnqualT1 = T1.getUnqualifiedType();
1712 QualType UnqualT2 = T2.getUnqualifiedType();
1713
1714 // C++ [dcl.init.ref]p4:
1715 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1716 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1717 // T1 is a base class of T2.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001718 if (UnqualT1 == UnqualT2)
1719 DerivedToBase = false;
1720 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1721 DerivedToBase = true;
1722 else
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001723 return Ref_Incompatible;
1724
1725 // At this point, we know that T1 and T2 are reference-related (at
1726 // least).
1727
1728 // C++ [dcl.init.ref]p4:
1729 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1730 // reference-related to T2 and cv1 is the same cv-qualification
1731 // as, or greater cv-qualification than, cv2. For purposes of
1732 // overload resolution, cases for which cv1 is greater
1733 // cv-qualification than cv2 are identified as
1734 // reference-compatible with added qualification (see 13.3.3.2).
1735 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1736 return Ref_Compatible;
1737 else if (T1.isMoreQualifiedThan(T2))
1738 return Ref_Compatible_With_Added_Qualification;
1739 else
1740 return Ref_Related;
1741}
1742
1743/// CheckReferenceInit - Check the initialization of a reference
1744/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1745/// the initializer (either a simple initializer or an initializer
Douglas Gregor3205a782008-10-29 23:31:03 +00001746/// list), and DeclType is the type of the declaration. When ICS is
1747/// non-null, this routine will compute the implicit conversion
1748/// sequence according to C++ [over.ics.ref] and will not produce any
1749/// diagnostics; when ICS is null, it will emit diagnostics when any
1750/// errors are found. Either way, a return value of true indicates
1751/// that there was a failure, a return value of false indicates that
1752/// the reference initialization succeeded.
Douglas Gregor225c41e2008-11-03 19:09:14 +00001753///
1754/// When @p SuppressUserConversions, user-defined conversions are
1755/// suppressed.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001756/// When @p AllowExplicit, we also permit explicit user-defined
1757/// conversion functions.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001758bool
1759Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregor225c41e2008-11-03 19:09:14 +00001760 ImplicitConversionSequence *ICS,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001761 bool SuppressUserConversions,
1762 bool AllowExplicit) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001763 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1764
1765 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1766 QualType T2 = Init->getType();
1767
Douglas Gregor904eed32008-11-10 20:40:00 +00001768 // If the initializer is the address of an overloaded function, try
1769 // to resolve the overloaded function. If all goes well, T2 is the
1770 // type of the resulting function.
1771 if (T2->isOverloadType()) {
1772 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1773 ICS != 0);
1774 if (Fn) {
1775 // Since we're performing this reference-initialization for
1776 // real, update the initializer with the resulting function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001777 if (!ICS) {
1778 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
1779 return true;
1780
Douglas Gregor904eed32008-11-10 20:40:00 +00001781 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001782 }
Douglas Gregor904eed32008-11-10 20:40:00 +00001783
1784 T2 = Fn->getType();
1785 }
1786 }
1787
Douglas Gregor15da57e2008-10-29 02:00:59 +00001788 // Compute some basic properties of the types and the initializer.
1789 bool DerivedToBase = false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001790 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor15da57e2008-10-29 02:00:59 +00001791 ReferenceCompareResult RefRelationship
1792 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1793
1794 // Most paths end in a failed conversion.
1795 if (ICS)
1796 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001797
1798 // C++ [dcl.init.ref]p5:
1799 // A reference to type “cv1 T1” is initialized by an expression
1800 // of type “cv2 T2” as follows:
1801
1802 // -- If the initializer expression
1803
1804 bool BindsDirectly = false;
1805 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1806 // reference-compatible with “cv2 T2,” or
Douglas Gregor15da57e2008-10-29 02:00:59 +00001807 //
1808 // Note that the bit-field check is skipped if we are just computing
1809 // the implicit conversion sequence (C++ [over.best.ics]p2).
1810 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1811 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001812 BindsDirectly = true;
1813
Douglas Gregor15da57e2008-10-29 02:00:59 +00001814 if (ICS) {
1815 // C++ [over.ics.ref]p1:
1816 // When a parameter of reference type binds directly (8.5.3)
1817 // to an argument expression, the implicit conversion sequence
1818 // is the identity conversion, unless the argument expression
1819 // has a type that is a derived class of the parameter type,
1820 // in which case the implicit conversion sequence is a
1821 // derived-to-base Conversion (13.3.3.1).
1822 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1823 ICS->Standard.First = ICK_Identity;
1824 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1825 ICS->Standard.Third = ICK_Identity;
1826 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1827 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001828 ICS->Standard.ReferenceBinding = true;
1829 ICS->Standard.DirectBinding = true;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001830
1831 // Nothing more to do: the inaccessibility/ambiguity check for
1832 // derived-to-base conversions is suppressed when we're
1833 // computing the implicit conversion sequence (C++
1834 // [over.best.ics]p2).
1835 return false;
1836 } else {
1837 // Perform the conversion.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001838 // FIXME: Binding to a subobject of the lvalue is going to require
1839 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001840 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001841 }
1842 }
1843
1844 // -- has a class type (i.e., T2 is a class type) and can be
1845 // implicitly converted to an lvalue of type “cv3 T3,”
1846 // where “cv1 T1” is reference-compatible with “cv3 T3”
1847 // 92) (this conversion is selected by enumerating the
1848 // applicable conversion functions (13.3.1.6) and choosing
1849 // the best one through overload resolution (13.3)),
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001850 if (!SuppressUserConversions && T2->isRecordType()) {
1851 // FIXME: Look for conversions in base classes!
1852 CXXRecordDecl *T2RecordDecl
1853 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001854
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001855 OverloadCandidateSet CandidateSet;
1856 OverloadedFunctionDecl *Conversions
1857 = T2RecordDecl->getConversionFunctions();
1858 for (OverloadedFunctionDecl::function_iterator Func
1859 = Conversions->function_begin();
1860 Func != Conversions->function_end(); ++Func) {
1861 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1862
1863 // If the conversion function doesn't return a reference type,
1864 // it can't be considered for this conversion.
1865 // FIXME: This will change when we support rvalue references.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001866 if (Conv->getConversionType()->isReferenceType() &&
1867 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001868 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1869 }
1870
1871 OverloadCandidateSet::iterator Best;
1872 switch (BestViableFunction(CandidateSet, Best)) {
1873 case OR_Success:
1874 // This is a direct binding.
1875 BindsDirectly = true;
1876
1877 if (ICS) {
1878 // C++ [over.ics.ref]p1:
1879 //
1880 // [...] If the parameter binds directly to the result of
1881 // applying a conversion function to the argument
1882 // expression, the implicit conversion sequence is a
1883 // user-defined conversion sequence (13.3.3.1.2), with the
1884 // second standard conversion sequence either an identity
1885 // conversion or, if the conversion function returns an
1886 // entity of a type that is a derived class of the parameter
1887 // type, a derived-to-base Conversion.
1888 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1889 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1890 ICS->UserDefined.After = Best->FinalConversion;
1891 ICS->UserDefined.ConversionFunction = Best->Function;
1892 assert(ICS->UserDefined.After.ReferenceBinding &&
1893 ICS->UserDefined.After.DirectBinding &&
1894 "Expected a direct reference binding!");
1895 return false;
1896 } else {
1897 // Perform the conversion.
1898 // FIXME: Binding to a subobject of the lvalue is going to require
1899 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001900 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001901 }
1902 break;
1903
1904 case OR_Ambiguous:
1905 assert(false && "Ambiguous reference binding conversions not implemented.");
1906 return true;
1907
1908 case OR_No_Viable_Function:
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001909 case OR_Deleted:
1910 // There was no suitable conversion, or we found a deleted
1911 // conversion; continue with other checks.
Douglas Gregorcb9b9772008-11-10 16:14:15 +00001912 break;
1913 }
1914 }
1915
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001916 if (BindsDirectly) {
1917 // C++ [dcl.init.ref]p4:
1918 // [...] In all cases where the reference-related or
1919 // reference-compatible relationship of two types is used to
1920 // establish the validity of a reference binding, and T1 is a
1921 // base class of T2, a program that necessitates such a binding
1922 // is ill-formed if T1 is an inaccessible (clause 11) or
1923 // ambiguous (10.2) base class of T2.
1924 //
1925 // Note that we only check this condition when we're allowed to
1926 // complain about errors, because we should not be checking for
1927 // ambiguity (or inaccessibility) unless the reference binding
1928 // actually happens.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001929 if (DerivedToBase)
1930 return CheckDerivedToBaseConversion(T2, T1,
1931 Init->getSourceRange().getBegin(),
1932 Init->getSourceRange());
1933 else
1934 return false;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001935 }
1936
1937 // -- Otherwise, the reference shall be to a non-volatile const
1938 // type (i.e., cv1 shall be const).
1939 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor15da57e2008-10-29 02:00:59 +00001940 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001941 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001942 diag::err_not_reference_to_const_init)
Chris Lattnerd1625842008-11-24 06:25:27 +00001943 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1944 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001945 return true;
1946 }
1947
1948 // -- If the initializer expression is an rvalue, with T2 a
1949 // class type, and “cv1 T1” is reference-compatible with
1950 // “cv2 T2,” the reference is bound in one of the
1951 // following ways (the choice is implementation-defined):
1952 //
1953 // -- The reference is bound to the object represented by
1954 // the rvalue (see 3.10) or to a sub-object within that
1955 // object.
1956 //
1957 // -- A temporary of type “cv1 T2” [sic] is created, and
1958 // a constructor is called to copy the entire rvalue
1959 // object into the temporary. The reference is bound to
1960 // the temporary or to a sub-object within the
1961 // temporary.
1962 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001963 // The constructor that would be used to make the copy
1964 // shall be callable whether or not the copy is actually
1965 // done.
1966 //
1967 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1968 // freedom, so we will always take the first option and never build
1969 // a temporary in this case. FIXME: We will, however, have to check
1970 // for the presence of a copy constructor in C++98/03 mode.
1971 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor15da57e2008-10-29 02:00:59 +00001972 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1973 if (ICS) {
1974 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1975 ICS->Standard.First = ICK_Identity;
1976 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1977 ICS->Standard.Third = ICK_Identity;
1978 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1979 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00001980 ICS->Standard.ReferenceBinding = true;
1981 ICS->Standard.DirectBinding = false;
Douglas Gregor15da57e2008-10-29 02:00:59 +00001982 } else {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001983 // FIXME: Binding to a subobject of the rvalue is going to require
1984 // more AST annotation than this.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001985 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001986 }
1987 return false;
1988 }
1989
1990 // -- Otherwise, a temporary of type “cv1 T1” is created and
1991 // initialized from the initializer expression using the
1992 // rules for a non-reference copy initialization (8.5). The
1993 // reference is then bound to the temporary. If T1 is
1994 // reference-related to T2, cv1 must be the same
1995 // cv-qualification as, or greater cv-qualification than,
1996 // cv2; otherwise, the program is ill-formed.
1997 if (RefRelationship == Ref_Related) {
1998 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1999 // we would be reference-compatible or reference-compatible with
2000 // added qualification. But that wasn't the case, so the reference
2001 // initialization fails.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002002 if (!ICS)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002003 Diag(Init->getSourceRange().getBegin(),
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002004 diag::err_reference_init_drops_quals)
Chris Lattnerd1625842008-11-24 06:25:27 +00002005 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2006 << T2 << Init->getSourceRange();
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002007 return true;
2008 }
2009
Douglas Gregor734d9862009-01-30 23:27:23 +00002010 // If at least one of the types is a class type, the types are not
2011 // related, and we aren't allowed any user conversions, the
2012 // reference binding fails. This case is important for breaking
2013 // recursion, since TryImplicitConversion below will attempt to
2014 // create a temporary through the use of a copy constructor.
2015 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2016 (T1->isRecordType() || T2->isRecordType())) {
2017 if (!ICS)
2018 Diag(Init->getSourceRange().getBegin(),
2019 diag::err_typecheck_convert_incompatible)
2020 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2021 return true;
2022 }
2023
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002024 // Actually try to convert the initializer to T1.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002025 if (ICS) {
2026 /// C++ [over.ics.ref]p2:
2027 ///
2028 /// When a parameter of reference type is not bound directly to
2029 /// an argument expression, the conversion sequence is the one
2030 /// required to convert the argument expression to the
2031 /// underlying type of the reference according to
2032 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
2033 /// to copy-initializing a temporary of the underlying type with
2034 /// the argument expression. Any difference in top-level
2035 /// cv-qualification is subsumed by the initialization itself
2036 /// and does not constitute a conversion.
Douglas Gregor225c41e2008-11-03 19:09:14 +00002037 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor15da57e2008-10-29 02:00:59 +00002038 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2039 } else {
Douglas Gregor45920e82008-12-19 17:40:08 +00002040 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor15da57e2008-10-29 02:00:59 +00002041 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002042}
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002043
2044/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2045/// of this overloaded operator is well-formed. If so, returns false;
2046/// otherwise, emits appropriate diagnostics and returns true.
2047bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002048 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002049 "Expected an overloaded operator declaration");
2050
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002051 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2052
2053 // C++ [over.oper]p5:
2054 // The allocation and deallocation functions, operator new,
2055 // operator new[], operator delete and operator delete[], are
2056 // described completely in 3.7.3. The attributes and restrictions
2057 // found in the rest of this subclause do not apply to them unless
2058 // explicitly stated in 3.7.3.
2059 // FIXME: Write a separate routine for checking this. For now, just
2060 // allow it.
2061 if (Op == OO_New || Op == OO_Array_New ||
2062 Op == OO_Delete || Op == OO_Array_Delete)
2063 return false;
2064
2065 // C++ [over.oper]p6:
2066 // An operator function shall either be a non-static member
2067 // function or be a non-member function and have at least one
2068 // parameter whose type is a class, a reference to a class, an
2069 // enumeration, or a reference to an enumeration.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002070 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2071 if (MethodDecl->isStatic())
2072 return Diag(FnDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002073 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002074 } else {
2075 bool ClassOrEnumParam = false;
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002076 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2077 ParamEnd = FnDecl->param_end();
2078 Param != ParamEnd; ++Param) {
2079 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002080 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2081 ClassOrEnumParam = true;
2082 break;
2083 }
2084 }
2085
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002086 if (!ClassOrEnumParam)
2087 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002088 diag::err_operator_overload_needs_class_or_enum)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002089 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002090 }
2091
2092 // C++ [over.oper]p8:
2093 // An operator function cannot have default arguments (8.3.6),
2094 // except where explicitly stated below.
2095 //
2096 // Only the function-call operator allows default arguments
2097 // (C++ [over.call]p1).
2098 if (Op != OO_Call) {
2099 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2100 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor61366e92008-12-24 00:01:03 +00002101 if ((*Param)->hasUnparsedDefaultArg())
2102 return Diag((*Param)->getLocation(),
2103 diag::err_operator_overload_default_arg)
2104 << FnDecl->getDeclName();
2105 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002106 return Diag((*Param)->getLocation(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002107 diag::err_operator_overload_default_arg)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002108 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002109 }
2110 }
2111
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002112 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2113 { false, false, false }
2114#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2115 , { Unary, Binary, MemberOnly }
2116#include "clang/Basic/OperatorKinds.def"
2117 };
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002118
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002119 bool CanBeUnaryOperator = OperatorUses[Op][0];
2120 bool CanBeBinaryOperator = OperatorUses[Op][1];
2121 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002122
2123 // C++ [over.oper]p8:
2124 // [...] Operator functions cannot have more or fewer parameters
2125 // than the number required for the corresponding operator, as
2126 // described in the rest of this subclause.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002127 unsigned NumParams = FnDecl->getNumParams()
2128 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002129 if (Op != OO_Call &&
2130 ((NumParams == 1 && !CanBeUnaryOperator) ||
2131 (NumParams == 2 && !CanBeBinaryOperator) ||
2132 (NumParams < 1) || (NumParams > 2))) {
2133 // We have the wrong number of parameters.
Chris Lattner416e46f2008-11-21 07:57:12 +00002134 unsigned ErrorKind;
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002135 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002136 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002137 } else if (CanBeUnaryOperator) {
Chris Lattner416e46f2008-11-21 07:57:12 +00002138 ErrorKind = 0; // 0 -> unary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002139 } else {
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002140 assert(CanBeBinaryOperator &&
2141 "All non-call overloaded operators are unary or binary!");
Chris Lattner416e46f2008-11-21 07:57:12 +00002142 ErrorKind = 1; // 1 -> binary
Douglas Gregor02bcd4c2008-11-10 13:38:07 +00002143 }
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002144
Chris Lattner416e46f2008-11-21 07:57:12 +00002145 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002146 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002147 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00002148
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002149 // Overloaded operators other than operator() cannot be variadic.
2150 if (Op != OO_Call &&
Douglas Gregor72564e72009-02-26 23:50:07 +00002151 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002152 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002153 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002154 }
2155
2156 // Some operators must be non-static member functions.
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002157 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2158 return Diag(FnDecl->getLocation(),
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002159 diag::err_operator_overload_must_be_member)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002160 << FnDecl->getDeclName();
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002161 }
2162
2163 // C++ [over.inc]p1:
2164 // The user-defined function called operator++ implements the
2165 // prefix and postfix ++ operator. If this function is a member
2166 // function with no parameters, or a non-member function with one
2167 // parameter of class or enumeration type, it defines the prefix
2168 // increment operator ++ for objects of that type. If the function
2169 // is a member function with one parameter (which shall be of type
2170 // int) or a non-member function with two parameters (the second
2171 // of which shall be of type int), it defines the postfix
2172 // increment operator ++ for objects of that type.
2173 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2174 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2175 bool ParamIsInt = false;
2176 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2177 ParamIsInt = BT->getKind() == BuiltinType::Int;
2178
Chris Lattneraf7ae4e2008-11-21 07:50:02 +00002179 if (!ParamIsInt)
2180 return Diag(LastParam->getLocation(),
2181 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattnerd1625842008-11-24 06:25:27 +00002182 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002183 }
2184
Sebastian Redl64b45f72009-01-05 20:52:13 +00002185 // Notify the class if it got an assignment operator.
2186 if (Op == OO_Equal) {
2187 // Would have returned earlier otherwise.
2188 assert(isa<CXXMethodDecl>(FnDecl) &&
2189 "Overloaded = not member, but not filtered.");
2190 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2191 Method->getParent()->addedAssignmentOperator(Context, Method);
2192 }
2193
Douglas Gregor43c7bad2008-11-17 16:14:12 +00002194 return false;
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00002195}
Chris Lattner5a003a42008-12-17 07:09:26 +00002196
Douglas Gregor074149e2009-01-05 19:45:36 +00002197/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2198/// linkage specification, including the language and (if present)
2199/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2200/// the location of the language string literal, which is provided
2201/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2202/// the '{' brace. Otherwise, this linkage specification does not
2203/// have any braces.
2204Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2205 SourceLocation ExternLoc,
2206 SourceLocation LangLoc,
2207 const char *Lang,
2208 unsigned StrSize,
2209 SourceLocation LBraceLoc) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00002210 LinkageSpecDecl::LanguageIDs Language;
2211 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2212 Language = LinkageSpecDecl::lang_c;
2213 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2214 Language = LinkageSpecDecl::lang_cxx;
2215 else {
Douglas Gregor074149e2009-01-05 19:45:36 +00002216 Diag(LangLoc, diag::err_bad_language);
Chris Lattnercc98eac2008-12-17 07:13:27 +00002217 return 0;
2218 }
2219
2220 // FIXME: Add all the various semantics of linkage specifications
2221
Douglas Gregor074149e2009-01-05 19:45:36 +00002222 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2223 LangLoc, Language,
2224 LBraceLoc.isValid());
Douglas Gregor482b77d2009-01-12 23:27:07 +00002225 CurContext->addDecl(D);
Douglas Gregor074149e2009-01-05 19:45:36 +00002226 PushDeclContext(S, D);
2227 return D;
Chris Lattnercc98eac2008-12-17 07:13:27 +00002228}
2229
Douglas Gregor074149e2009-01-05 19:45:36 +00002230/// ActOnFinishLinkageSpecification - Completely the definition of
2231/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2232/// valid, it's the position of the closing '}' brace in a linkage
2233/// specification that uses braces.
2234Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2235 DeclTy *LinkageSpec,
2236 SourceLocation RBraceLoc) {
2237 if (LinkageSpec)
2238 PopDeclContext();
2239 return LinkageSpec;
Chris Lattner5a003a42008-12-17 07:09:26 +00002240}
2241
Sebastian Redl4b07b292008-12-22 19:15:10 +00002242/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2243/// handler.
2244Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2245{
2246 QualType ExDeclType = GetTypeForDeclarator(D, S);
2247 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2248
2249 bool Invalid = false;
2250
2251 // Arrays and functions decay.
2252 if (ExDeclType->isArrayType())
2253 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2254 else if (ExDeclType->isFunctionType())
2255 ExDeclType = Context.getPointerType(ExDeclType);
2256
2257 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2258 // The exception-declaration shall not denote a pointer or reference to an
2259 // incomplete type, other than [cv] void*.
2260 QualType BaseType = ExDeclType;
2261 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002262 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002263 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2264 BaseType = Ptr->getPointeeType();
2265 Mode = 1;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002266 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002267 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2268 BaseType = Ref->getPointeeType();
2269 Mode = 2;
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002270 DK = diag::err_catch_incomplete_ref;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002271 }
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002272 if ((Mode == 0 || !BaseType->isVoidType()) &&
2273 DiagnoseIncompleteType(Begin, BaseType, DK))
Sebastian Redl4b07b292008-12-22 19:15:10 +00002274 Invalid = true;
Sebastian Redl4b07b292008-12-22 19:15:10 +00002275
Sebastian Redl8351da02008-12-22 21:35:02 +00002276 // FIXME: Need to test for ability to copy-construct and destroy the
2277 // exception variable.
2278 // FIXME: Need to check for abstract classes.
2279
Sebastian Redl4b07b292008-12-22 19:15:10 +00002280 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002281 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl4b07b292008-12-22 19:15:10 +00002282 // The scope should be freshly made just for us. There is just no way
2283 // it contains any previous declaration.
2284 assert(!S->isDeclScope(PrevDecl));
2285 if (PrevDecl->isTemplateParameter()) {
2286 // Maybe we will complain about the shadowed template parameter.
2287 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2288
2289 }
2290 }
2291
2292 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002293 II, ExDeclType, VarDecl::None, Begin);
Sebastian Redl4b07b292008-12-22 19:15:10 +00002294 if (D.getInvalidType() || Invalid)
2295 ExDecl->setInvalidDecl();
2296
2297 if (D.getCXXScopeSpec().isSet()) {
2298 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2299 << D.getCXXScopeSpec().getRange();
2300 ExDecl->setInvalidDecl();
2301 }
2302
2303 // Add the exception declaration into this scope.
2304 S->AddDecl(ExDecl);
2305 if (II)
2306 IdResolver.AddDecl(ExDecl);
2307
2308 ProcessDeclAttributes(ExDecl, D);
2309 return ExDecl;
2310}