blob: bedea3a7cd7096d3c33c9a173f1b2eb7c4a33c5f [file] [log] [blame]
Chris Lattnerac7b83a2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregora65e8dd2008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor05904022008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Parse/DeclSpec.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Chris Lattner97316c02008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000025#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner97316c02008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattnerb1856db2008-04-12 23:52:44 +000033namespace {
34 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
35 /// the default argument of a parameter to determine whether it
36 /// contains any ill-formed subexpressions. For example, this will
37 /// diagnose the use of local variables or parameters within the
38 /// default argument expression.
39 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000043
Chris Lattnerb1856db2008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000047
Chris Lattnerb1856db2008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000051 };
Chris Lattner97316c02008-04-10 02:22:51 +000052
Chris Lattnerb1856db2008-04-12 23:52:44 +000053 /// VisitExpr - Visit all of the children of this expression.
54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
55 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000056 for (Stmt::child_iterator I = Node->child_begin(),
57 E = Node->child_end(); I != E; ++I)
58 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000060 }
61
Chris Lattnerb1856db2008-04-12 23:52:44 +000062 /// VisitDeclRefExpr - Visit a reference to a declaration, to
63 /// determine whether this declaration can be used in the default
64 /// argument expression.
65 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000067 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
68 // C++ [dcl.fct.default]p9
69 // Default arguments are evaluated each time the function is
70 // called. The order of evaluation of function arguments is
71 // unspecified. Consequently, parameters of a function shall not
72 // be used in default argument expressions, even if they are not
73 // evaluated. Parameters of a function declared before a default
74 // argument expression are in scope and can hide namespace and
75 // class member names.
76 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000077 diag::err_param_default_argument_references_param)
Chris Lattnerb1753422008-11-23 21:45:46 +000078 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff72a6ebc2008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000083 if (VDecl->isBlockVarDecl())
84 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000085 diag::err_param_default_argument_references_local)
Chris Lattnerb1753422008-11-23 21:45:46 +000086 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +000087 }
Chris Lattner97316c02008-04-10 02:22:51 +000088
Douglas Gregor3c246952008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000091
Douglas Gregora5b022a2008-11-04 14:32:21 +000092 /// VisitCXXThisExpr - Visit a C++ "this" expression.
93 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
94 // C++ [dcl.fct.default]p8:
95 // The keyword this shall not be used in a default argument of a
96 // member function.
97 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000098 diag::err_param_default_argument_references_this)
99 << ThisE->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +0000100 }
Chris Lattner97316c02008-04-10 02:22:51 +0000101}
102
103/// ActOnParamDefaultArgument - Check whether the default argument
104/// provided for a function parameter is well-formed. If so, attach it
105/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000106void
107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
108 ExprTy *defarg) {
109 ParmVarDecl *Param = (ParmVarDecl *)param;
Ted Kremenek0c97e042009-02-07 01:47:29 +0000110 ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000111 QualType ParamType = Param->getType();
112
113 // Default arguments are only permitted in C++
114 if (!getLangOptions().CPlusPlus) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000115 Diag(EqualLoc, diag::err_param_default_argument)
116 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000117 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000118 return;
119 }
120
121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000127 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000128 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
129 EqualLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000130 Param->getDeclName(),
131 /*DirectInit=*/false);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000132 if (DefaultArgPtr != DefaultArg.get()) {
133 DefaultArg.take();
134 DefaultArg.reset(DefaultArgPtr);
135 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000136 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000137 return;
138 }
139
Chris Lattner97316c02008-04-10 02:22:51 +0000140 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000141 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000142 if (DefaultArgChecker.Visit(DefaultArg.get())) {
143 Param->setInvalidDecl();
Chris Lattner97316c02008-04-10 02:22:51 +0000144 return;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000145 }
Chris Lattner97316c02008-04-10 02:22:51 +0000146
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000147 // Okay: add the default argument to the parameter
148 Param->setDefaultArg(DefaultArg.take());
149}
150
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000151/// ActOnParamUnparsedDefaultArgument - We've seen a default
152/// argument for a function parameter, but we can't parse it yet
153/// because we're inside a class definition. Note that this default
154/// argument will be parsed later.
155void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param,
156 SourceLocation EqualLoc) {
157 ParmVarDecl *Param = (ParmVarDecl*)param;
158 if (Param)
159 Param->setUnparsedDefaultArg();
160}
161
Douglas Gregor605de8d2008-12-16 21:30:33 +0000162/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
163/// the default argument for the parameter param failed.
164void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
165 ((ParmVarDecl*)param)->setInvalidDecl();
166}
167
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000168/// CheckExtraCXXDefaultArguments - Check for any extra default
169/// arguments in the declarator, which is not a function declaration
170/// or definition and therefore is not permitted to have default
171/// arguments. This routine should be invoked for every declarator
172/// that is not a function declaration or definition.
173void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
174 // C++ [dcl.fct.default]p3
175 // A default argument expression shall be specified only in the
176 // parameter-declaration-clause of a function declaration or in a
177 // template-parameter (14.1). It shall not be specified for a
178 // parameter pack. If it is specified in a
179 // parameter-declaration-clause, it shall not occur within a
180 // declarator or abstract-declarator of a parameter-declaration.
181 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
182 DeclaratorChunk &chunk = D.getTypeObject(i);
183 if (chunk.Kind == DeclaratorChunk::Function) {
184 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
185 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000186 if (Param->hasUnparsedDefaultArg()) {
187 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000188 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
189 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
190 delete Toks;
191 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000192 } else if (Param->getDefaultArg()) {
193 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
194 << Param->getDefaultArg()->getSourceRange();
195 Param->setDefaultArg(0);
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000196 }
197 }
198 }
199 }
200}
201
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000202// MergeCXXFunctionDecl - Merge two declarations of the same C++
203// function, once we already know that they have the same
Douglas Gregor083c23e2009-02-16 17:45:42 +0000204// type. Subroutine of MergeFunctionDecl. Returns true if there was an
205// error, false otherwise.
206bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
207 bool Invalid = false;
208
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000209 // C++ [dcl.fct.default]p4:
210 //
211 // For non-template functions, default arguments can be added in
212 // later declarations of a function in the same
213 // scope. Declarations in different scopes have completely
214 // distinct sets of default arguments. That is, declarations in
215 // inner scopes do not acquire default arguments from
216 // declarations in outer scopes, and vice versa. In a given
217 // function declaration, all parameters subsequent to a
218 // parameter with a default argument shall have default
219 // arguments supplied in this or previous declarations. A
220 // default argument shall not be redefined by a later
221 // declaration (not even to the same value).
222 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
223 ParmVarDecl *OldParam = Old->getParamDecl(p);
224 ParmVarDecl *NewParam = New->getParamDecl(p);
225
226 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
227 Diag(NewParam->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000228 diag::err_param_default_argument_redefinition)
229 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000230 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregor083c23e2009-02-16 17:45:42 +0000231 Invalid = true;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000232 } else if (OldParam->getDefaultArg()) {
233 // Merge the old default argument into the new parameter
234 NewParam->setDefaultArg(OldParam->getDefaultArg());
235 }
236 }
237
Douglas Gregor083c23e2009-02-16 17:45:42 +0000238 return Invalid;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000239}
240
241/// CheckCXXDefaultArguments - Verify that the default arguments for a
242/// function declaration are well-formed according to C++
243/// [dcl.fct.default].
244void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
245 unsigned NumParams = FD->getNumParams();
246 unsigned p;
247
248 // Find first parameter with a default argument
249 for (p = 0; p < NumParams; ++p) {
250 ParmVarDecl *Param = FD->getParamDecl(p);
251 if (Param->getDefaultArg())
252 break;
253 }
254
255 // C++ [dcl.fct.default]p4:
256 // In a given function declaration, all parameters
257 // subsequent to a parameter with a default argument shall
258 // have default arguments supplied in this or previous
259 // declarations. A default argument shall not be redefined
260 // by a later declaration (not even to the same value).
261 unsigned LastMissingDefaultArg = 0;
262 for(; p < NumParams; ++p) {
263 ParmVarDecl *Param = FD->getParamDecl(p);
264 if (!Param->getDefaultArg()) {
Douglas Gregor605de8d2008-12-16 21:30:33 +0000265 if (Param->isInvalidDecl())
266 /* We already complained about this parameter. */;
267 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000268 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000269 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000270 << Param->getIdentifier();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000271 else
272 Diag(Param->getLocation(),
273 diag::err_param_default_argument_missing);
274
275 LastMissingDefaultArg = p;
276 }
277 }
278
279 if (LastMissingDefaultArg > 0) {
280 // Some default arguments were missing. Clear out all of the
281 // default arguments up to (and including) the last missing
282 // default argument, so that we leave the function parameters
283 // in a semantically valid state.
284 for (p = 0; p <= LastMissingDefaultArg; ++p) {
285 ParmVarDecl *Param = FD->getParamDecl(p);
286 if (Param->getDefaultArg()) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000287 if (!Param->hasUnparsedDefaultArg())
288 Param->getDefaultArg()->Destroy(Context);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000289 Param->setDefaultArg(0);
290 }
291 }
292 }
293}
Douglas Gregorec93f442008-04-13 21:30:24 +0000294
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000295/// isCurrentClassName - Determine whether the identifier II is the
296/// name of the class type currently being defined. In the case of
297/// nested classes, this will only return true if II is the name of
298/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000299bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
300 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000301 CXXRecordDecl *CurDecl;
302 if (SS) {
303 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
304 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
305 } else
306 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
307
308 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000309 return &II == CurDecl->getIdentifier();
310 else
311 return false;
312}
313
Douglas Gregored3a3982009-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.
Douglas Gregorc84d8932009-03-09 16:13:40 +0000353 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
Douglas Gregor375733c2009-03-10 00:06:19 +0000354 SpecifierRange))
Douglas Gregored3a3982009-03-03 04:44:36 +0000355 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 Gregorec93f442008-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 Gregorabed2172008-10-22 17:49:05 +0000382Sema::BaseResult
383Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
384 bool Virtual, AccessSpecifier Access,
385 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000386 AdjustDeclIfTemplate(classdecl);
387 CXXRecordDecl *Class = cast<CXXRecordDecl>((Decl*)classdecl);
Douglas Gregora60c62e2009-02-09 15:09:02 +0000388 QualType BaseType = QualType::getFromOpaquePtr(basetype);
Douglas Gregored3a3982009-03-03 04:44:36 +0000389 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
390 Virtual, Access,
391 BaseType, BaseLoc))
392 return BaseSpec;
393
394 return true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000395}
Douglas Gregorec93f442008-04-13 21:30:24 +0000396
Douglas Gregored3a3982009-03-03 04:44:36 +0000397/// \brief Performs the actual work of attaching the given base class
398/// specifiers to a C++ class.
399bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
400 unsigned NumBases) {
401 if (NumBases == 0)
402 return false;
Douglas Gregorabed2172008-10-22 17:49:05 +0000403
404 // Used to keep track of which base types we have already seen, so
405 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000406 // that the key is always the unqualified canonical type of the base
407 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000408 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
409
410 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000411 unsigned NumGoodBases = 0;
Douglas Gregored3a3982009-03-03 04:44:36 +0000412 bool Invalid = false;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000413 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000414 QualType NewBaseType
Douglas Gregored3a3982009-03-03 04:44:36 +0000415 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor4fd85902008-10-23 18:13:27 +0000416 NewBaseType = NewBaseType.getUnqualifiedType();
417
Douglas Gregorabed2172008-10-22 17:49:05 +0000418 if (KnownBaseTypes[NewBaseType]) {
419 // C++ [class.mi]p3:
420 // A class shall not be specified as a direct base class of a
421 // derived class more than once.
Douglas Gregored3a3982009-03-03 04:44:36 +0000422 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000423 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000424 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregored3a3982009-03-03 04:44:36 +0000425 << Bases[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000426
427 // Delete the duplicate base class specifier; we're going to
428 // overwrite its pointer later.
Douglas Gregored3a3982009-03-03 04:44:36 +0000429 delete Bases[idx];
430
431 Invalid = true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000432 } else {
433 // Okay, add this new base class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000434 KnownBaseTypes[NewBaseType] = Bases[idx];
435 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000436 }
437 }
438
439 // Attach the remaining base class specifiers to the derived class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000440 Class->setBases(Bases, NumGoodBases);
Douglas Gregor4fd85902008-10-23 18:13:27 +0000441
442 // Delete the remaining (good) base class specifiers, since their
443 // data has been copied into the CXXRecordDecl.
444 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregored3a3982009-03-03 04:44:36 +0000445 delete Bases[idx];
446
447 return Invalid;
448}
449
450/// ActOnBaseSpecifiers - Attach the given base specifiers to the
451/// class, after checking whether there are any duplicate base
452/// classes.
453void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
454 unsigned NumBases) {
455 if (!ClassDecl || !Bases || !NumBases)
456 return;
457
458 AdjustDeclIfTemplate(ClassDecl);
459 AttachBaseSpecifiers(cast<CXXRecordDecl>((Decl*)ClassDecl),
460 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregorec93f442008-04-13 21:30:24 +0000461}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000462
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000463//===----------------------------------------------------------------------===//
464// C++ class member Handling
465//===----------------------------------------------------------------------===//
466
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000467/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
468/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
469/// bitfield width if there is one and 'InitExpr' specifies the initializer if
470/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
471/// declarators on it.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000472Sema::DeclTy *
473Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
474 ExprTy *BW, ExprTy *InitExpr,
475 DeclTy *LastInGroup) {
476 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000477 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000478 Expr *BitWidth = static_cast<Expr*>(BW);
479 Expr *Init = static_cast<Expr*>(InitExpr);
480 SourceLocation Loc = D.getIdentifierLoc();
481
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000482 bool isFunc = D.isFunctionDeclarator();
483
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000484 // C++ 9.2p6: A member shall not be declared to have automatic storage
485 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000486 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
487 // data members and cannot be applied to names declared const or static,
488 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000489 switch (DS.getStorageClassSpec()) {
490 case DeclSpec::SCS_unspecified:
491 case DeclSpec::SCS_typedef:
492 case DeclSpec::SCS_static:
493 // FALL THROUGH.
494 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000495 case DeclSpec::SCS_mutable:
496 if (isFunc) {
497 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000498 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000499 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000500 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
501
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000502 // FIXME: It would be nicer if the keyword was ignored only for this
503 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000504 D.getMutableDeclSpec().ClearStorageClassSpecs();
505 } else {
506 QualType T = GetTypeForDeclarator(D, S);
507 diag::kind err = static_cast<diag::kind>(0);
508 if (T->isReferenceType())
509 err = diag::err_mutable_reference;
510 else if (T.isConstQualified())
511 err = diag::err_mutable_const;
512 if (err != 0) {
513 if (DS.getStorageClassSpecLoc().isValid())
514 Diag(DS.getStorageClassSpecLoc(), err);
515 else
516 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000517 // FIXME: It would be nicer if the keyword was ignored only for this
518 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000519 D.getMutableDeclSpec().ClearStorageClassSpecs();
520 }
521 }
522 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000523 default:
524 if (DS.getStorageClassSpecLoc().isValid())
525 Diag(DS.getStorageClassSpecLoc(),
526 diag::err_storageclass_invalid_for_member);
527 else
528 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
529 D.getMutableDeclSpec().ClearStorageClassSpecs();
530 }
531
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000532 if (!isFunc &&
Douglas Gregora60c62e2009-02-09 15:09:02 +0000533 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000534 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000535 // Check also for this case:
536 //
537 // typedef int f();
538 // f a;
539 //
Douglas Gregora60c62e2009-02-09 15:09:02 +0000540 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
541 isFunc = TDType->isFunctionType();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000542 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000543
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000544 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
545 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000546 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000547
548 Decl *Member;
Chris Lattner9cffefc2009-03-05 22:45:59 +0000549 if (isInstField) {
Chris Lattnere384c182009-03-05 23:03:49 +0000550 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth);
551 assert(Member && "HandleField never returns null");
Chris Lattner9cffefc2009-03-05 22:45:59 +0000552 } else {
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000553 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Chris Lattnere384c182009-03-05 23:03:49 +0000554 if (!Member) {
555 if (BitWidth) DeleteExpr(BitWidth);
556 return LastInGroup;
557 }
Chris Lattner432780c2009-03-05 23:01:03 +0000558
559 // Non-instance-fields can't have a bitfield.
560 if (BitWidth) {
561 if (Member->isInvalidDecl()) {
562 // don't emit another diagnostic.
Douglas Gregor00660582009-03-11 20:22:50 +0000563 } else if (isa<VarDecl>(Member)) {
Chris Lattner432780c2009-03-05 23:01:03 +0000564 // C++ 9.6p3: A bit-field shall not be a static member.
565 // "static member 'A' cannot be a bit-field"
566 Diag(Loc, diag::err_static_not_bitfield)
567 << Name << BitWidth->getSourceRange();
568 } else if (isa<TypedefDecl>(Member)) {
569 // "typedef member 'x' cannot be a bit-field"
570 Diag(Loc, diag::err_typedef_not_bitfield)
571 << Name << BitWidth->getSourceRange();
572 } else {
573 // A function typedef ("typedef int f(); f a;").
574 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
575 Diag(Loc, diag::err_not_integral_type_bitfield)
Douglas Gregor0e518af2009-03-11 18:59:21 +0000576 << Name << cast<ValueDecl>(Member)->getType()
577 << BitWidth->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000578 }
579
580 DeleteExpr(BitWidth);
581 BitWidth = 0;
582 Member->setInvalidDecl();
583 }
Chris Lattner9cffefc2009-03-05 22:45:59 +0000584 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000585
Douglas Gregor6704b312008-11-17 22:58:34 +0000586 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000587
Douglas Gregor26561a02009-03-11 20:25:10 +0000588 Member->setAccess(AS);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000589
Douglas Gregor15e04622008-11-05 16:20:31 +0000590 // C++ [dcl.init.aggr]p1:
591 // An aggregate is an array or a class (clause 9) with [...] no
592 // private or protected non-static data members (clause 11).
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000593 // A POD must be an aggregate.
594 if (isInstField && (AS == AS_private || AS == AS_protected)) {
595 CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext);
596 Record->setAggregate(false);
597 Record->setPOD(false);
598 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000599
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000600 if (DS.isVirtualSpecified()) {
601 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
602 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
Chris Lattner432780c2009-03-05 23:01:03 +0000603 Member->setInvalidDecl();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000604 } else {
Sebastian Redl83faa292009-01-09 19:57:06 +0000605 cast<CXXMethodDecl>(Member)->setVirtual();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000606 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
607 CurClass->setAggregate(false);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000608 CurClass->setPOD(false);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000609 CurClass->setPolymorphic(true);
610 }
611 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000612
Sebastian Redl83faa292009-01-09 19:57:06 +0000613 // FIXME: The above definition of virtual is not sufficient. A function is
614 // also virtual if it overrides an already virtual function. This is important
615 // to do here because it decides the validity of a pure specifier.
616
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000617 if (Init) {
618 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
619 // if it declares a static member of const integral or const enumeration
620 // type.
Douglas Gregor00660582009-03-11 20:22:50 +0000621 if (VarDecl *CVD = dyn_cast<VarDecl>(Member)) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000622 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000623 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000624 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000625 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
626 CVD->getType()->isIntegralType()) {
627 // constant-initializer
628 if (CheckForConstantInitializer(Init, CVD->getType()))
Chris Lattner432780c2009-03-05 23:01:03 +0000629 Member->setInvalidDecl();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000630
631 } else {
632 // not const integral.
Chris Lattner77d52da2008-11-20 06:06:08 +0000633 Diag(Loc, diag::err_member_initialization)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000634 << Name << Init->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000635 Member->setInvalidDecl();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000636 }
637
638 } else {
Sebastian Redl83faa292009-01-09 19:57:06 +0000639 // not static member. perhaps virtual function?
640 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
Sebastian Redl54e4be92009-01-09 22:29:03 +0000641 // With declarators parsed the way they are, the parser cannot
642 // distinguish between a normal initializer and a pure-specifier.
643 // Thus this grotesque test.
Sebastian Redl83faa292009-01-09 19:57:06 +0000644 IntegerLiteral *IL;
645 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
646 Context.getCanonicalType(IL->getType()) == Context.IntTy) {
647 if (MD->isVirtual())
648 MD->setPure();
649 else {
650 Diag(Loc, diag::err_non_virtual_pure)
651 << Name << Init->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000652 Member->setInvalidDecl();
Sebastian Redl83faa292009-01-09 19:57:06 +0000653 }
654 } else {
655 Diag(Loc, diag::err_member_function_initialization)
656 << Name << Init->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000657 Member->setInvalidDecl();
Sebastian Redl83faa292009-01-09 19:57:06 +0000658 }
659 } else {
660 Diag(Loc, diag::err_member_initialization)
661 << Name << Init->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000662 Member->setInvalidDecl();
Sebastian Redl83faa292009-01-09 19:57:06 +0000663 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000664 }
665 }
666
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000667 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000668 FieldCollector->Add(cast<FieldDecl>(Member));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000669 return LastInGroup;
670 }
671 return Member;
672}
673
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000674/// ActOnMemInitializer - Handle a C++ member initializer.
675Sema::MemInitResult
676Sema::ActOnMemInitializer(DeclTy *ConstructorD,
677 Scope *S,
678 IdentifierInfo *MemberOrBase,
679 SourceLocation IdLoc,
680 SourceLocation LParenLoc,
681 ExprTy **Args, unsigned NumArgs,
682 SourceLocation *CommaLocs,
683 SourceLocation RParenLoc) {
684 CXXConstructorDecl *Constructor
685 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
686 if (!Constructor) {
687 // The user wrote a constructor initializer on a function that is
688 // not a C++ constructor. Ignore the error for now, because we may
689 // have more member initializers coming; we'll diagnose it just
690 // once in ActOnMemInitializers.
691 return true;
692 }
693
694 CXXRecordDecl *ClassDecl = Constructor->getParent();
695
696 // C++ [class.base.init]p2:
697 // Names in a mem-initializer-id are looked up in the scope of the
698 // constructor’s class and, if not found in that scope, are looked
699 // up in the scope containing the constructor’s
700 // definition. [Note: if the constructor’s class contains a member
701 // with the same name as a direct or virtual base class of the
702 // class, a mem-initializer-id naming the member or base class and
703 // composed of a single identifier refers to the class member. A
704 // mem-initializer-id for the hidden base class may be specified
705 // using a qualified name. ]
706 // Look for a member, first.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000707 FieldDecl *Member = 0;
Steve Naroffab63fd62009-01-08 17:28:14 +0000708 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000709 if (Result.first != Result.second)
710 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000711
712 // FIXME: Handle members of an anonymous union.
713
714 if (Member) {
715 // FIXME: Perform direct initialization of the member.
716 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
717 }
718
719 // It didn't name a member, so see if it names a class.
Douglas Gregor1075a162009-02-04 17:00:24 +0000720 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000721 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000722 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
723 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000724
Douglas Gregora60c62e2009-02-09 15:09:02 +0000725 QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000726 if (!BaseType->isRecordType())
Chris Lattner65cae292008-11-19 08:23:25 +0000727 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattnerb1753422008-11-23 21:45:46 +0000728 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000729
730 // C++ [class.base.init]p2:
731 // [...] Unless the mem-initializer-id names a nonstatic data
732 // member of the constructor’s class or a direct or virtual base
733 // of that class, the mem-initializer is ill-formed. A
734 // mem-initializer-list can initialize a base class using any
735 // name that denotes that base class type.
736
737 // First, check for a direct base class.
738 const CXXBaseSpecifier *DirectBaseSpec = 0;
739 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
740 Base != ClassDecl->bases_end(); ++Base) {
741 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
742 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
743 // We found a direct base of this type. That's what we're
744 // initializing.
745 DirectBaseSpec = &*Base;
746 break;
747 }
748 }
749
750 // Check for a virtual base class.
751 // FIXME: We might be able to short-circuit this if we know in
752 // advance that there are no virtual bases.
753 const CXXBaseSpecifier *VirtualBaseSpec = 0;
754 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
755 // We haven't found a base yet; search the class hierarchy for a
756 // virtual base class.
757 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
758 /*DetectVirtual=*/false);
759 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
760 for (BasePaths::paths_iterator Path = Paths.begin();
761 Path != Paths.end(); ++Path) {
762 if (Path->back().Base->isVirtual()) {
763 VirtualBaseSpec = Path->back().Base;
764 break;
765 }
766 }
767 }
768 }
769
770 // C++ [base.class.init]p2:
771 // If a mem-initializer-id is ambiguous because it designates both
772 // a direct non-virtual base class and an inherited virtual base
773 // class, the mem-initializer is ill-formed.
774 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner65cae292008-11-19 08:23:25 +0000775 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
776 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000777
778 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
779}
780
781
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000782void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
783 DeclTy *TagDecl,
784 SourceLocation LBrac,
785 SourceLocation RBrac) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000786 TemplateDecl *Template = AdjustDeclIfTemplate(TagDecl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000787 ActOnFields(S, RLoc, TagDecl,
788 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000789 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregored3a3982009-03-03 04:44:36 +0000790
791 if (!Template)
792 AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000793}
794
Douglas Gregore640ab62008-11-03 17:51:48 +0000795/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
796/// special functions, such as the default constructor, copy
797/// constructor, or destructor, to the given C++ class (C++
798/// [special]p1). This routine can only be executed just before the
799/// definition of the class is complete.
800void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000801 QualType ClassType = Context.getTypeDeclType(ClassDecl);
802 ClassType = Context.getCanonicalType(ClassType);
803
Douglas Gregore640ab62008-11-03 17:51:48 +0000804 if (!ClassDecl->hasUserDeclaredConstructor()) {
805 // C++ [class.ctor]p5:
806 // A default constructor for a class X is a constructor of class X
807 // that can be called without an argument. If there is no
808 // user-declared constructor for class X, a default constructor is
809 // implicitly declared. An implicitly-declared default constructor
810 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000811 DeclarationName Name
812 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000813 CXXConstructorDecl *DefaultCon =
814 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000815 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000816 Context.getFunctionType(Context.VoidTy,
817 0, 0, false, 0),
818 /*isExplicit=*/false,
819 /*isInline=*/true,
820 /*isImplicitlyDeclared=*/true);
821 DefaultCon->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000822 DefaultCon->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000823 ClassDecl->addDecl(DefaultCon);
Douglas Gregorb9213832008-12-15 21:24:18 +0000824
825 // Notify the class that we've added a constructor.
826 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +0000827 }
828
829 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
830 // C++ [class.copy]p4:
831 // If the class definition does not explicitly declare a copy
832 // constructor, one is declared implicitly.
833
834 // C++ [class.copy]p5:
835 // The implicitly-declared copy constructor for a class X will
836 // have the form
837 //
838 // X::X(const X&)
839 //
840 // if
841 bool HasConstCopyConstructor = true;
842
843 // -- each direct or virtual base class B of X has a copy
844 // constructor whose first parameter is of type const B& or
845 // const volatile B&, and
846 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
847 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
848 const CXXRecordDecl *BaseClassDecl
849 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
850 HasConstCopyConstructor
851 = BaseClassDecl->hasConstCopyConstructor(Context);
852 }
853
854 // -- for all the nonstatic data members of X that are of a
855 // class type M (or array thereof), each such class type
856 // has a copy constructor whose first parameter is of type
857 // const M& or const volatile M&.
858 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
859 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
860 QualType FieldType = (*Field)->getType();
861 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
862 FieldType = Array->getElementType();
863 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
864 const CXXRecordDecl *FieldClassDecl
865 = cast<CXXRecordDecl>(FieldClassType->getDecl());
866 HasConstCopyConstructor
867 = FieldClassDecl->hasConstCopyConstructor(Context);
868 }
869 }
870
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000871 // Otherwise, the implicitly declared copy constructor will have
872 // the form
Douglas Gregore640ab62008-11-03 17:51:48 +0000873 //
874 // X::X(X&)
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000875 QualType ArgType = ClassType;
Douglas Gregore640ab62008-11-03 17:51:48 +0000876 if (HasConstCopyConstructor)
877 ArgType = ArgType.withConst();
878 ArgType = Context.getReferenceType(ArgType);
879
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000880 // An implicitly-declared copy constructor is an inline public
881 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000882 DeclarationName Name
883 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000884 CXXConstructorDecl *CopyConstructor
885 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000886 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000887 Context.getFunctionType(Context.VoidTy,
888 &ArgType, 1,
889 false, 0),
890 /*isExplicit=*/false,
891 /*isInline=*/true,
892 /*isImplicitlyDeclared=*/true);
893 CopyConstructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000894 CopyConstructor->setImplicit();
Douglas Gregore640ab62008-11-03 17:51:48 +0000895
896 // Add the parameter to the constructor.
897 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
898 ClassDecl->getLocation(),
899 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000900 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000901 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregore640ab62008-11-03 17:51:48 +0000902
Douglas Gregorb9213832008-12-15 21:24:18 +0000903 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000904 ClassDecl->addDecl(CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +0000905 }
906
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000907 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
908 // Note: The following rules are largely analoguous to the copy
909 // constructor rules. Note that virtual bases are not taken into account
910 // for determining the argument type of the operator. Note also that
911 // operators taking an object instead of a reference are allowed.
912 //
913 // C++ [class.copy]p10:
914 // If the class definition does not explicitly declare a copy
915 // assignment operator, one is declared implicitly.
916 // The implicitly-defined copy assignment operator for a class X
917 // will have the form
918 //
919 // X& X::operator=(const X&)
920 //
921 // if
922 bool HasConstCopyAssignment = true;
923
924 // -- each direct base class B of X has a copy assignment operator
925 // whose parameter is of type const B&, const volatile B& or B,
926 // and
927 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
928 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
929 const CXXRecordDecl *BaseClassDecl
930 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
931 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
932 }
933
934 // -- for all the nonstatic data members of X that are of a class
935 // type M (or array thereof), each such class type has a copy
936 // assignment operator whose parameter is of type const M&,
937 // const volatile M& or M.
938 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
939 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
940 QualType FieldType = (*Field)->getType();
941 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
942 FieldType = Array->getElementType();
943 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
944 const CXXRecordDecl *FieldClassDecl
945 = cast<CXXRecordDecl>(FieldClassType->getDecl());
946 HasConstCopyAssignment
947 = FieldClassDecl->hasConstCopyAssignment(Context);
948 }
949 }
950
951 // Otherwise, the implicitly declared copy assignment operator will
952 // have the form
953 //
954 // X& X::operator=(X&)
955 QualType ArgType = ClassType;
956 QualType RetType = Context.getReferenceType(ArgType);
957 if (HasConstCopyAssignment)
958 ArgType = ArgType.withConst();
959 ArgType = Context.getReferenceType(ArgType);
960
961 // An implicitly-declared copy assignment operator is an inline public
962 // member of its class.
963 DeclarationName Name =
964 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
965 CXXMethodDecl *CopyAssignment =
966 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
967 Context.getFunctionType(RetType, &ArgType, 1,
968 false, 0),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000969 /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000970 CopyAssignment->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000971 CopyAssignment->setImplicit();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000972
973 // Add the parameter to the operator.
974 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
975 ClassDecl->getLocation(),
976 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000977 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000978 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000979
980 // Don't call addedAssignmentOperator. There is no way to distinguish an
981 // implicit from an explicit assignment operator.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000982 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000983 }
984
Douglas Gregorb9213832008-12-15 21:24:18 +0000985 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000986 // C++ [class.dtor]p2:
987 // If a class has no user-declared destructor, a destructor is
988 // declared implicitly. An implicitly-declared destructor is an
989 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000990 DeclarationName Name
991 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000992 CXXDestructorDecl *Destructor
993 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000994 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000995 Context.getFunctionType(Context.VoidTy,
996 0, 0, false, 0),
997 /*isInline=*/true,
998 /*isImplicitlyDeclared=*/true);
999 Destructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001000 Destructor->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +00001001 ClassDecl->addDecl(Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001002 }
Douglas Gregore640ab62008-11-03 17:51:48 +00001003}
1004
Douglas Gregor605de8d2008-12-16 21:30:33 +00001005/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1006/// parsing a top-level (non-nested) C++ class, and we are now
1007/// parsing those parts of the given Method declaration that could
1008/// not be parsed earlier (C++ [class.mem]p2), such as default
1009/// arguments. This action should enter the scope of the given
1010/// Method declaration as if we had just parsed the qualified method
1011/// name. However, it should not bring the parameters into scope;
1012/// that will be performed by ActOnDelayedCXXMethodParameter.
1013void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
1014 CXXScopeSpec SS;
1015 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
1016 ActOnCXXEnterDeclaratorScope(S, SS);
1017}
1018
1019/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1020/// C++ method declaration. We're (re-)introducing the given
1021/// function parameter into scope for use in parsing later parts of
1022/// the method declaration. For example, we could see an
1023/// ActOnParamDefaultArgument event for this parameter.
1024void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1025 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001026
1027 // If this parameter has an unparsed default argument, clear it out
1028 // to make way for the parsed default argument.
1029 if (Param->hasUnparsedDefaultArg())
1030 Param->setDefaultArg(0);
1031
Douglas Gregor605de8d2008-12-16 21:30:33 +00001032 S->AddDecl(Param);
1033 if (Param->getDeclName())
1034 IdResolver.AddDecl(Param);
1035}
1036
1037/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1038/// processing the delayed method declaration for Method. The method
1039/// declaration is now considered finished. There may be a separate
1040/// ActOnStartOfFunctionDef action later (not necessarily
1041/// immediately!) for this method, if it was also defined inside the
1042/// class body.
1043void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1044 FunctionDecl *Method = (FunctionDecl*)MethodD;
1045 CXXScopeSpec SS;
1046 SS.setScopeRep(Method->getDeclContext());
1047 ActOnCXXExitDeclaratorScope(S, SS);
1048
1049 // Now that we have our default arguments, check the constructor
1050 // again. It could produce additional diagnostics or affect whether
1051 // the class has implicitly-declared destructors, among other
1052 // things.
1053 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1054 if (CheckConstructor(Constructor))
1055 Constructor->setInvalidDecl();
1056 }
1057
1058 // Check the default arguments, which we may have added.
1059 if (!Method->isInvalidDecl())
1060 CheckCXXDefaultArguments(Method);
1061}
1062
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001063/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +00001064/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001065/// R. If there are any errors in the declarator, this routine will
1066/// emit diagnostics and return true. Otherwise, it will return
1067/// false. Either way, the type @p R will be updated to reflect a
1068/// well-formed type for the constructor.
1069bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1070 FunctionDecl::StorageClass& SC) {
1071 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1072 bool isInvalid = false;
1073
1074 // C++ [class.ctor]p3:
1075 // A constructor shall not be virtual (10.3) or static (9.4). A
1076 // constructor can be invoked for a const, volatile or const
1077 // volatile object. A constructor shall not be declared const,
1078 // volatile, or const volatile (9.3.2).
1079 if (isVirtual) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001080 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1081 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1082 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001083 isInvalid = true;
1084 }
1085 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001086 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1087 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1088 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001089 isInvalid = true;
1090 SC = FunctionDecl::None;
1091 }
1092 if (D.getDeclSpec().hasTypeSpecifier()) {
1093 // Constructors don't have return types, but the parser will
1094 // happily parse something like:
1095 //
1096 // class X {
1097 // float X(float);
1098 // };
1099 //
1100 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001101 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1102 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1103 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001104 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00001105 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001106 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1107 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001108 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1109 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001110 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001111 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1112 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001113 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001114 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1115 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001116 }
1117
1118 // Rebuild the function type "R" without any type qualifiers (in
1119 // case any of the errors above fired) and with "void" as the
1120 // return type, since constructors don't have return types. We
1121 // *always* have to do this, because GetTypeForDeclarator will
1122 // put in a result type of "int" when none was specified.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001123 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001124 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1125 Proto->getNumArgs(),
1126 Proto->isVariadic(),
1127 0);
1128
1129 return isInvalid;
1130}
1131
Douglas Gregor605de8d2008-12-16 21:30:33 +00001132/// CheckConstructor - Checks a fully-formed constructor for
1133/// well-formedness, issuing any diagnostics required. Returns true if
1134/// the constructor declarator is invalid.
1135bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1136 if (Constructor->isInvalidDecl())
1137 return true;
1138
1139 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1140 bool Invalid = false;
1141
1142 // C++ [class.copy]p3:
1143 // A declaration of a constructor for a class X is ill-formed if
1144 // its first parameter is of type (optionally cv-qualified) X and
1145 // either there are no other parameters or else all other
1146 // parameters have default arguments.
1147 if ((Constructor->getNumParams() == 1) ||
1148 (Constructor->getNumParams() > 1 &&
1149 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1150 QualType ParamType = Constructor->getParamDecl(0)->getType();
1151 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1152 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1153 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1154 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1155 Invalid = true;
1156 }
1157 }
1158
1159 // Notify the class that we've added a constructor.
1160 ClassDecl->addedConstructor(Context, Constructor);
1161
1162 return Invalid;
1163}
1164
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001165/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1166/// the well-formednes of the destructor declarator @p D with type @p
1167/// R. If there are any errors in the declarator, this routine will
1168/// emit diagnostics and return true. Otherwise, it will return
1169/// false. Either way, the type @p R will be updated to reflect a
1170/// well-formed type for the destructor.
1171bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1172 FunctionDecl::StorageClass& SC) {
1173 bool isInvalid = false;
1174
1175 // C++ [class.dtor]p1:
1176 // [...] A typedef-name that names a class is a class-name
1177 // (7.1.3); however, a typedef-name that names a class shall not
1178 // be used as the identifier in the declarator for a destructor
1179 // declaration.
Douglas Gregora60c62e2009-02-09 15:09:02 +00001180 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1181 if (DeclaratorType->getAsTypedefType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001182 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregora60c62e2009-02-09 15:09:02 +00001183 << DeclaratorType;
Douglas Gregorbd19fdb2008-11-10 14:41:22 +00001184 isInvalid = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001185 }
1186
1187 // C++ [class.dtor]p2:
1188 // A destructor is used to destroy objects of its class type. A
1189 // destructor takes no parameters, and no return type can be
1190 // specified for it (not even void). The address of a destructor
1191 // shall not be taken. A destructor shall not be static. A
1192 // destructor can be invoked for a const, volatile or const
1193 // volatile object. A destructor shall not be declared const,
1194 // volatile or const volatile (9.3.2).
1195 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001196 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1197 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1198 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001199 isInvalid = true;
1200 SC = FunctionDecl::None;
1201 }
1202 if (D.getDeclSpec().hasTypeSpecifier()) {
1203 // Destructors don't have return types, but the parser will
1204 // happily parse something like:
1205 //
1206 // class X {
1207 // float ~X();
1208 // };
1209 //
1210 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001211 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1212 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1213 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001214 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00001215 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001216 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1217 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001218 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1219 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001220 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001221 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1222 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001223 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001224 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1225 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001226 }
1227
1228 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001229 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001230 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1231
1232 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001233 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001234 }
1235
1236 // Make sure the destructor isn't variadic.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001237 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001238 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1239
1240 // Rebuild the function type "R" without any type qualifiers or
1241 // parameters (in case any of the errors above fired) and with
1242 // "void" as the return type, since destructors don't have return
1243 // types. We *always* have to do this, because GetTypeForDeclarator
1244 // will put in a result type of "int" when none was specified.
1245 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1246
1247 return isInvalid;
1248}
1249
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001250/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1251/// well-formednes of the conversion function declarator @p D with
1252/// type @p R. If there are any errors in the declarator, this routine
1253/// will emit diagnostics and return true. Otherwise, it will return
1254/// false. Either way, the type @p R will be updated to reflect a
1255/// well-formed type for the conversion operator.
1256bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1257 FunctionDecl::StorageClass& SC) {
1258 bool isInvalid = false;
1259
1260 // C++ [class.conv.fct]p1:
1261 // Neither parameter types nor return type can be specified. The
1262 // type of a conversion function (8.3.5) is “function taking no
1263 // parameter returning conversion-type-id.”
1264 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001265 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1266 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1267 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001268 isInvalid = true;
1269 SC = FunctionDecl::None;
1270 }
1271 if (D.getDeclSpec().hasTypeSpecifier()) {
1272 // Conversion functions don't have return types, but the parser will
1273 // happily parse something like:
1274 //
1275 // class X {
1276 // float operator bool();
1277 // };
1278 //
1279 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001280 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1281 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1282 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001283 }
1284
1285 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001286 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001287 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1288
1289 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001290 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001291 }
1292
1293 // Make sure the conversion function isn't variadic.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001294 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001295 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1296
1297 // C++ [class.conv.fct]p4:
1298 // The conversion-type-id shall not represent a function type nor
1299 // an array type.
1300 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1301 if (ConvType->isArrayType()) {
1302 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1303 ConvType = Context.getPointerType(ConvType);
1304 } else if (ConvType->isFunctionType()) {
1305 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1306 ConvType = Context.getPointerType(ConvType);
1307 }
1308
1309 // Rebuild the function type "R" without any parameters (in case any
1310 // of the errors above fired) and with the conversion type as the
1311 // return type.
1312 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001313 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001314
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001315 // C++0x explicit conversion operators.
1316 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1317 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1318 diag::warn_explicit_conversion_functions)
1319 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1320
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001321 return isInvalid;
1322}
1323
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001324/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1325/// the declaration of the given C++ conversion function. This routine
1326/// is responsible for recording the conversion function in the C++
1327/// class, if possible.
1328Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1329 assert(Conversion && "Expected to receive a conversion function declaration");
1330
Douglas Gregor98341042008-12-12 08:25:50 +00001331 // Set the lexical context of this conversion function
1332 Conversion->setLexicalDeclContext(CurContext);
1333
1334 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001335
1336 // Make sure we aren't redeclaring the conversion function.
1337 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001338
1339 // C++ [class.conv.fct]p1:
1340 // [...] A conversion function is never used to convert a
1341 // (possibly cv-qualified) object to the (possibly cv-qualified)
1342 // same object type (or a reference to it), to a (possibly
1343 // cv-qualified) base class of that type (or a reference to it),
1344 // or to (possibly cv-qualified) void.
1345 // FIXME: Suppress this warning if the conversion function ends up
1346 // being a virtual function that overrides a virtual function in a
1347 // base class.
1348 QualType ClassType
1349 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1350 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1351 ConvType = ConvTypeRef->getPointeeType();
1352 if (ConvType->isRecordType()) {
1353 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1354 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001355 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001356 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001357 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001358 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001359 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001360 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001361 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001362 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001363 }
1364
Douglas Gregor853dd392008-12-26 15:00:45 +00001365 if (Conversion->getPreviousDeclaration()) {
1366 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1367 for (OverloadedFunctionDecl::function_iterator
1368 Conv = Conversions->function_begin(),
1369 ConvEnd = Conversions->function_end();
1370 Conv != ConvEnd; ++Conv) {
1371 if (*Conv == Conversion->getPreviousDeclaration()) {
1372 *Conv = Conversion;
1373 return (DeclTy *)Conversion;
1374 }
1375 }
1376 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1377 } else
1378 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001379
1380 return (DeclTy *)Conversion;
1381}
1382
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001383//===----------------------------------------------------------------------===//
1384// Namespace Handling
1385//===----------------------------------------------------------------------===//
1386
1387/// ActOnStartNamespaceDef - This is called at the start of a namespace
1388/// definition.
1389Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1390 SourceLocation IdentLoc,
1391 IdentifierInfo *II,
1392 SourceLocation LBrace) {
1393 NamespaceDecl *Namespc =
1394 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1395 Namespc->setLBracLoc(LBrace);
1396
1397 Scope *DeclRegionScope = NamespcScope->getParent();
1398
1399 if (II) {
1400 // C++ [namespace.def]p2:
1401 // The identifier in an original-namespace-definition shall not have been
1402 // previously defined in the declarative region in which the
1403 // original-namespace-definition appears. The identifier in an
1404 // original-namespace-definition is the name of the namespace. Subsequently
1405 // in that declarative region, it is treated as an original-namespace-name.
1406
Douglas Gregor09be81b2009-02-04 17:27:36 +00001407 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1408 true);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001409
1410 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1411 // This is an extended namespace definition.
1412 // Attach this namespace decl to the chain of extended namespace
1413 // definitions.
1414 OrigNS->setNextNamespace(Namespc);
1415 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001416
Douglas Gregor8acb7272008-12-11 16:49:14 +00001417 // Remove the previous declaration from the scope.
1418 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor39677622008-12-11 20:41:00 +00001419 IdResolver.RemoveDecl(OrigNS);
1420 DeclRegionScope->RemoveDecl(OrigNS);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001421 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001422 } else if (PrevDecl) {
1423 // This is an invalid name redefinition.
1424 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1425 << Namespc->getDeclName();
1426 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1427 Namespc->setInvalidDecl();
1428 // Continue on to push Namespc as current DeclContext and return it.
1429 }
1430
1431 PushOnScopeChains(Namespc, DeclRegionScope);
1432 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001433 // FIXME: Handle anonymous namespaces
1434 }
1435
1436 // Although we could have an invalid decl (i.e. the namespace name is a
1437 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001438 // FIXME: We should be able to push Namespc here, so that the
1439 // each DeclContext for the namespace has the declarations
1440 // that showed up in that particular namespace definition.
1441 PushDeclContext(NamespcScope, Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001442 return Namespc;
1443}
1444
1445/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1446/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1447void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1448 Decl *Dcl = static_cast<Decl *>(D);
1449 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1450 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1451 Namespc->setRBracLoc(RBrace);
1452 PopDeclContext();
1453}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001454
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001455Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1456 SourceLocation UsingLoc,
1457 SourceLocation NamespcLoc,
1458 const CXXScopeSpec &SS,
1459 SourceLocation IdentLoc,
1460 IdentifierInfo *NamespcName,
1461 AttributeList *AttrList) {
1462 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1463 assert(NamespcName && "Invalid NamespcName.");
1464 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001465 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001466
Douglas Gregor7a7be652009-02-03 19:21:40 +00001467 UsingDirectiveDecl *UDir = 0;
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001468
Douglas Gregor78d70132009-01-14 22:20:51 +00001469 // Lookup namespace name.
Douglas Gregor7a7be652009-02-03 19:21:40 +00001470 LookupResult R = LookupParsedName(S, &SS, NamespcName,
1471 LookupNamespaceName, false);
1472 if (R.isAmbiguous()) {
1473 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1474 return 0;
1475 }
Douglas Gregor09be81b2009-02-04 17:27:36 +00001476 if (NamedDecl *NS = R) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001477 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001478 // C++ [namespace.udir]p1:
1479 // A using-directive specifies that the names in the nominated
1480 // namespace can be used in the scope in which the
1481 // using-directive appears after the using-directive. During
1482 // unqualified name lookup (3.4.1), the names appear as if they
1483 // were declared in the nearest enclosing namespace which
1484 // contains both the using-directive and the nominated
1485 // namespace. [Note: in this context, “contains” means “contains
1486 // directly or indirectly”. ]
1487
1488 // Find enclosing context containing both using-directive and
1489 // nominated namespace.
1490 DeclContext *CommonAncestor = cast<DeclContext>(NS);
1491 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1492 CommonAncestor = CommonAncestor->getParent();
1493
1494 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1495 NamespcLoc, IdentLoc,
1496 cast<NamespaceDecl>(NS),
1497 CommonAncestor);
1498 PushUsingDirective(S, UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001499 } else {
Chris Lattner954381a2009-01-06 07:24:29 +00001500 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001501 }
1502
Douglas Gregor7a7be652009-02-03 19:21:40 +00001503 // FIXME: We ignore attributes for now.
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001504 delete AttrList;
Douglas Gregor7a7be652009-02-03 19:21:40 +00001505 return UDir;
1506}
1507
1508void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1509 // If scope has associated entity, then using directive is at namespace
1510 // or translation unit scope. We add UsingDirectiveDecls, into
1511 // it's lookup structure.
1512 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1513 Ctx->addDecl(UDir);
1514 else
1515 // Otherwise it is block-sope. using-directives will affect lookup
1516 // only to the end of scope.
1517 S->PushUsingDirective(UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001518}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001519
1520/// AddCXXDirectInitializerToDecl - This action is called immediately after
1521/// ActOnDeclarator, when a C++ direct initializer is present.
1522/// e.g: "int x(1);"
1523void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1524 ExprTy **ExprTys, unsigned NumExprs,
1525 SourceLocation *CommaLocs,
1526 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001527 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001528 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001529
1530 // If there is no declaration, there was an error parsing it. Just ignore
1531 // the initializer.
1532 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +00001533 for (unsigned i = 0; i != NumExprs; ++i)
Ted Kremenek0c97e042009-02-07 01:47:29 +00001534 static_cast<Expr *>(ExprTys[i])->Destroy(Context);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001535 return;
1536 }
1537
1538 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1539 if (!VDecl) {
1540 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1541 RealDecl->setInvalidDecl();
1542 return;
1543 }
1544
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001545 // We will treat direct-initialization as a copy-initialization:
1546 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001547 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1548 //
1549 // Clients that want to distinguish between the two forms, can check for
1550 // direct initializer using VarDecl::hasCXXDirectInitializer().
1551 // A major benefit is that clients that don't particularly care about which
1552 // exactly form was it (like the CodeGen) can handle both cases without
1553 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001554
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001555 // C++ 8.5p11:
1556 // The form of initialization (using parentheses or '=') is generally
1557 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001558 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001559 QualType DeclInitType = VDecl->getType();
1560 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1561 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001562
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001563 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001564 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +00001565 = PerformInitializationByConstructor(DeclInitType,
1566 (Expr **)ExprTys, NumExprs,
1567 VDecl->getLocation(),
1568 SourceRange(VDecl->getLocation(),
1569 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00001570 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00001571 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +00001572 if (!Constructor) {
1573 RealDecl->setInvalidDecl();
1574 }
Douglas Gregor6428e762008-11-05 15:29:30 +00001575
1576 // Let clients know that initialization was done with a direct
1577 // initializer.
1578 VDecl->setCXXDirectInitializer(true);
1579
1580 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1581 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001582 return;
1583 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001584
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001585 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001586 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1587 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001588 RealDecl->setInvalidDecl();
1589 return;
1590 }
1591
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001592 // Let clients know that initialization was done with a direct initializer.
1593 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001594
1595 assert(NumExprs == 1 && "Expected 1 expression");
1596 // Set the init expression, handles conversions.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001597 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001598}
Douglas Gregor81c29152008-10-29 00:13:59 +00001599
Douglas Gregor6428e762008-11-05 15:29:30 +00001600/// PerformInitializationByConstructor - Perform initialization by
1601/// constructor (C++ [dcl.init]p14), which may occur as part of
1602/// direct-initialization or copy-initialization. We are initializing
1603/// an object of type @p ClassType with the given arguments @p
1604/// Args. @p Loc is the location in the source code where the
1605/// initializer occurs (e.g., a declaration, member initializer,
1606/// functional cast, etc.) while @p Range covers the whole
1607/// initialization. @p InitEntity is the entity being initialized,
1608/// which may by the name of a declaration or a type. @p Kind is the
1609/// kind of initialization we're performing, which affects whether
1610/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001611/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001612/// when the initialization fails, emits a diagnostic and returns
1613/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001614CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001615Sema::PerformInitializationByConstructor(QualType ClassType,
1616 Expr **Args, unsigned NumArgs,
1617 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00001618 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00001619 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001620 const RecordType *ClassRec = ClassType->getAsRecordType();
1621 assert(ClassRec && "Can only initialize a class type here");
1622
1623 // C++ [dcl.init]p14:
1624 //
1625 // If the initialization is direct-initialization, or if it is
1626 // copy-initialization where the cv-unqualified version of the
1627 // source type is the same class as, or a derived class of, the
1628 // class of the destination, constructors are considered. The
1629 // applicable constructors are enumerated (13.3.1.3), and the
1630 // best one is chosen through overload resolution (13.3). The
1631 // constructor so selected is called to initialize the object,
1632 // with the initializer expression(s) as its argument(s). If no
1633 // constructor applies, or the overload resolution is ambiguous,
1634 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001635 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1636 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001637
1638 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00001639 DeclarationName ConstructorName
1640 = Context.DeclarationNames.getCXXConstructorName(
1641 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001642 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00001643 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001644 Con != ConEnd; ++Con) {
1645 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor6428e762008-11-05 15:29:30 +00001646 if ((Kind == IK_Direct) ||
1647 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1648 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1649 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1650 }
1651
Douglas Gregorb9213832008-12-15 21:24:18 +00001652 // FIXME: When we decide not to synthesize the implicitly-declared
1653 // constructors, we'll need to make them appear here.
1654
Douglas Gregor5870a952008-11-03 20:45:27 +00001655 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001656 switch (BestViableFunction(CandidateSet, Best)) {
1657 case OR_Success:
1658 // We found a constructor. Return it.
1659 return cast<CXXConstructorDecl>(Best->Function);
1660
1661 case OR_No_Viable_Function:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001662 if (InitEntity)
1663 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001664 << InitEntity << Range;
Douglas Gregor538a4c22009-02-02 17:43:21 +00001665 else
1666 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001667 << ClassType << Range;
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00001668 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00001669 return 0;
1670
1671 case OR_Ambiguous:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001672 if (InitEntity)
1673 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1674 else
1675 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00001676 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1677 return 0;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001678
1679 case OR_Deleted:
1680 if (InitEntity)
1681 Diag(Loc, diag::err_ovl_deleted_init)
1682 << Best->Function->isDeleted()
1683 << InitEntity << Range;
1684 else
1685 Diag(Loc, diag::err_ovl_deleted_init)
1686 << Best->Function->isDeleted()
1687 << InitEntity << Range;
1688 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1689 return 0;
Douglas Gregor5870a952008-11-03 20:45:27 +00001690 }
1691
1692 return 0;
1693}
1694
Douglas Gregor81c29152008-10-29 00:13:59 +00001695/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1696/// determine whether they are reference-related,
1697/// reference-compatible, reference-compatible with added
1698/// qualification, or incompatible, for use in C++ initialization by
1699/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1700/// type, and the first type (T1) is the pointee type of the reference
1701/// type being initialized.
1702Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001703Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1704 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001705 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1706 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1707
1708 T1 = Context.getCanonicalType(T1);
1709 T2 = Context.getCanonicalType(T2);
1710 QualType UnqualT1 = T1.getUnqualifiedType();
1711 QualType UnqualT2 = T2.getUnqualifiedType();
1712
1713 // C++ [dcl.init.ref]p4:
1714 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1715 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1716 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001717 if (UnqualT1 == UnqualT2)
1718 DerivedToBase = false;
1719 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1720 DerivedToBase = true;
1721 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001722 return Ref_Incompatible;
1723
1724 // At this point, we know that T1 and T2 are reference-related (at
1725 // least).
1726
1727 // C++ [dcl.init.ref]p4:
1728 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1729 // reference-related to T2 and cv1 is the same cv-qualification
1730 // as, or greater cv-qualification than, cv2. For purposes of
1731 // overload resolution, cases for which cv1 is greater
1732 // cv-qualification than cv2 are identified as
1733 // reference-compatible with added qualification (see 13.3.3.2).
1734 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1735 return Ref_Compatible;
1736 else if (T1.isMoreQualifiedThan(T2))
1737 return Ref_Compatible_With_Added_Qualification;
1738 else
1739 return Ref_Related;
1740}
1741
1742/// CheckReferenceInit - Check the initialization of a reference
1743/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1744/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001745/// list), and DeclType is the type of the declaration. When ICS is
1746/// non-null, this routine will compute the implicit conversion
1747/// sequence according to C++ [over.ics.ref] and will not produce any
1748/// diagnostics; when ICS is null, it will emit diagnostics when any
1749/// errors are found. Either way, a return value of true indicates
1750/// that there was a failure, a return value of false indicates that
1751/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001752///
1753/// When @p SuppressUserConversions, user-defined conversions are
1754/// suppressed.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001755/// When @p AllowExplicit, we also permit explicit user-defined
1756/// conversion functions.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001757bool
1758Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001759 ImplicitConversionSequence *ICS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001760 bool SuppressUserConversions,
1761 bool AllowExplicit) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001762 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1763
1764 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1765 QualType T2 = Init->getType();
1766
Douglas Gregor45014fd2008-11-10 20:40:00 +00001767 // If the initializer is the address of an overloaded function, try
1768 // to resolve the overloaded function. If all goes well, T2 is the
1769 // type of the resulting function.
1770 if (T2->isOverloadType()) {
1771 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1772 ICS != 0);
1773 if (Fn) {
1774 // Since we're performing this reference-initialization for
1775 // real, update the initializer with the resulting function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00001776 if (!ICS) {
1777 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
1778 return true;
1779
Douglas Gregor45014fd2008-11-10 20:40:00 +00001780 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregoraa57e862009-02-18 21:56:37 +00001781 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00001782
1783 T2 = Fn->getType();
1784 }
1785 }
1786
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001787 // Compute some basic properties of the types and the initializer.
1788 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001789 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001790 ReferenceCompareResult RefRelationship
1791 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1792
1793 // Most paths end in a failed conversion.
1794 if (ICS)
1795 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001796
1797 // C++ [dcl.init.ref]p5:
1798 // A reference to type “cv1 T1” is initialized by an expression
1799 // of type “cv2 T2” as follows:
1800
1801 // -- If the initializer expression
1802
1803 bool BindsDirectly = false;
1804 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1805 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001806 //
1807 // Note that the bit-field check is skipped if we are just computing
1808 // the implicit conversion sequence (C++ [over.best.ics]p2).
1809 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1810 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001811 BindsDirectly = true;
1812
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001813 if (ICS) {
1814 // C++ [over.ics.ref]p1:
1815 // When a parameter of reference type binds directly (8.5.3)
1816 // to an argument expression, the implicit conversion sequence
1817 // is the identity conversion, unless the argument expression
1818 // has a type that is a derived class of the parameter type,
1819 // in which case the implicit conversion sequence is a
1820 // derived-to-base Conversion (13.3.3.1).
1821 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1822 ICS->Standard.First = ICK_Identity;
1823 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1824 ICS->Standard.Third = ICK_Identity;
1825 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1826 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001827 ICS->Standard.ReferenceBinding = true;
1828 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001829
1830 // Nothing more to do: the inaccessibility/ambiguity check for
1831 // derived-to-base conversions is suppressed when we're
1832 // computing the implicit conversion sequence (C++
1833 // [over.best.ics]p2).
1834 return false;
1835 } else {
1836 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001837 // FIXME: Binding to a subobject of the lvalue is going to require
1838 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001839 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001840 }
1841 }
1842
1843 // -- has a class type (i.e., T2 is a class type) and can be
1844 // implicitly converted to an lvalue of type “cv3 T3,”
1845 // where “cv1 T1” is reference-compatible with “cv3 T3”
1846 // 92) (this conversion is selected by enumerating the
1847 // applicable conversion functions (13.3.1.6) and choosing
1848 // the best one through overload resolution (13.3)),
Douglas Gregore6985fe2008-11-10 16:14:15 +00001849 if (!SuppressUserConversions && T2->isRecordType()) {
1850 // FIXME: Look for conversions in base classes!
1851 CXXRecordDecl *T2RecordDecl
1852 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00001853
Douglas Gregore6985fe2008-11-10 16:14:15 +00001854 OverloadCandidateSet CandidateSet;
1855 OverloadedFunctionDecl *Conversions
1856 = T2RecordDecl->getConversionFunctions();
1857 for (OverloadedFunctionDecl::function_iterator Func
1858 = Conversions->function_begin();
1859 Func != Conversions->function_end(); ++Func) {
1860 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1861
1862 // If the conversion function doesn't return a reference type,
1863 // it can't be considered for this conversion.
1864 // FIXME: This will change when we support rvalue references.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001865 if (Conv->getConversionType()->isReferenceType() &&
1866 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregore6985fe2008-11-10 16:14:15 +00001867 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1868 }
1869
1870 OverloadCandidateSet::iterator Best;
1871 switch (BestViableFunction(CandidateSet, Best)) {
1872 case OR_Success:
1873 // This is a direct binding.
1874 BindsDirectly = true;
1875
1876 if (ICS) {
1877 // C++ [over.ics.ref]p1:
1878 //
1879 // [...] If the parameter binds directly to the result of
1880 // applying a conversion function to the argument
1881 // expression, the implicit conversion sequence is a
1882 // user-defined conversion sequence (13.3.3.1.2), with the
1883 // second standard conversion sequence either an identity
1884 // conversion or, if the conversion function returns an
1885 // entity of a type that is a derived class of the parameter
1886 // type, a derived-to-base Conversion.
1887 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1888 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1889 ICS->UserDefined.After = Best->FinalConversion;
1890 ICS->UserDefined.ConversionFunction = Best->Function;
1891 assert(ICS->UserDefined.After.ReferenceBinding &&
1892 ICS->UserDefined.After.DirectBinding &&
1893 "Expected a direct reference binding!");
1894 return false;
1895 } else {
1896 // Perform the conversion.
1897 // FIXME: Binding to a subobject of the lvalue is going to require
1898 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001899 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00001900 }
1901 break;
1902
1903 case OR_Ambiguous:
1904 assert(false && "Ambiguous reference binding conversions not implemented.");
1905 return true;
1906
1907 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001908 case OR_Deleted:
1909 // There was no suitable conversion, or we found a deleted
1910 // conversion; continue with other checks.
Douglas Gregore6985fe2008-11-10 16:14:15 +00001911 break;
1912 }
1913 }
1914
Douglas Gregor81c29152008-10-29 00:13:59 +00001915 if (BindsDirectly) {
1916 // C++ [dcl.init.ref]p4:
1917 // [...] In all cases where the reference-related or
1918 // reference-compatible relationship of two types is used to
1919 // establish the validity of a reference binding, and T1 is a
1920 // base class of T2, a program that necessitates such a binding
1921 // is ill-formed if T1 is an inaccessible (clause 11) or
1922 // ambiguous (10.2) base class of T2.
1923 //
1924 // Note that we only check this condition when we're allowed to
1925 // complain about errors, because we should not be checking for
1926 // ambiguity (or inaccessibility) unless the reference binding
1927 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001928 if (DerivedToBase)
1929 return CheckDerivedToBaseConversion(T2, T1,
1930 Init->getSourceRange().getBegin(),
1931 Init->getSourceRange());
1932 else
1933 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001934 }
1935
1936 // -- Otherwise, the reference shall be to a non-volatile const
1937 // type (i.e., cv1 shall be const).
1938 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001939 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001940 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001941 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001942 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1943 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001944 return true;
1945 }
1946
1947 // -- If the initializer expression is an rvalue, with T2 a
1948 // class type, and “cv1 T1” is reference-compatible with
1949 // “cv2 T2,” the reference is bound in one of the
1950 // following ways (the choice is implementation-defined):
1951 //
1952 // -- The reference is bound to the object represented by
1953 // the rvalue (see 3.10) or to a sub-object within that
1954 // object.
1955 //
1956 // -- A temporary of type “cv1 T2” [sic] is created, and
1957 // a constructor is called to copy the entire rvalue
1958 // object into the temporary. The reference is bound to
1959 // the temporary or to a sub-object within the
1960 // temporary.
1961 //
Douglas Gregor81c29152008-10-29 00:13:59 +00001962 // The constructor that would be used to make the copy
1963 // shall be callable whether or not the copy is actually
1964 // done.
1965 //
1966 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1967 // freedom, so we will always take the first option and never build
1968 // a temporary in this case. FIXME: We will, however, have to check
1969 // for the presence of a copy constructor in C++98/03 mode.
1970 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001971 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1972 if (ICS) {
1973 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1974 ICS->Standard.First = ICK_Identity;
1975 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1976 ICS->Standard.Third = ICK_Identity;
1977 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1978 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001979 ICS->Standard.ReferenceBinding = true;
1980 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001981 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001982 // FIXME: Binding to a subobject of the rvalue is going to require
1983 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001984 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001985 }
1986 return false;
1987 }
1988
1989 // -- Otherwise, a temporary of type “cv1 T1” is created and
1990 // initialized from the initializer expression using the
1991 // rules for a non-reference copy initialization (8.5). The
1992 // reference is then bound to the temporary. If T1 is
1993 // reference-related to T2, cv1 must be the same
1994 // cv-qualification as, or greater cv-qualification than,
1995 // cv2; otherwise, the program is ill-formed.
1996 if (RefRelationship == Ref_Related) {
1997 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1998 // we would be reference-compatible or reference-compatible with
1999 // added qualification. But that wasn't the case, so the reference
2000 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002001 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00002002 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00002003 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002004 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2005 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00002006 return true;
2007 }
2008
Douglas Gregorb206cc42009-01-30 23:27:23 +00002009 // If at least one of the types is a class type, the types are not
2010 // related, and we aren't allowed any user conversions, the
2011 // reference binding fails. This case is important for breaking
2012 // recursion, since TryImplicitConversion below will attempt to
2013 // create a temporary through the use of a copy constructor.
2014 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2015 (T1->isRecordType() || T2->isRecordType())) {
2016 if (!ICS)
2017 Diag(Init->getSourceRange().getBegin(),
2018 diag::err_typecheck_convert_incompatible)
2019 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2020 return true;
2021 }
2022
Douglas Gregor81c29152008-10-29 00:13:59 +00002023 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002024 if (ICS) {
2025 /// C++ [over.ics.ref]p2:
2026 ///
2027 /// When a parameter of reference type is not bound directly to
2028 /// an argument expression, the conversion sequence is the one
2029 /// required to convert the argument expression to the
2030 /// underlying type of the reference according to
2031 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
2032 /// to copy-initializing a temporary of the underlying type with
2033 /// the argument expression. Any difference in top-level
2034 /// cv-qualification is subsumed by the initialization itself
2035 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002036 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002037 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2038 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00002039 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002040 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002041}
Douglas Gregore60e5d32008-11-06 22:13:31 +00002042
2043/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2044/// of this overloaded operator is well-formed. If so, returns false;
2045/// otherwise, emits appropriate diagnostics and returns true.
2046bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002047 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00002048 "Expected an overloaded operator declaration");
2049
Douglas Gregore60e5d32008-11-06 22:13:31 +00002050 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2051
2052 // C++ [over.oper]p5:
2053 // The allocation and deallocation functions, operator new,
2054 // operator new[], operator delete and operator delete[], are
2055 // described completely in 3.7.3. The attributes and restrictions
2056 // found in the rest of this subclause do not apply to them unless
2057 // explicitly stated in 3.7.3.
2058 // FIXME: Write a separate routine for checking this. For now, just
2059 // allow it.
2060 if (Op == OO_New || Op == OO_Array_New ||
2061 Op == OO_Delete || Op == OO_Array_Delete)
2062 return false;
2063
2064 // C++ [over.oper]p6:
2065 // An operator function shall either be a non-static member
2066 // function or be a non-member function and have at least one
2067 // parameter whose type is a class, a reference to a class, an
2068 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002069 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2070 if (MethodDecl->isStatic())
2071 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002072 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002073 } else {
2074 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002075 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2076 ParamEnd = FnDecl->param_end();
2077 Param != ParamEnd; ++Param) {
2078 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002079 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2080 ClassOrEnumParam = true;
2081 break;
2082 }
2083 }
2084
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002085 if (!ClassOrEnumParam)
2086 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002087 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00002088 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002089 }
2090
2091 // C++ [over.oper]p8:
2092 // An operator function cannot have default arguments (8.3.6),
2093 // except where explicitly stated below.
2094 //
2095 // Only the function-call operator allows default arguments
2096 // (C++ [over.call]p1).
2097 if (Op != OO_Call) {
2098 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2099 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002100 if ((*Param)->hasUnparsedDefaultArg())
2101 return Diag((*Param)->getLocation(),
2102 diag::err_operator_overload_default_arg)
2103 << FnDecl->getDeclName();
2104 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002105 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00002106 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00002107 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002108 }
2109 }
2110
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002111 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2112 { false, false, false }
2113#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2114 , { Unary, Binary, MemberOnly }
2115#include "clang/Basic/OperatorKinds.def"
2116 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00002117
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002118 bool CanBeUnaryOperator = OperatorUses[Op][0];
2119 bool CanBeBinaryOperator = OperatorUses[Op][1];
2120 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00002121
2122 // C++ [over.oper]p8:
2123 // [...] Operator functions cannot have more or fewer parameters
2124 // than the number required for the corresponding operator, as
2125 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002126 unsigned NumParams = FnDecl->getNumParams()
2127 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002128 if (Op != OO_Call &&
2129 ((NumParams == 1 && !CanBeUnaryOperator) ||
2130 (NumParams == 2 && !CanBeBinaryOperator) ||
2131 (NumParams < 1) || (NumParams > 2))) {
2132 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00002133 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002134 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002135 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002136 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002137 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002138 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00002139 assert(CanBeBinaryOperator &&
2140 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00002141 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002142 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00002143
Chris Lattnerbb002332008-11-21 07:57:12 +00002144 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00002145 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002146 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002147
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002148 // Overloaded operators other than operator() cannot be variadic.
2149 if (Op != OO_Call &&
Douglas Gregor4fa58902009-02-26 23:50:07 +00002150 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002151 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00002152 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002153 }
2154
2155 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002156 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2157 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002158 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00002159 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002160 }
2161
2162 // C++ [over.inc]p1:
2163 // The user-defined function called operator++ implements the
2164 // prefix and postfix ++ operator. If this function is a member
2165 // function with no parameters, or a non-member function with one
2166 // parameter of class or enumeration type, it defines the prefix
2167 // increment operator ++ for objects of that type. If the function
2168 // is a member function with one parameter (which shall be of type
2169 // int) or a non-member function with two parameters (the second
2170 // of which shall be of type int), it defines the postfix
2171 // increment operator ++ for objects of that type.
2172 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2173 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2174 bool ParamIsInt = false;
2175 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2176 ParamIsInt = BT->getKind() == BuiltinType::Int;
2177
Chris Lattnera7021ee2008-11-21 07:50:02 +00002178 if (!ParamIsInt)
2179 return Diag(LastParam->getLocation(),
2180 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002181 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002182 }
2183
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002184 // Notify the class if it got an assignment operator.
2185 if (Op == OO_Equal) {
2186 // Would have returned earlier otherwise.
2187 assert(isa<CXXMethodDecl>(FnDecl) &&
2188 "Overloaded = not member, but not filtered.");
2189 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2190 Method->getParent()->addedAssignmentOperator(Context, Method);
2191 }
2192
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002193 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002194}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002195
Douglas Gregord8028382009-01-05 19:45:36 +00002196/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2197/// linkage specification, including the language and (if present)
2198/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2199/// the location of the language string literal, which is provided
2200/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2201/// the '{' brace. Otherwise, this linkage specification does not
2202/// have any braces.
2203Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2204 SourceLocation ExternLoc,
2205 SourceLocation LangLoc,
2206 const char *Lang,
2207 unsigned StrSize,
2208 SourceLocation LBraceLoc) {
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002209 LinkageSpecDecl::LanguageIDs Language;
2210 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2211 Language = LinkageSpecDecl::lang_c;
2212 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2213 Language = LinkageSpecDecl::lang_cxx;
2214 else {
Douglas Gregord8028382009-01-05 19:45:36 +00002215 Diag(LangLoc, diag::err_bad_language);
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002216 return 0;
2217 }
2218
2219 // FIXME: Add all the various semantics of linkage specifications
2220
Douglas Gregord8028382009-01-05 19:45:36 +00002221 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2222 LangLoc, Language,
2223 LBraceLoc.isValid());
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002224 CurContext->addDecl(D);
Douglas Gregord8028382009-01-05 19:45:36 +00002225 PushDeclContext(S, D);
2226 return D;
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002227}
2228
Douglas Gregord8028382009-01-05 19:45:36 +00002229/// ActOnFinishLinkageSpecification - Completely the definition of
2230/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2231/// valid, it's the position of the closing '}' brace in a linkage
2232/// specification that uses braces.
2233Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2234 DeclTy *LinkageSpec,
2235 SourceLocation RBraceLoc) {
2236 if (LinkageSpec)
2237 PopDeclContext();
2238 return LinkageSpec;
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002239}
2240
Sebastian Redl743c8162008-12-22 19:15:10 +00002241/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2242/// handler.
2243Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2244{
2245 QualType ExDeclType = GetTypeForDeclarator(D, S);
2246 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2247
2248 bool Invalid = false;
2249
2250 // Arrays and functions decay.
2251 if (ExDeclType->isArrayType())
2252 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2253 else if (ExDeclType->isFunctionType())
2254 ExDeclType = Context.getPointerType(ExDeclType);
2255
2256 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2257 // The exception-declaration shall not denote a pointer or reference to an
2258 // incomplete type, other than [cv] void*.
2259 QualType BaseType = ExDeclType;
2260 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002261 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl743c8162008-12-22 19:15:10 +00002262 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2263 BaseType = Ptr->getPointeeType();
2264 Mode = 1;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002265 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl743c8162008-12-22 19:15:10 +00002266 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2267 BaseType = Ref->getPointeeType();
2268 Mode = 2;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002269 DK = diag::err_catch_incomplete_ref;
Sebastian Redl743c8162008-12-22 19:15:10 +00002270 }
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002271 if ((Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorc84d8932009-03-09 16:13:40 +00002272 RequireCompleteType(Begin, BaseType, DK))
Sebastian Redl743c8162008-12-22 19:15:10 +00002273 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00002274
Sebastian Redl237116b2008-12-22 21:35:02 +00002275 // FIXME: Need to test for ability to copy-construct and destroy the
2276 // exception variable.
2277 // FIXME: Need to check for abstract classes.
2278
Sebastian Redl743c8162008-12-22 19:15:10 +00002279 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor09be81b2009-02-04 17:27:36 +00002280 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl743c8162008-12-22 19:15:10 +00002281 // The scope should be freshly made just for us. There is just no way
2282 // it contains any previous declaration.
2283 assert(!S->isDeclScope(PrevDecl));
2284 if (PrevDecl->isTemplateParameter()) {
2285 // Maybe we will complain about the shadowed template parameter.
2286 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2287
2288 }
2289 }
2290
2291 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002292 II, ExDeclType, VarDecl::None, Begin);
Sebastian Redl743c8162008-12-22 19:15:10 +00002293 if (D.getInvalidType() || Invalid)
2294 ExDecl->setInvalidDecl();
2295
2296 if (D.getCXXScopeSpec().isSet()) {
2297 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2298 << D.getCXXScopeSpec().getRange();
2299 ExDecl->setInvalidDecl();
2300 }
2301
2302 // Add the exception declaration into this scope.
2303 S->AddDecl(ExDecl);
2304 if (II)
2305 IdResolver.AddDecl(ExDecl);
2306
2307 ProcessDeclAttributes(ExDecl, D);
2308 return ExDecl;
2309}