blob: 3e8ee5ed1f706e5d72a4f3cc2551843e7e199a25 [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.
353 if (DiagnoseIncompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
354 SpecifierRange))
355 return 0;
356
357 // If the base class is polymorphic, the new one is, too.
358 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
359 assert(BaseDecl && "Record type has no declaration");
360 BaseDecl = BaseDecl->getDefinition(Context);
361 assert(BaseDecl && "Base type is not incomplete, but has no definition");
362 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
363 Class->setPolymorphic(true);
364
365 // C++ [dcl.init.aggr]p1:
366 // An aggregate is [...] a class with [...] no base classes [...].
367 Class->setAggregate(false);
368 Class->setPOD(false);
369
370 // Create the base specifier.
371 // FIXME: Allocate via ASTContext?
372 return new CXXBaseSpecifier(SpecifierRange, Virtual,
373 Class->getTagKind() == RecordDecl::TK_class,
374 Access, BaseType);
375}
376
Douglas 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 Gregored3a3982009-03-03 04:44:36 +0000386 CXXRecordDecl *Class = (CXXRecordDecl*)classdecl;
Douglas Gregora60c62e2009-02-09 15:09:02 +0000387 QualType BaseType = QualType::getFromOpaquePtr(basetype);
Douglas Gregored3a3982009-03-03 04:44:36 +0000388 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
389 Virtual, Access,
390 BaseType, BaseLoc))
391 return BaseSpec;
392
393 return true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000394}
Douglas Gregorec93f442008-04-13 21:30:24 +0000395
Douglas Gregored3a3982009-03-03 04:44:36 +0000396/// \brief Performs the actual work of attaching the given base class
397/// specifiers to a C++ class.
398bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
399 unsigned NumBases) {
400 if (NumBases == 0)
401 return false;
Douglas Gregorabed2172008-10-22 17:49:05 +0000402
403 // Used to keep track of which base types we have already seen, so
404 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000405 // that the key is always the unqualified canonical type of the base
406 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000407 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
408
409 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000410 unsigned NumGoodBases = 0;
Douglas Gregored3a3982009-03-03 04:44:36 +0000411 bool Invalid = false;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000412 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000413 QualType NewBaseType
Douglas Gregored3a3982009-03-03 04:44:36 +0000414 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor4fd85902008-10-23 18:13:27 +0000415 NewBaseType = NewBaseType.getUnqualifiedType();
416
Douglas Gregorabed2172008-10-22 17:49:05 +0000417 if (KnownBaseTypes[NewBaseType]) {
418 // C++ [class.mi]p3:
419 // A class shall not be specified as a direct base class of a
420 // derived class more than once.
Douglas Gregored3a3982009-03-03 04:44:36 +0000421 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000422 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000423 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregored3a3982009-03-03 04:44:36 +0000424 << Bases[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000425
426 // Delete the duplicate base class specifier; we're going to
427 // overwrite its pointer later.
Douglas Gregored3a3982009-03-03 04:44:36 +0000428 delete Bases[idx];
429
430 Invalid = true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000431 } else {
432 // Okay, add this new base class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000433 KnownBaseTypes[NewBaseType] = Bases[idx];
434 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000435 }
436 }
437
438 // Attach the remaining base class specifiers to the derived class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000439 Class->setBases(Bases, NumGoodBases);
Douglas Gregor4fd85902008-10-23 18:13:27 +0000440
441 // Delete the remaining (good) base class specifiers, since their
442 // data has been copied into the CXXRecordDecl.
443 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregored3a3982009-03-03 04:44:36 +0000444 delete Bases[idx];
445
446 return Invalid;
447}
448
449/// ActOnBaseSpecifiers - Attach the given base specifiers to the
450/// class, after checking whether there are any duplicate base
451/// classes.
452void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
453 unsigned NumBases) {
454 if (!ClassDecl || !Bases || !NumBases)
455 return;
456
457 AdjustDeclIfTemplate(ClassDecl);
458 AttachBaseSpecifiers(cast<CXXRecordDecl>((Decl*)ClassDecl),
459 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregorec93f442008-04-13 21:30:24 +0000460}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000461
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000462//===----------------------------------------------------------------------===//
463// C++ class member Handling
464//===----------------------------------------------------------------------===//
465
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000466/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
467/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
468/// bitfield width if there is one and 'InitExpr' specifies the initializer if
469/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
470/// declarators on it.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000471Sema::DeclTy *
472Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
473 ExprTy *BW, ExprTy *InitExpr,
474 DeclTy *LastInGroup) {
475 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000476 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000477 Expr *BitWidth = static_cast<Expr*>(BW);
478 Expr *Init = static_cast<Expr*>(InitExpr);
479 SourceLocation Loc = D.getIdentifierLoc();
480
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000481 bool isFunc = D.isFunctionDeclarator();
482
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000483 // C++ 9.2p6: A member shall not be declared to have automatic storage
484 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000485 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
486 // data members and cannot be applied to names declared const or static,
487 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000488 switch (DS.getStorageClassSpec()) {
489 case DeclSpec::SCS_unspecified:
490 case DeclSpec::SCS_typedef:
491 case DeclSpec::SCS_static:
492 // FALL THROUGH.
493 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000494 case DeclSpec::SCS_mutable:
495 if (isFunc) {
496 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000497 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000498 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000499 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
500
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000501 // FIXME: It would be nicer if the keyword was ignored only for this
502 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000503 D.getMutableDeclSpec().ClearStorageClassSpecs();
504 } else {
505 QualType T = GetTypeForDeclarator(D, S);
506 diag::kind err = static_cast<diag::kind>(0);
507 if (T->isReferenceType())
508 err = diag::err_mutable_reference;
509 else if (T.isConstQualified())
510 err = diag::err_mutable_const;
511 if (err != 0) {
512 if (DS.getStorageClassSpecLoc().isValid())
513 Diag(DS.getStorageClassSpecLoc(), err);
514 else
515 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000516 // FIXME: It would be nicer if the keyword was ignored only for this
517 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000518 D.getMutableDeclSpec().ClearStorageClassSpecs();
519 }
520 }
521 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000522 default:
523 if (DS.getStorageClassSpecLoc().isValid())
524 Diag(DS.getStorageClassSpecLoc(),
525 diag::err_storageclass_invalid_for_member);
526 else
527 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
528 D.getMutableDeclSpec().ClearStorageClassSpecs();
529 }
530
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000531 if (!isFunc &&
Douglas Gregora60c62e2009-02-09 15:09:02 +0000532 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000533 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000534 // Check also for this case:
535 //
536 // typedef int f();
537 // f a;
538 //
Douglas Gregora60c62e2009-02-09 15:09:02 +0000539 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
540 isFunc = TDType->isFunctionType();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000541 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000542
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000543 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
544 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000545 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000546
547 Decl *Member;
548 bool InvalidDecl = false;
549
550 if (isInstField)
Douglas Gregor8acb7272008-12-11 16:49:14 +0000551 Member = static_cast<Decl*>(ActOnField(S, cast<CXXRecordDecl>(CurContext),
552 Loc, D, BitWidth));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000553 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000554 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000555
556 if (!Member) return LastInGroup;
557
Douglas Gregor6704b312008-11-17 22:58:34 +0000558 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000559
560 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
561 // specific methods. Use a wrapper class that can be used with all C++ class
562 // member decls.
563 CXXClassMemberWrapper(Member).setAccess(AS);
564
Douglas Gregor15e04622008-11-05 16:20:31 +0000565 // C++ [dcl.init.aggr]p1:
566 // An aggregate is an array or a class (clause 9) with [...] no
567 // private or protected non-static data members (clause 11).
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000568 // A POD must be an aggregate.
569 if (isInstField && (AS == AS_private || AS == AS_protected)) {
570 CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext);
571 Record->setAggregate(false);
572 Record->setPOD(false);
573 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000574
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000575 if (DS.isVirtualSpecified()) {
576 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
577 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
578 InvalidDecl = true;
579 } else {
Sebastian Redl83faa292009-01-09 19:57:06 +0000580 cast<CXXMethodDecl>(Member)->setVirtual();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000581 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
582 CurClass->setAggregate(false);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000583 CurClass->setPOD(false);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000584 CurClass->setPolymorphic(true);
585 }
586 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000587
Sebastian Redl83faa292009-01-09 19:57:06 +0000588 // FIXME: The above definition of virtual is not sufficient. A function is
589 // also virtual if it overrides an already virtual function. This is important
590 // to do here because it decides the validity of a pure specifier.
591
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000592 if (BitWidth) {
593 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
594 // constant-expression be a value equal to zero.
595 // FIXME: Check this.
596
597 if (D.isFunctionDeclarator()) {
598 // FIXME: Emit diagnostic about only constructors taking base initializers
599 // or something similar, when constructor support is in place.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000600 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000601 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000602 InvalidDecl = true;
603
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000604 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000605 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000606 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000607 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000608 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000609 InvalidDecl = true;
610 }
611
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000612 } else if (isa<FunctionDecl>(Member)) {
613 // A function typedef ("typedef int f(); f a;").
614 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000615 Diag(Loc, diag::err_not_integral_type_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000616 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000617 InvalidDecl = true;
618
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000619 } else if (isa<TypedefDecl>(Member)) {
620 // "cannot declare 'A' to be a bit-field type"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000621 Diag(Loc, diag::err_not_bitfield_type)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000622 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000623 InvalidDecl = true;
624
625 } else {
626 assert(isa<CXXClassVarDecl>(Member) &&
627 "Didn't we cover all member kinds?");
628 // C++ 9.6p3: A bit-field shall not be a static member.
629 // "static member 'A' cannot be a bit-field"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000630 Diag(Loc, diag::err_static_not_bitfield)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000631 << Name << BitWidth->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000632 InvalidDecl = true;
633 }
634 }
635
636 if (Init) {
637 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
638 // if it declares a static member of const integral or const enumeration
639 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000640 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
641 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000642 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000643 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000644 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
645 CVD->getType()->isIntegralType()) {
646 // constant-initializer
647 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000648 InvalidDecl = true;
649
650 } else {
651 // not const integral.
Chris Lattner77d52da2008-11-20 06:06:08 +0000652 Diag(Loc, diag::err_member_initialization)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000653 << Name << Init->getSourceRange();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000654 InvalidDecl = true;
655 }
656
657 } else {
Sebastian Redl83faa292009-01-09 19:57:06 +0000658 // not static member. perhaps virtual function?
659 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
Sebastian Redl54e4be92009-01-09 22:29:03 +0000660 // With declarators parsed the way they are, the parser cannot
661 // distinguish between a normal initializer and a pure-specifier.
662 // Thus this grotesque test.
Sebastian Redl83faa292009-01-09 19:57:06 +0000663 IntegerLiteral *IL;
664 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
665 Context.getCanonicalType(IL->getType()) == Context.IntTy) {
666 if (MD->isVirtual())
667 MD->setPure();
668 else {
669 Diag(Loc, diag::err_non_virtual_pure)
670 << Name << Init->getSourceRange();
671 InvalidDecl = true;
672 }
673 } else {
674 Diag(Loc, diag::err_member_function_initialization)
675 << Name << Init->getSourceRange();
676 InvalidDecl = true;
677 }
678 } else {
679 Diag(Loc, diag::err_member_initialization)
680 << Name << Init->getSourceRange();
681 InvalidDecl = true;
682 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000683 }
684 }
685
686 if (InvalidDecl)
687 Member->setInvalidDecl();
688
689 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000690 FieldCollector->Add(cast<FieldDecl>(Member));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000691 return LastInGroup;
692 }
693 return Member;
694}
695
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000696/// ActOnMemInitializer - Handle a C++ member initializer.
697Sema::MemInitResult
698Sema::ActOnMemInitializer(DeclTy *ConstructorD,
699 Scope *S,
700 IdentifierInfo *MemberOrBase,
701 SourceLocation IdLoc,
702 SourceLocation LParenLoc,
703 ExprTy **Args, unsigned NumArgs,
704 SourceLocation *CommaLocs,
705 SourceLocation RParenLoc) {
706 CXXConstructorDecl *Constructor
707 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
708 if (!Constructor) {
709 // The user wrote a constructor initializer on a function that is
710 // not a C++ constructor. Ignore the error for now, because we may
711 // have more member initializers coming; we'll diagnose it just
712 // once in ActOnMemInitializers.
713 return true;
714 }
715
716 CXXRecordDecl *ClassDecl = Constructor->getParent();
717
718 // C++ [class.base.init]p2:
719 // Names in a mem-initializer-id are looked up in the scope of the
720 // constructor’s class and, if not found in that scope, are looked
721 // up in the scope containing the constructor’s
722 // definition. [Note: if the constructor’s class contains a member
723 // with the same name as a direct or virtual base class of the
724 // class, a mem-initializer-id naming the member or base class and
725 // composed of a single identifier refers to the class member. A
726 // mem-initializer-id for the hidden base class may be specified
727 // using a qualified name. ]
728 // Look for a member, first.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000729 FieldDecl *Member = 0;
Steve Naroffab63fd62009-01-08 17:28:14 +0000730 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000731 if (Result.first != Result.second)
732 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000733
734 // FIXME: Handle members of an anonymous union.
735
736 if (Member) {
737 // FIXME: Perform direct initialization of the member.
738 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
739 }
740
741 // It didn't name a member, so see if it names a class.
Douglas Gregor1075a162009-02-04 17:00:24 +0000742 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000743 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000744 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
745 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000746
Douglas Gregora60c62e2009-02-09 15:09:02 +0000747 QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000748 if (!BaseType->isRecordType())
Chris Lattner65cae292008-11-19 08:23:25 +0000749 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattnerb1753422008-11-23 21:45:46 +0000750 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000751
752 // C++ [class.base.init]p2:
753 // [...] Unless the mem-initializer-id names a nonstatic data
754 // member of the constructor’s class or a direct or virtual base
755 // of that class, the mem-initializer is ill-formed. A
756 // mem-initializer-list can initialize a base class using any
757 // name that denotes that base class type.
758
759 // First, check for a direct base class.
760 const CXXBaseSpecifier *DirectBaseSpec = 0;
761 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
762 Base != ClassDecl->bases_end(); ++Base) {
763 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
764 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
765 // We found a direct base of this type. That's what we're
766 // initializing.
767 DirectBaseSpec = &*Base;
768 break;
769 }
770 }
771
772 // Check for a virtual base class.
773 // FIXME: We might be able to short-circuit this if we know in
774 // advance that there are no virtual bases.
775 const CXXBaseSpecifier *VirtualBaseSpec = 0;
776 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
777 // We haven't found a base yet; search the class hierarchy for a
778 // virtual base class.
779 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
780 /*DetectVirtual=*/false);
781 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
782 for (BasePaths::paths_iterator Path = Paths.begin();
783 Path != Paths.end(); ++Path) {
784 if (Path->back().Base->isVirtual()) {
785 VirtualBaseSpec = Path->back().Base;
786 break;
787 }
788 }
789 }
790 }
791
792 // C++ [base.class.init]p2:
793 // If a mem-initializer-id is ambiguous because it designates both
794 // a direct non-virtual base class and an inherited virtual base
795 // class, the mem-initializer is ill-formed.
796 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner65cae292008-11-19 08:23:25 +0000797 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
798 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000799
800 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
801}
802
803
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000804void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
805 DeclTy *TagDecl,
806 SourceLocation LBrac,
807 SourceLocation RBrac) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000808 TemplateDecl *Template = AdjustDeclIfTemplate(TagDecl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000809 ActOnFields(S, RLoc, TagDecl,
810 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000811 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregored3a3982009-03-03 04:44:36 +0000812
813 if (!Template)
814 AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000815}
816
Douglas Gregore640ab62008-11-03 17:51:48 +0000817/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
818/// special functions, such as the default constructor, copy
819/// constructor, or destructor, to the given C++ class (C++
820/// [special]p1). This routine can only be executed just before the
821/// definition of the class is complete.
822void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000823 QualType ClassType = Context.getTypeDeclType(ClassDecl);
824 ClassType = Context.getCanonicalType(ClassType);
825
Douglas Gregore640ab62008-11-03 17:51:48 +0000826 if (!ClassDecl->hasUserDeclaredConstructor()) {
827 // C++ [class.ctor]p5:
828 // A default constructor for a class X is a constructor of class X
829 // that can be called without an argument. If there is no
830 // user-declared constructor for class X, a default constructor is
831 // implicitly declared. An implicitly-declared default constructor
832 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000833 DeclarationName Name
834 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000835 CXXConstructorDecl *DefaultCon =
836 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000837 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000838 Context.getFunctionType(Context.VoidTy,
839 0, 0, false, 0),
840 /*isExplicit=*/false,
841 /*isInline=*/true,
842 /*isImplicitlyDeclared=*/true);
843 DefaultCon->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000844 DefaultCon->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000845 ClassDecl->addDecl(DefaultCon);
Douglas Gregorb9213832008-12-15 21:24:18 +0000846
847 // Notify the class that we've added a constructor.
848 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +0000849 }
850
851 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
852 // C++ [class.copy]p4:
853 // If the class definition does not explicitly declare a copy
854 // constructor, one is declared implicitly.
855
856 // C++ [class.copy]p5:
857 // The implicitly-declared copy constructor for a class X will
858 // have the form
859 //
860 // X::X(const X&)
861 //
862 // if
863 bool HasConstCopyConstructor = true;
864
865 // -- each direct or virtual base class B of X has a copy
866 // constructor whose first parameter is of type const B& or
867 // const volatile B&, and
868 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
869 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
870 const CXXRecordDecl *BaseClassDecl
871 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
872 HasConstCopyConstructor
873 = BaseClassDecl->hasConstCopyConstructor(Context);
874 }
875
876 // -- for all the nonstatic data members of X that are of a
877 // class type M (or array thereof), each such class type
878 // has a copy constructor whose first parameter is of type
879 // const M& or const volatile M&.
880 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
881 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
882 QualType FieldType = (*Field)->getType();
883 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
884 FieldType = Array->getElementType();
885 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
886 const CXXRecordDecl *FieldClassDecl
887 = cast<CXXRecordDecl>(FieldClassType->getDecl());
888 HasConstCopyConstructor
889 = FieldClassDecl->hasConstCopyConstructor(Context);
890 }
891 }
892
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000893 // Otherwise, the implicitly declared copy constructor will have
894 // the form
Douglas Gregore640ab62008-11-03 17:51:48 +0000895 //
896 // X::X(X&)
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000897 QualType ArgType = ClassType;
Douglas Gregore640ab62008-11-03 17:51:48 +0000898 if (HasConstCopyConstructor)
899 ArgType = ArgType.withConst();
900 ArgType = Context.getReferenceType(ArgType);
901
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000902 // An implicitly-declared copy constructor is an inline public
903 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000904 DeclarationName Name
905 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000906 CXXConstructorDecl *CopyConstructor
907 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000908 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000909 Context.getFunctionType(Context.VoidTy,
910 &ArgType, 1,
911 false, 0),
912 /*isExplicit=*/false,
913 /*isInline=*/true,
914 /*isImplicitlyDeclared=*/true);
915 CopyConstructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000916 CopyConstructor->setImplicit();
Douglas Gregore640ab62008-11-03 17:51:48 +0000917
918 // Add the parameter to the constructor.
919 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
920 ClassDecl->getLocation(),
921 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000922 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000923 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregore640ab62008-11-03 17:51:48 +0000924
Douglas Gregorb9213832008-12-15 21:24:18 +0000925 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000926 ClassDecl->addDecl(CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +0000927 }
928
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000929 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
930 // Note: The following rules are largely analoguous to the copy
931 // constructor rules. Note that virtual bases are not taken into account
932 // for determining the argument type of the operator. Note also that
933 // operators taking an object instead of a reference are allowed.
934 //
935 // C++ [class.copy]p10:
936 // If the class definition does not explicitly declare a copy
937 // assignment operator, one is declared implicitly.
938 // The implicitly-defined copy assignment operator for a class X
939 // will have the form
940 //
941 // X& X::operator=(const X&)
942 //
943 // if
944 bool HasConstCopyAssignment = true;
945
946 // -- each direct base class B of X has a copy assignment operator
947 // whose parameter is of type const B&, const volatile B& or B,
948 // and
949 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
950 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
951 const CXXRecordDecl *BaseClassDecl
952 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
953 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
954 }
955
956 // -- for all the nonstatic data members of X that are of a class
957 // type M (or array thereof), each such class type has a copy
958 // assignment operator whose parameter is of type const M&,
959 // const volatile M& or M.
960 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
961 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
962 QualType FieldType = (*Field)->getType();
963 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
964 FieldType = Array->getElementType();
965 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
966 const CXXRecordDecl *FieldClassDecl
967 = cast<CXXRecordDecl>(FieldClassType->getDecl());
968 HasConstCopyAssignment
969 = FieldClassDecl->hasConstCopyAssignment(Context);
970 }
971 }
972
973 // Otherwise, the implicitly declared copy assignment operator will
974 // have the form
975 //
976 // X& X::operator=(X&)
977 QualType ArgType = ClassType;
978 QualType RetType = Context.getReferenceType(ArgType);
979 if (HasConstCopyAssignment)
980 ArgType = ArgType.withConst();
981 ArgType = Context.getReferenceType(ArgType);
982
983 // An implicitly-declared copy assignment operator is an inline public
984 // member of its class.
985 DeclarationName Name =
986 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
987 CXXMethodDecl *CopyAssignment =
988 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
989 Context.getFunctionType(RetType, &ArgType, 1,
990 false, 0),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000991 /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000992 CopyAssignment->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000993 CopyAssignment->setImplicit();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000994
995 // Add the parameter to the operator.
996 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
997 ClassDecl->getLocation(),
998 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000999 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +00001000 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001001
1002 // Don't call addedAssignmentOperator. There is no way to distinguish an
1003 // implicit from an explicit assignment operator.
Douglas Gregor03b2ad22009-01-12 23:27:07 +00001004 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001005 }
1006
Douglas Gregorb9213832008-12-15 21:24:18 +00001007 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001008 // C++ [class.dtor]p2:
1009 // If a class has no user-declared destructor, a destructor is
1010 // declared implicitly. An implicitly-declared destructor is an
1011 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001012 DeclarationName Name
1013 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001014 CXXDestructorDecl *Destructor
1015 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +00001016 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001017 Context.getFunctionType(Context.VoidTy,
1018 0, 0, false, 0),
1019 /*isInline=*/true,
1020 /*isImplicitlyDeclared=*/true);
1021 Destructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001022 Destructor->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +00001023 ClassDecl->addDecl(Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001024 }
Douglas Gregore640ab62008-11-03 17:51:48 +00001025}
1026
Douglas Gregor605de8d2008-12-16 21:30:33 +00001027/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1028/// parsing a top-level (non-nested) C++ class, and we are now
1029/// parsing those parts of the given Method declaration that could
1030/// not be parsed earlier (C++ [class.mem]p2), such as default
1031/// arguments. This action should enter the scope of the given
1032/// Method declaration as if we had just parsed the qualified method
1033/// name. However, it should not bring the parameters into scope;
1034/// that will be performed by ActOnDelayedCXXMethodParameter.
1035void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
1036 CXXScopeSpec SS;
1037 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
1038 ActOnCXXEnterDeclaratorScope(S, SS);
1039}
1040
1041/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1042/// C++ method declaration. We're (re-)introducing the given
1043/// function parameter into scope for use in parsing later parts of
1044/// the method declaration. For example, we could see an
1045/// ActOnParamDefaultArgument event for this parameter.
1046void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1047 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001048
1049 // If this parameter has an unparsed default argument, clear it out
1050 // to make way for the parsed default argument.
1051 if (Param->hasUnparsedDefaultArg())
1052 Param->setDefaultArg(0);
1053
Douglas Gregor605de8d2008-12-16 21:30:33 +00001054 S->AddDecl(Param);
1055 if (Param->getDeclName())
1056 IdResolver.AddDecl(Param);
1057}
1058
1059/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1060/// processing the delayed method declaration for Method. The method
1061/// declaration is now considered finished. There may be a separate
1062/// ActOnStartOfFunctionDef action later (not necessarily
1063/// immediately!) for this method, if it was also defined inside the
1064/// class body.
1065void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1066 FunctionDecl *Method = (FunctionDecl*)MethodD;
1067 CXXScopeSpec SS;
1068 SS.setScopeRep(Method->getDeclContext());
1069 ActOnCXXExitDeclaratorScope(S, SS);
1070
1071 // Now that we have our default arguments, check the constructor
1072 // again. It could produce additional diagnostics or affect whether
1073 // the class has implicitly-declared destructors, among other
1074 // things.
1075 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1076 if (CheckConstructor(Constructor))
1077 Constructor->setInvalidDecl();
1078 }
1079
1080 // Check the default arguments, which we may have added.
1081 if (!Method->isInvalidDecl())
1082 CheckCXXDefaultArguments(Method);
1083}
1084
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001085/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +00001086/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001087/// R. If there are any errors in the declarator, this routine will
1088/// emit diagnostics and return true. Otherwise, it will return
1089/// false. Either way, the type @p R will be updated to reflect a
1090/// well-formed type for the constructor.
1091bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1092 FunctionDecl::StorageClass& SC) {
1093 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1094 bool isInvalid = false;
1095
1096 // C++ [class.ctor]p3:
1097 // A constructor shall not be virtual (10.3) or static (9.4). A
1098 // constructor can be invoked for a const, volatile or const
1099 // volatile object. A constructor shall not be declared const,
1100 // volatile, or const volatile (9.3.2).
1101 if (isVirtual) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001102 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1103 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1104 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001105 isInvalid = true;
1106 }
1107 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001108 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1109 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1110 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001111 isInvalid = true;
1112 SC = FunctionDecl::None;
1113 }
1114 if (D.getDeclSpec().hasTypeSpecifier()) {
1115 // Constructors don't have return types, but the parser will
1116 // happily parse something like:
1117 //
1118 // class X {
1119 // float X(float);
1120 // };
1121 //
1122 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001123 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1124 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1125 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001126 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00001127 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001128 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1129 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001130 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1131 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001132 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001133 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1134 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001135 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001136 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1137 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001138 }
1139
1140 // Rebuild the function type "R" without any type qualifiers (in
1141 // case any of the errors above fired) and with "void" as the
1142 // return type, since constructors don't have return types. We
1143 // *always* have to do this, because GetTypeForDeclarator will
1144 // put in a result type of "int" when none was specified.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001145 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001146 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1147 Proto->getNumArgs(),
1148 Proto->isVariadic(),
1149 0);
1150
1151 return isInvalid;
1152}
1153
Douglas Gregor605de8d2008-12-16 21:30:33 +00001154/// CheckConstructor - Checks a fully-formed constructor for
1155/// well-formedness, issuing any diagnostics required. Returns true if
1156/// the constructor declarator is invalid.
1157bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1158 if (Constructor->isInvalidDecl())
1159 return true;
1160
1161 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1162 bool Invalid = false;
1163
1164 // C++ [class.copy]p3:
1165 // A declaration of a constructor for a class X is ill-formed if
1166 // its first parameter is of type (optionally cv-qualified) X and
1167 // either there are no other parameters or else all other
1168 // parameters have default arguments.
1169 if ((Constructor->getNumParams() == 1) ||
1170 (Constructor->getNumParams() > 1 &&
1171 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1172 QualType ParamType = Constructor->getParamDecl(0)->getType();
1173 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1174 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1175 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1176 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1177 Invalid = true;
1178 }
1179 }
1180
1181 // Notify the class that we've added a constructor.
1182 ClassDecl->addedConstructor(Context, Constructor);
1183
1184 return Invalid;
1185}
1186
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001187/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1188/// the well-formednes of the destructor declarator @p D with type @p
1189/// R. If there are any errors in the declarator, this routine will
1190/// emit diagnostics and return true. Otherwise, it will return
1191/// false. Either way, the type @p R will be updated to reflect a
1192/// well-formed type for the destructor.
1193bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1194 FunctionDecl::StorageClass& SC) {
1195 bool isInvalid = false;
1196
1197 // C++ [class.dtor]p1:
1198 // [...] A typedef-name that names a class is a class-name
1199 // (7.1.3); however, a typedef-name that names a class shall not
1200 // be used as the identifier in the declarator for a destructor
1201 // declaration.
Douglas Gregora60c62e2009-02-09 15:09:02 +00001202 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1203 if (DeclaratorType->getAsTypedefType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001204 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregora60c62e2009-02-09 15:09:02 +00001205 << DeclaratorType;
Douglas Gregorbd19fdb2008-11-10 14:41:22 +00001206 isInvalid = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001207 }
1208
1209 // C++ [class.dtor]p2:
1210 // A destructor is used to destroy objects of its class type. A
1211 // destructor takes no parameters, and no return type can be
1212 // specified for it (not even void). The address of a destructor
1213 // shall not be taken. A destructor shall not be static. A
1214 // destructor can be invoked for a const, volatile or const
1215 // volatile object. A destructor shall not be declared const,
1216 // volatile or const volatile (9.3.2).
1217 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001218 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1219 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1220 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001221 isInvalid = true;
1222 SC = FunctionDecl::None;
1223 }
1224 if (D.getDeclSpec().hasTypeSpecifier()) {
1225 // Destructors don't have return types, but the parser will
1226 // happily parse something like:
1227 //
1228 // class X {
1229 // float ~X();
1230 // };
1231 //
1232 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001233 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1234 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1235 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001236 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00001237 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001238 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1239 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001240 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1241 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001242 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001243 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1244 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001245 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001246 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1247 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001248 }
1249
1250 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001251 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001252 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1253
1254 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001255 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001256 }
1257
1258 // Make sure the destructor isn't variadic.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001259 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001260 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1261
1262 // Rebuild the function type "R" without any type qualifiers or
1263 // parameters (in case any of the errors above fired) and with
1264 // "void" as the return type, since destructors don't have return
1265 // types. We *always* have to do this, because GetTypeForDeclarator
1266 // will put in a result type of "int" when none was specified.
1267 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1268
1269 return isInvalid;
1270}
1271
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001272/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1273/// well-formednes of the conversion function declarator @p D with
1274/// type @p R. If there are any errors in the declarator, this routine
1275/// will emit diagnostics and return true. Otherwise, it will return
1276/// false. Either way, the type @p R will be updated to reflect a
1277/// well-formed type for the conversion operator.
1278bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1279 FunctionDecl::StorageClass& SC) {
1280 bool isInvalid = false;
1281
1282 // C++ [class.conv.fct]p1:
1283 // Neither parameter types nor return type can be specified. The
1284 // type of a conversion function (8.3.5) is “function taking no
1285 // parameter returning conversion-type-id.”
1286 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001287 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1288 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1289 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001290 isInvalid = true;
1291 SC = FunctionDecl::None;
1292 }
1293 if (D.getDeclSpec().hasTypeSpecifier()) {
1294 // Conversion functions don't have return types, but the parser will
1295 // happily parse something like:
1296 //
1297 // class X {
1298 // float operator bool();
1299 // };
1300 //
1301 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001302 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1303 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1304 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001305 }
1306
1307 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001308 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001309 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1310
1311 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001312 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001313 }
1314
1315 // Make sure the conversion function isn't variadic.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001316 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001317 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1318
1319 // C++ [class.conv.fct]p4:
1320 // The conversion-type-id shall not represent a function type nor
1321 // an array type.
1322 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1323 if (ConvType->isArrayType()) {
1324 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1325 ConvType = Context.getPointerType(ConvType);
1326 } else if (ConvType->isFunctionType()) {
1327 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1328 ConvType = Context.getPointerType(ConvType);
1329 }
1330
1331 // Rebuild the function type "R" without any parameters (in case any
1332 // of the errors above fired) and with the conversion type as the
1333 // return type.
1334 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001335 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001336
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001337 // C++0x explicit conversion operators.
1338 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1339 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1340 diag::warn_explicit_conversion_functions)
1341 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1342
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001343 return isInvalid;
1344}
1345
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001346/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1347/// the declaration of the given C++ conversion function. This routine
1348/// is responsible for recording the conversion function in the C++
1349/// class, if possible.
1350Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1351 assert(Conversion && "Expected to receive a conversion function declaration");
1352
Douglas Gregor98341042008-12-12 08:25:50 +00001353 // Set the lexical context of this conversion function
1354 Conversion->setLexicalDeclContext(CurContext);
1355
1356 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001357
1358 // Make sure we aren't redeclaring the conversion function.
1359 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001360
1361 // C++ [class.conv.fct]p1:
1362 // [...] A conversion function is never used to convert a
1363 // (possibly cv-qualified) object to the (possibly cv-qualified)
1364 // same object type (or a reference to it), to a (possibly
1365 // cv-qualified) base class of that type (or a reference to it),
1366 // or to (possibly cv-qualified) void.
1367 // FIXME: Suppress this warning if the conversion function ends up
1368 // being a virtual function that overrides a virtual function in a
1369 // base class.
1370 QualType ClassType
1371 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1372 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1373 ConvType = ConvTypeRef->getPointeeType();
1374 if (ConvType->isRecordType()) {
1375 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1376 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001377 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001378 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001379 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001380 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001381 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001382 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001383 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001384 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001385 }
1386
Douglas Gregor853dd392008-12-26 15:00:45 +00001387 if (Conversion->getPreviousDeclaration()) {
1388 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1389 for (OverloadedFunctionDecl::function_iterator
1390 Conv = Conversions->function_begin(),
1391 ConvEnd = Conversions->function_end();
1392 Conv != ConvEnd; ++Conv) {
1393 if (*Conv == Conversion->getPreviousDeclaration()) {
1394 *Conv = Conversion;
1395 return (DeclTy *)Conversion;
1396 }
1397 }
1398 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1399 } else
1400 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001401
1402 return (DeclTy *)Conversion;
1403}
1404
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001405//===----------------------------------------------------------------------===//
1406// Namespace Handling
1407//===----------------------------------------------------------------------===//
1408
1409/// ActOnStartNamespaceDef - This is called at the start of a namespace
1410/// definition.
1411Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1412 SourceLocation IdentLoc,
1413 IdentifierInfo *II,
1414 SourceLocation LBrace) {
1415 NamespaceDecl *Namespc =
1416 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1417 Namespc->setLBracLoc(LBrace);
1418
1419 Scope *DeclRegionScope = NamespcScope->getParent();
1420
1421 if (II) {
1422 // C++ [namespace.def]p2:
1423 // The identifier in an original-namespace-definition shall not have been
1424 // previously defined in the declarative region in which the
1425 // original-namespace-definition appears. The identifier in an
1426 // original-namespace-definition is the name of the namespace. Subsequently
1427 // in that declarative region, it is treated as an original-namespace-name.
1428
Douglas Gregor09be81b2009-02-04 17:27:36 +00001429 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1430 true);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001431
1432 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1433 // This is an extended namespace definition.
1434 // Attach this namespace decl to the chain of extended namespace
1435 // definitions.
1436 OrigNS->setNextNamespace(Namespc);
1437 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001438
Douglas Gregor8acb7272008-12-11 16:49:14 +00001439 // Remove the previous declaration from the scope.
1440 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor39677622008-12-11 20:41:00 +00001441 IdResolver.RemoveDecl(OrigNS);
1442 DeclRegionScope->RemoveDecl(OrigNS);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001443 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001444 } else if (PrevDecl) {
1445 // This is an invalid name redefinition.
1446 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1447 << Namespc->getDeclName();
1448 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1449 Namespc->setInvalidDecl();
1450 // Continue on to push Namespc as current DeclContext and return it.
1451 }
1452
1453 PushOnScopeChains(Namespc, DeclRegionScope);
1454 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001455 // FIXME: Handle anonymous namespaces
1456 }
1457
1458 // Although we could have an invalid decl (i.e. the namespace name is a
1459 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001460 // FIXME: We should be able to push Namespc here, so that the
1461 // each DeclContext for the namespace has the declarations
1462 // that showed up in that particular namespace definition.
1463 PushDeclContext(NamespcScope, Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001464 return Namespc;
1465}
1466
1467/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1468/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1469void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1470 Decl *Dcl = static_cast<Decl *>(D);
1471 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1472 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1473 Namespc->setRBracLoc(RBrace);
1474 PopDeclContext();
1475}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001476
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001477Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1478 SourceLocation UsingLoc,
1479 SourceLocation NamespcLoc,
1480 const CXXScopeSpec &SS,
1481 SourceLocation IdentLoc,
1482 IdentifierInfo *NamespcName,
1483 AttributeList *AttrList) {
1484 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1485 assert(NamespcName && "Invalid NamespcName.");
1486 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001487 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001488
Douglas Gregor7a7be652009-02-03 19:21:40 +00001489 UsingDirectiveDecl *UDir = 0;
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001490
Douglas Gregor78d70132009-01-14 22:20:51 +00001491 // Lookup namespace name.
Douglas Gregor7a7be652009-02-03 19:21:40 +00001492 LookupResult R = LookupParsedName(S, &SS, NamespcName,
1493 LookupNamespaceName, false);
1494 if (R.isAmbiguous()) {
1495 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1496 return 0;
1497 }
Douglas Gregor09be81b2009-02-04 17:27:36 +00001498 if (NamedDecl *NS = R) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001499 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001500 // C++ [namespace.udir]p1:
1501 // A using-directive specifies that the names in the nominated
1502 // namespace can be used in the scope in which the
1503 // using-directive appears after the using-directive. During
1504 // unqualified name lookup (3.4.1), the names appear as if they
1505 // were declared in the nearest enclosing namespace which
1506 // contains both the using-directive and the nominated
1507 // namespace. [Note: in this context, “contains” means “contains
1508 // directly or indirectly”. ]
1509
1510 // Find enclosing context containing both using-directive and
1511 // nominated namespace.
1512 DeclContext *CommonAncestor = cast<DeclContext>(NS);
1513 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1514 CommonAncestor = CommonAncestor->getParent();
1515
1516 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1517 NamespcLoc, IdentLoc,
1518 cast<NamespaceDecl>(NS),
1519 CommonAncestor);
1520 PushUsingDirective(S, UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001521 } else {
Chris Lattner954381a2009-01-06 07:24:29 +00001522 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001523 }
1524
Douglas Gregor7a7be652009-02-03 19:21:40 +00001525 // FIXME: We ignore attributes for now.
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001526 delete AttrList;
Douglas Gregor7a7be652009-02-03 19:21:40 +00001527 return UDir;
1528}
1529
1530void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1531 // If scope has associated entity, then using directive is at namespace
1532 // or translation unit scope. We add UsingDirectiveDecls, into
1533 // it's lookup structure.
1534 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1535 Ctx->addDecl(UDir);
1536 else
1537 // Otherwise it is block-sope. using-directives will affect lookup
1538 // only to the end of scope.
1539 S->PushUsingDirective(UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001540}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001541
1542/// AddCXXDirectInitializerToDecl - This action is called immediately after
1543/// ActOnDeclarator, when a C++ direct initializer is present.
1544/// e.g: "int x(1);"
1545void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1546 ExprTy **ExprTys, unsigned NumExprs,
1547 SourceLocation *CommaLocs,
1548 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001549 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001550 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001551
1552 // If there is no declaration, there was an error parsing it. Just ignore
1553 // the initializer.
1554 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +00001555 for (unsigned i = 0; i != NumExprs; ++i)
Ted Kremenek0c97e042009-02-07 01:47:29 +00001556 static_cast<Expr *>(ExprTys[i])->Destroy(Context);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001557 return;
1558 }
1559
1560 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1561 if (!VDecl) {
1562 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1563 RealDecl->setInvalidDecl();
1564 return;
1565 }
1566
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001567 // We will treat direct-initialization as a copy-initialization:
1568 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001569 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1570 //
1571 // Clients that want to distinguish between the two forms, can check for
1572 // direct initializer using VarDecl::hasCXXDirectInitializer().
1573 // A major benefit is that clients that don't particularly care about which
1574 // exactly form was it (like the CodeGen) can handle both cases without
1575 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001576
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001577 // C++ 8.5p11:
1578 // The form of initialization (using parentheses or '=') is generally
1579 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001580 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001581 QualType DeclInitType = VDecl->getType();
1582 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1583 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001584
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001585 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001586 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +00001587 = PerformInitializationByConstructor(DeclInitType,
1588 (Expr **)ExprTys, NumExprs,
1589 VDecl->getLocation(),
1590 SourceRange(VDecl->getLocation(),
1591 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00001592 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00001593 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +00001594 if (!Constructor) {
1595 RealDecl->setInvalidDecl();
1596 }
Douglas Gregor6428e762008-11-05 15:29:30 +00001597
1598 // Let clients know that initialization was done with a direct
1599 // initializer.
1600 VDecl->setCXXDirectInitializer(true);
1601
1602 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1603 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001604 return;
1605 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001606
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001607 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001608 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1609 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001610 RealDecl->setInvalidDecl();
1611 return;
1612 }
1613
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001614 // Let clients know that initialization was done with a direct initializer.
1615 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001616
1617 assert(NumExprs == 1 && "Expected 1 expression");
1618 // Set the init expression, handles conversions.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001619 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001620}
Douglas Gregor81c29152008-10-29 00:13:59 +00001621
Douglas Gregor6428e762008-11-05 15:29:30 +00001622/// PerformInitializationByConstructor - Perform initialization by
1623/// constructor (C++ [dcl.init]p14), which may occur as part of
1624/// direct-initialization or copy-initialization. We are initializing
1625/// an object of type @p ClassType with the given arguments @p
1626/// Args. @p Loc is the location in the source code where the
1627/// initializer occurs (e.g., a declaration, member initializer,
1628/// functional cast, etc.) while @p Range covers the whole
1629/// initialization. @p InitEntity is the entity being initialized,
1630/// which may by the name of a declaration or a type. @p Kind is the
1631/// kind of initialization we're performing, which affects whether
1632/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001633/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001634/// when the initialization fails, emits a diagnostic and returns
1635/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001636CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001637Sema::PerformInitializationByConstructor(QualType ClassType,
1638 Expr **Args, unsigned NumArgs,
1639 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00001640 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00001641 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001642 const RecordType *ClassRec = ClassType->getAsRecordType();
1643 assert(ClassRec && "Can only initialize a class type here");
1644
1645 // C++ [dcl.init]p14:
1646 //
1647 // If the initialization is direct-initialization, or if it is
1648 // copy-initialization where the cv-unqualified version of the
1649 // source type is the same class as, or a derived class of, the
1650 // class of the destination, constructors are considered. The
1651 // applicable constructors are enumerated (13.3.1.3), and the
1652 // best one is chosen through overload resolution (13.3). The
1653 // constructor so selected is called to initialize the object,
1654 // with the initializer expression(s) as its argument(s). If no
1655 // constructor applies, or the overload resolution is ambiguous,
1656 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001657 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1658 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001659
1660 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00001661 DeclarationName ConstructorName
1662 = Context.DeclarationNames.getCXXConstructorName(
1663 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001664 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00001665 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001666 Con != ConEnd; ++Con) {
1667 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor6428e762008-11-05 15:29:30 +00001668 if ((Kind == IK_Direct) ||
1669 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1670 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1671 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1672 }
1673
Douglas Gregorb9213832008-12-15 21:24:18 +00001674 // FIXME: When we decide not to synthesize the implicitly-declared
1675 // constructors, we'll need to make them appear here.
1676
Douglas Gregor5870a952008-11-03 20:45:27 +00001677 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001678 switch (BestViableFunction(CandidateSet, Best)) {
1679 case OR_Success:
1680 // We found a constructor. Return it.
1681 return cast<CXXConstructorDecl>(Best->Function);
1682
1683 case OR_No_Viable_Function:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001684 if (InitEntity)
1685 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001686 << InitEntity << Range;
Douglas Gregor538a4c22009-02-02 17:43:21 +00001687 else
1688 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001689 << ClassType << Range;
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00001690 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00001691 return 0;
1692
1693 case OR_Ambiguous:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001694 if (InitEntity)
1695 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1696 else
1697 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00001698 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1699 return 0;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001700
1701 case OR_Deleted:
1702 if (InitEntity)
1703 Diag(Loc, diag::err_ovl_deleted_init)
1704 << Best->Function->isDeleted()
1705 << InitEntity << Range;
1706 else
1707 Diag(Loc, diag::err_ovl_deleted_init)
1708 << Best->Function->isDeleted()
1709 << InitEntity << Range;
1710 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1711 return 0;
Douglas Gregor5870a952008-11-03 20:45:27 +00001712 }
1713
1714 return 0;
1715}
1716
Douglas Gregor81c29152008-10-29 00:13:59 +00001717/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1718/// determine whether they are reference-related,
1719/// reference-compatible, reference-compatible with added
1720/// qualification, or incompatible, for use in C++ initialization by
1721/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1722/// type, and the first type (T1) is the pointee type of the reference
1723/// type being initialized.
1724Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001725Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1726 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001727 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1728 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1729
1730 T1 = Context.getCanonicalType(T1);
1731 T2 = Context.getCanonicalType(T2);
1732 QualType UnqualT1 = T1.getUnqualifiedType();
1733 QualType UnqualT2 = T2.getUnqualifiedType();
1734
1735 // C++ [dcl.init.ref]p4:
1736 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1737 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1738 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001739 if (UnqualT1 == UnqualT2)
1740 DerivedToBase = false;
1741 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1742 DerivedToBase = true;
1743 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001744 return Ref_Incompatible;
1745
1746 // At this point, we know that T1 and T2 are reference-related (at
1747 // least).
1748
1749 // C++ [dcl.init.ref]p4:
1750 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1751 // reference-related to T2 and cv1 is the same cv-qualification
1752 // as, or greater cv-qualification than, cv2. For purposes of
1753 // overload resolution, cases for which cv1 is greater
1754 // cv-qualification than cv2 are identified as
1755 // reference-compatible with added qualification (see 13.3.3.2).
1756 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1757 return Ref_Compatible;
1758 else if (T1.isMoreQualifiedThan(T2))
1759 return Ref_Compatible_With_Added_Qualification;
1760 else
1761 return Ref_Related;
1762}
1763
1764/// CheckReferenceInit - Check the initialization of a reference
1765/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1766/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001767/// list), and DeclType is the type of the declaration. When ICS is
1768/// non-null, this routine will compute the implicit conversion
1769/// sequence according to C++ [over.ics.ref] and will not produce any
1770/// diagnostics; when ICS is null, it will emit diagnostics when any
1771/// errors are found. Either way, a return value of true indicates
1772/// that there was a failure, a return value of false indicates that
1773/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001774///
1775/// When @p SuppressUserConversions, user-defined conversions are
1776/// suppressed.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001777/// When @p AllowExplicit, we also permit explicit user-defined
1778/// conversion functions.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001779bool
1780Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001781 ImplicitConversionSequence *ICS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001782 bool SuppressUserConversions,
1783 bool AllowExplicit) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001784 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1785
1786 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1787 QualType T2 = Init->getType();
1788
Douglas Gregor45014fd2008-11-10 20:40:00 +00001789 // If the initializer is the address of an overloaded function, try
1790 // to resolve the overloaded function. If all goes well, T2 is the
1791 // type of the resulting function.
1792 if (T2->isOverloadType()) {
1793 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1794 ICS != 0);
1795 if (Fn) {
1796 // Since we're performing this reference-initialization for
1797 // real, update the initializer with the resulting function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00001798 if (!ICS) {
1799 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
1800 return true;
1801
Douglas Gregor45014fd2008-11-10 20:40:00 +00001802 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregoraa57e862009-02-18 21:56:37 +00001803 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00001804
1805 T2 = Fn->getType();
1806 }
1807 }
1808
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001809 // Compute some basic properties of the types and the initializer.
1810 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001811 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001812 ReferenceCompareResult RefRelationship
1813 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1814
1815 // Most paths end in a failed conversion.
1816 if (ICS)
1817 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001818
1819 // C++ [dcl.init.ref]p5:
1820 // A reference to type “cv1 T1” is initialized by an expression
1821 // of type “cv2 T2” as follows:
1822
1823 // -- If the initializer expression
1824
1825 bool BindsDirectly = false;
1826 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1827 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001828 //
1829 // Note that the bit-field check is skipped if we are just computing
1830 // the implicit conversion sequence (C++ [over.best.ics]p2).
1831 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1832 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001833 BindsDirectly = true;
1834
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001835 if (ICS) {
1836 // C++ [over.ics.ref]p1:
1837 // When a parameter of reference type binds directly (8.5.3)
1838 // to an argument expression, the implicit conversion sequence
1839 // is the identity conversion, unless the argument expression
1840 // has a type that is a derived class of the parameter type,
1841 // in which case the implicit conversion sequence is a
1842 // derived-to-base Conversion (13.3.3.1).
1843 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1844 ICS->Standard.First = ICK_Identity;
1845 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1846 ICS->Standard.Third = ICK_Identity;
1847 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1848 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001849 ICS->Standard.ReferenceBinding = true;
1850 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001851
1852 // Nothing more to do: the inaccessibility/ambiguity check for
1853 // derived-to-base conversions is suppressed when we're
1854 // computing the implicit conversion sequence (C++
1855 // [over.best.ics]p2).
1856 return false;
1857 } else {
1858 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001859 // FIXME: Binding to a subobject of the lvalue is going to require
1860 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001861 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001862 }
1863 }
1864
1865 // -- has a class type (i.e., T2 is a class type) and can be
1866 // implicitly converted to an lvalue of type “cv3 T3,”
1867 // where “cv1 T1” is reference-compatible with “cv3 T3”
1868 // 92) (this conversion is selected by enumerating the
1869 // applicable conversion functions (13.3.1.6) and choosing
1870 // the best one through overload resolution (13.3)),
Douglas Gregore6985fe2008-11-10 16:14:15 +00001871 if (!SuppressUserConversions && T2->isRecordType()) {
1872 // FIXME: Look for conversions in base classes!
1873 CXXRecordDecl *T2RecordDecl
1874 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00001875
Douglas Gregore6985fe2008-11-10 16:14:15 +00001876 OverloadCandidateSet CandidateSet;
1877 OverloadedFunctionDecl *Conversions
1878 = T2RecordDecl->getConversionFunctions();
1879 for (OverloadedFunctionDecl::function_iterator Func
1880 = Conversions->function_begin();
1881 Func != Conversions->function_end(); ++Func) {
1882 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1883
1884 // If the conversion function doesn't return a reference type,
1885 // it can't be considered for this conversion.
1886 // FIXME: This will change when we support rvalue references.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001887 if (Conv->getConversionType()->isReferenceType() &&
1888 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregore6985fe2008-11-10 16:14:15 +00001889 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1890 }
1891
1892 OverloadCandidateSet::iterator Best;
1893 switch (BestViableFunction(CandidateSet, Best)) {
1894 case OR_Success:
1895 // This is a direct binding.
1896 BindsDirectly = true;
1897
1898 if (ICS) {
1899 // C++ [over.ics.ref]p1:
1900 //
1901 // [...] If the parameter binds directly to the result of
1902 // applying a conversion function to the argument
1903 // expression, the implicit conversion sequence is a
1904 // user-defined conversion sequence (13.3.3.1.2), with the
1905 // second standard conversion sequence either an identity
1906 // conversion or, if the conversion function returns an
1907 // entity of a type that is a derived class of the parameter
1908 // type, a derived-to-base Conversion.
1909 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1910 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1911 ICS->UserDefined.After = Best->FinalConversion;
1912 ICS->UserDefined.ConversionFunction = Best->Function;
1913 assert(ICS->UserDefined.After.ReferenceBinding &&
1914 ICS->UserDefined.After.DirectBinding &&
1915 "Expected a direct reference binding!");
1916 return false;
1917 } else {
1918 // Perform the conversion.
1919 // FIXME: Binding to a subobject of the lvalue is going to require
1920 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001921 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00001922 }
1923 break;
1924
1925 case OR_Ambiguous:
1926 assert(false && "Ambiguous reference binding conversions not implemented.");
1927 return true;
1928
1929 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001930 case OR_Deleted:
1931 // There was no suitable conversion, or we found a deleted
1932 // conversion; continue with other checks.
Douglas Gregore6985fe2008-11-10 16:14:15 +00001933 break;
1934 }
1935 }
1936
Douglas Gregor81c29152008-10-29 00:13:59 +00001937 if (BindsDirectly) {
1938 // C++ [dcl.init.ref]p4:
1939 // [...] In all cases where the reference-related or
1940 // reference-compatible relationship of two types is used to
1941 // establish the validity of a reference binding, and T1 is a
1942 // base class of T2, a program that necessitates such a binding
1943 // is ill-formed if T1 is an inaccessible (clause 11) or
1944 // ambiguous (10.2) base class of T2.
1945 //
1946 // Note that we only check this condition when we're allowed to
1947 // complain about errors, because we should not be checking for
1948 // ambiguity (or inaccessibility) unless the reference binding
1949 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001950 if (DerivedToBase)
1951 return CheckDerivedToBaseConversion(T2, T1,
1952 Init->getSourceRange().getBegin(),
1953 Init->getSourceRange());
1954 else
1955 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001956 }
1957
1958 // -- Otherwise, the reference shall be to a non-volatile const
1959 // type (i.e., cv1 shall be const).
1960 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001961 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001962 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001963 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001964 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1965 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001966 return true;
1967 }
1968
1969 // -- If the initializer expression is an rvalue, with T2 a
1970 // class type, and “cv1 T1” is reference-compatible with
1971 // “cv2 T2,” the reference is bound in one of the
1972 // following ways (the choice is implementation-defined):
1973 //
1974 // -- The reference is bound to the object represented by
1975 // the rvalue (see 3.10) or to a sub-object within that
1976 // object.
1977 //
1978 // -- A temporary of type “cv1 T2” [sic] is created, and
1979 // a constructor is called to copy the entire rvalue
1980 // object into the temporary. The reference is bound to
1981 // the temporary or to a sub-object within the
1982 // temporary.
1983 //
Douglas Gregor81c29152008-10-29 00:13:59 +00001984 // The constructor that would be used to make the copy
1985 // shall be callable whether or not the copy is actually
1986 // done.
1987 //
1988 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1989 // freedom, so we will always take the first option and never build
1990 // a temporary in this case. FIXME: We will, however, have to check
1991 // for the presence of a copy constructor in C++98/03 mode.
1992 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001993 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1994 if (ICS) {
1995 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1996 ICS->Standard.First = ICK_Identity;
1997 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1998 ICS->Standard.Third = ICK_Identity;
1999 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
2000 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00002001 ICS->Standard.ReferenceBinding = true;
2002 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002003 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00002004 // FIXME: Binding to a subobject of the rvalue is going to require
2005 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00002006 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00002007 }
2008 return false;
2009 }
2010
2011 // -- Otherwise, a temporary of type “cv1 T1” is created and
2012 // initialized from the initializer expression using the
2013 // rules for a non-reference copy initialization (8.5). The
2014 // reference is then bound to the temporary. If T1 is
2015 // reference-related to T2, cv1 must be the same
2016 // cv-qualification as, or greater cv-qualification than,
2017 // cv2; otherwise, the program is ill-formed.
2018 if (RefRelationship == Ref_Related) {
2019 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2020 // we would be reference-compatible or reference-compatible with
2021 // added qualification. But that wasn't the case, so the reference
2022 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002023 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00002024 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00002025 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002026 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2027 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00002028 return true;
2029 }
2030
Douglas Gregorb206cc42009-01-30 23:27:23 +00002031 // If at least one of the types is a class type, the types are not
2032 // related, and we aren't allowed any user conversions, the
2033 // reference binding fails. This case is important for breaking
2034 // recursion, since TryImplicitConversion below will attempt to
2035 // create a temporary through the use of a copy constructor.
2036 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2037 (T1->isRecordType() || T2->isRecordType())) {
2038 if (!ICS)
2039 Diag(Init->getSourceRange().getBegin(),
2040 diag::err_typecheck_convert_incompatible)
2041 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2042 return true;
2043 }
2044
Douglas Gregor81c29152008-10-29 00:13:59 +00002045 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002046 if (ICS) {
2047 /// C++ [over.ics.ref]p2:
2048 ///
2049 /// When a parameter of reference type is not bound directly to
2050 /// an argument expression, the conversion sequence is the one
2051 /// required to convert the argument expression to the
2052 /// underlying type of the reference according to
2053 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
2054 /// to copy-initializing a temporary of the underlying type with
2055 /// the argument expression. Any difference in top-level
2056 /// cv-qualification is subsumed by the initialization itself
2057 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002058 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002059 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2060 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00002061 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002062 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002063}
Douglas Gregore60e5d32008-11-06 22:13:31 +00002064
2065/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2066/// of this overloaded operator is well-formed. If so, returns false;
2067/// otherwise, emits appropriate diagnostics and returns true.
2068bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002069 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00002070 "Expected an overloaded operator declaration");
2071
Douglas Gregore60e5d32008-11-06 22:13:31 +00002072 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2073
2074 // C++ [over.oper]p5:
2075 // The allocation and deallocation functions, operator new,
2076 // operator new[], operator delete and operator delete[], are
2077 // described completely in 3.7.3. The attributes and restrictions
2078 // found in the rest of this subclause do not apply to them unless
2079 // explicitly stated in 3.7.3.
2080 // FIXME: Write a separate routine for checking this. For now, just
2081 // allow it.
2082 if (Op == OO_New || Op == OO_Array_New ||
2083 Op == OO_Delete || Op == OO_Array_Delete)
2084 return false;
2085
2086 // C++ [over.oper]p6:
2087 // An operator function shall either be a non-static member
2088 // function or be a non-member function and have at least one
2089 // parameter whose type is a class, a reference to a class, an
2090 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002091 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2092 if (MethodDecl->isStatic())
2093 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002094 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002095 } else {
2096 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002097 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2098 ParamEnd = FnDecl->param_end();
2099 Param != ParamEnd; ++Param) {
2100 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002101 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2102 ClassOrEnumParam = true;
2103 break;
2104 }
2105 }
2106
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002107 if (!ClassOrEnumParam)
2108 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002109 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00002110 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002111 }
2112
2113 // C++ [over.oper]p8:
2114 // An operator function cannot have default arguments (8.3.6),
2115 // except where explicitly stated below.
2116 //
2117 // Only the function-call operator allows default arguments
2118 // (C++ [over.call]p1).
2119 if (Op != OO_Call) {
2120 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2121 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002122 if ((*Param)->hasUnparsedDefaultArg())
2123 return Diag((*Param)->getLocation(),
2124 diag::err_operator_overload_default_arg)
2125 << FnDecl->getDeclName();
2126 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002127 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00002128 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00002129 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002130 }
2131 }
2132
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002133 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2134 { false, false, false }
2135#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2136 , { Unary, Binary, MemberOnly }
2137#include "clang/Basic/OperatorKinds.def"
2138 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00002139
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002140 bool CanBeUnaryOperator = OperatorUses[Op][0];
2141 bool CanBeBinaryOperator = OperatorUses[Op][1];
2142 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00002143
2144 // C++ [over.oper]p8:
2145 // [...] Operator functions cannot have more or fewer parameters
2146 // than the number required for the corresponding operator, as
2147 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002148 unsigned NumParams = FnDecl->getNumParams()
2149 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002150 if (Op != OO_Call &&
2151 ((NumParams == 1 && !CanBeUnaryOperator) ||
2152 (NumParams == 2 && !CanBeBinaryOperator) ||
2153 (NumParams < 1) || (NumParams > 2))) {
2154 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00002155 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002156 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002157 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002158 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002159 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002160 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00002161 assert(CanBeBinaryOperator &&
2162 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00002163 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002164 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00002165
Chris Lattnerbb002332008-11-21 07:57:12 +00002166 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00002167 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002168 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002169
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002170 // Overloaded operators other than operator() cannot be variadic.
2171 if (Op != OO_Call &&
Douglas Gregor4fa58902009-02-26 23:50:07 +00002172 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002173 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00002174 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002175 }
2176
2177 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002178 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2179 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002180 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00002181 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002182 }
2183
2184 // C++ [over.inc]p1:
2185 // The user-defined function called operator++ implements the
2186 // prefix and postfix ++ operator. If this function is a member
2187 // function with no parameters, or a non-member function with one
2188 // parameter of class or enumeration type, it defines the prefix
2189 // increment operator ++ for objects of that type. If the function
2190 // is a member function with one parameter (which shall be of type
2191 // int) or a non-member function with two parameters (the second
2192 // of which shall be of type int), it defines the postfix
2193 // increment operator ++ for objects of that type.
2194 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2195 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2196 bool ParamIsInt = false;
2197 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2198 ParamIsInt = BT->getKind() == BuiltinType::Int;
2199
Chris Lattnera7021ee2008-11-21 07:50:02 +00002200 if (!ParamIsInt)
2201 return Diag(LastParam->getLocation(),
2202 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002203 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002204 }
2205
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002206 // Notify the class if it got an assignment operator.
2207 if (Op == OO_Equal) {
2208 // Would have returned earlier otherwise.
2209 assert(isa<CXXMethodDecl>(FnDecl) &&
2210 "Overloaded = not member, but not filtered.");
2211 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2212 Method->getParent()->addedAssignmentOperator(Context, Method);
2213 }
2214
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002215 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002216}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002217
Douglas Gregord8028382009-01-05 19:45:36 +00002218/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2219/// linkage specification, including the language and (if present)
2220/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2221/// the location of the language string literal, which is provided
2222/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2223/// the '{' brace. Otherwise, this linkage specification does not
2224/// have any braces.
2225Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2226 SourceLocation ExternLoc,
2227 SourceLocation LangLoc,
2228 const char *Lang,
2229 unsigned StrSize,
2230 SourceLocation LBraceLoc) {
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002231 LinkageSpecDecl::LanguageIDs Language;
2232 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2233 Language = LinkageSpecDecl::lang_c;
2234 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2235 Language = LinkageSpecDecl::lang_cxx;
2236 else {
Douglas Gregord8028382009-01-05 19:45:36 +00002237 Diag(LangLoc, diag::err_bad_language);
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002238 return 0;
2239 }
2240
2241 // FIXME: Add all the various semantics of linkage specifications
2242
Douglas Gregord8028382009-01-05 19:45:36 +00002243 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2244 LangLoc, Language,
2245 LBraceLoc.isValid());
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002246 CurContext->addDecl(D);
Douglas Gregord8028382009-01-05 19:45:36 +00002247 PushDeclContext(S, D);
2248 return D;
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002249}
2250
Douglas Gregord8028382009-01-05 19:45:36 +00002251/// ActOnFinishLinkageSpecification - Completely the definition of
2252/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2253/// valid, it's the position of the closing '}' brace in a linkage
2254/// specification that uses braces.
2255Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2256 DeclTy *LinkageSpec,
2257 SourceLocation RBraceLoc) {
2258 if (LinkageSpec)
2259 PopDeclContext();
2260 return LinkageSpec;
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002261}
2262
Sebastian Redl743c8162008-12-22 19:15:10 +00002263/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2264/// handler.
2265Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2266{
2267 QualType ExDeclType = GetTypeForDeclarator(D, S);
2268 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2269
2270 bool Invalid = false;
2271
2272 // Arrays and functions decay.
2273 if (ExDeclType->isArrayType())
2274 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2275 else if (ExDeclType->isFunctionType())
2276 ExDeclType = Context.getPointerType(ExDeclType);
2277
2278 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2279 // The exception-declaration shall not denote a pointer or reference to an
2280 // incomplete type, other than [cv] void*.
2281 QualType BaseType = ExDeclType;
2282 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002283 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl743c8162008-12-22 19:15:10 +00002284 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2285 BaseType = Ptr->getPointeeType();
2286 Mode = 1;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002287 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl743c8162008-12-22 19:15:10 +00002288 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2289 BaseType = Ref->getPointeeType();
2290 Mode = 2;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002291 DK = diag::err_catch_incomplete_ref;
Sebastian Redl743c8162008-12-22 19:15:10 +00002292 }
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002293 if ((Mode == 0 || !BaseType->isVoidType()) &&
2294 DiagnoseIncompleteType(Begin, BaseType, DK))
Sebastian Redl743c8162008-12-22 19:15:10 +00002295 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00002296
Sebastian Redl237116b2008-12-22 21:35:02 +00002297 // FIXME: Need to test for ability to copy-construct and destroy the
2298 // exception variable.
2299 // FIXME: Need to check for abstract classes.
2300
Sebastian Redl743c8162008-12-22 19:15:10 +00002301 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor09be81b2009-02-04 17:27:36 +00002302 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl743c8162008-12-22 19:15:10 +00002303 // The scope should be freshly made just for us. There is just no way
2304 // it contains any previous declaration.
2305 assert(!S->isDeclScope(PrevDecl));
2306 if (PrevDecl->isTemplateParameter()) {
2307 // Maybe we will complain about the shadowed template parameter.
2308 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2309
2310 }
2311 }
2312
2313 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002314 II, ExDeclType, VarDecl::None, Begin);
Sebastian Redl743c8162008-12-22 19:15:10 +00002315 if (D.getInvalidType() || Invalid)
2316 ExDecl->setInvalidDecl();
2317
2318 if (D.getCXXScopeSpec().isSet()) {
2319 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2320 << D.getCXXScopeSpec().getRange();
2321 ExDecl->setInvalidDecl();
2322 }
2323
2324 // Add the exception declaration into this scope.
2325 S->AddDecl(ExDecl);
2326 if (II)
2327 IdResolver.AddDecl(ExDecl);
2328
2329 ProcessDeclAttributes(ExDecl, D);
2330 return ExDecl;
2331}