blob: b708598c620ffb6c1cccce4494cac8f96802e724 [file] [log] [blame]
Chris Lattnerac7b83a2008-04-08 05:04:30 +00001//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Douglas Gregora65e8dd2008-11-05 04:29:56 +000015#include "SemaInherit.h"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor05904022008-10-22 21:13:31 +000018#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000019#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000020#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Parse/DeclSpec.h"
Douglas Gregorddfd9d52008-12-23 00:26:44 +000022#include "llvm/ADT/STLExtras.h"
Chris Lattner97316c02008-04-10 02:22:51 +000023#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000024#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000025#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000026
27using namespace clang;
28
Chris Lattner97316c02008-04-10 02:22:51 +000029//===----------------------------------------------------------------------===//
30// CheckDefaultArgumentVisitor
31//===----------------------------------------------------------------------===//
32
Chris Lattnerb1856db2008-04-12 23:52:44 +000033namespace {
34 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
35 /// the default argument of a parameter to determine whether it
36 /// contains any ill-formed subexpressions. For example, this will
37 /// diagnose the use of local variables or parameters within the
38 /// default argument expression.
39 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000040 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000041 Expr *DefaultArg;
42 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000043
Chris Lattnerb1856db2008-04-12 23:52:44 +000044 public:
45 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
46 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000047
Chris Lattnerb1856db2008-04-12 23:52:44 +000048 bool VisitExpr(Expr *Node);
49 bool VisitDeclRefExpr(DeclRefExpr *DRE);
Douglas Gregora5b022a2008-11-04 14:32:21 +000050 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
Chris Lattnerb1856db2008-04-12 23:52:44 +000051 };
Chris Lattner97316c02008-04-10 02:22:51 +000052
Chris Lattnerb1856db2008-04-12 23:52:44 +000053 /// VisitExpr - Visit all of the children of this expression.
54 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
55 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000056 for (Stmt::child_iterator I = Node->child_begin(),
57 E = Node->child_end(); I != E; ++I)
58 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000059 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000060 }
61
Chris Lattnerb1856db2008-04-12 23:52:44 +000062 /// VisitDeclRefExpr - Visit a reference to a declaration, to
63 /// determine whether this declaration can be used in the default
64 /// argument expression.
65 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000066 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000067 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
68 // C++ [dcl.fct.default]p9
69 // Default arguments are evaluated each time the function is
70 // called. The order of evaluation of function arguments is
71 // unspecified. Consequently, parameters of a function shall not
72 // be used in default argument expressions, even if they are not
73 // evaluated. Parameters of a function declared before a default
74 // argument expression are in scope and can hide namespace and
75 // class member names.
76 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000077 diag::err_param_default_argument_references_param)
Chris Lattnerb1753422008-11-23 21:45:46 +000078 << Param->getDeclName() << DefaultArg->getSourceRange();
Steve Naroff72a6ebc2008-04-15 22:42:06 +000079 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000080 // C++ [dcl.fct.default]p7
81 // Local variables shall not be used in default argument
82 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000083 if (VDecl->isBlockVarDecl())
84 return S->Diag(DRE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000085 diag::err_param_default_argument_references_local)
Chris Lattnerb1753422008-11-23 21:45:46 +000086 << VDecl->getDeclName() << DefaultArg->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +000087 }
Chris Lattner97316c02008-04-10 02:22:51 +000088
Douglas Gregor3c246952008-11-04 13:41:56 +000089 return false;
90 }
Chris Lattnerb1856db2008-04-12 23:52:44 +000091
Douglas Gregora5b022a2008-11-04 14:32:21 +000092 /// VisitCXXThisExpr - Visit a C++ "this" expression.
93 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
94 // C++ [dcl.fct.default]p8:
95 // The keyword this shall not be used in a default argument of a
96 // member function.
97 return S->Diag(ThisE->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +000098 diag::err_param_default_argument_references_this)
99 << ThisE->getSourceRange();
Chris Lattnerb1856db2008-04-12 23:52:44 +0000100 }
Chris Lattner97316c02008-04-10 02:22:51 +0000101}
102
103/// ActOnParamDefaultArgument - Check whether the default argument
104/// provided for a function parameter is well-formed. If so, attach it
105/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000106void
107Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
108 ExprTy *defarg) {
109 ParmVarDecl *Param = (ParmVarDecl *)param;
Ted Kremenek0c97e042009-02-07 01:47:29 +0000110 ExprOwningPtr<Expr> DefaultArg(this, (Expr *)defarg);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000111 QualType ParamType = Param->getType();
112
113 // Default arguments are only permitted in C++
114 if (!getLangOptions().CPlusPlus) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000115 Diag(EqualLoc, diag::err_param_default_argument)
116 << DefaultArg->getSourceRange();
Douglas Gregor605de8d2008-12-16 21:30:33 +0000117 Param->setInvalidDecl();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000118 return;
119 }
120
121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000127 Expr *DefaultArgPtr = DefaultArg.get();
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000128 bool DefaultInitFailed = CheckInitializerTypes(DefaultArgPtr, ParamType,
129 EqualLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +0000130 Param->getDeclName(),
131 /*DirectInit=*/false);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000132 if (DefaultArgPtr != DefaultArg.get()) {
133 DefaultArg.take();
134 DefaultArg.reset(DefaultArgPtr);
135 }
Douglas Gregor58c428c2008-11-04 13:57:51 +0000136 if (DefaultInitFailed) {
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000137 return;
138 }
139
Chris Lattner97316c02008-04-10 02:22:51 +0000140 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000141 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Douglas Gregor605de8d2008-12-16 21:30:33 +0000142 if (DefaultArgChecker.Visit(DefaultArg.get())) {
143 Param->setInvalidDecl();
Chris Lattner97316c02008-04-10 02:22:51 +0000144 return;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000145 }
Chris Lattner97316c02008-04-10 02:22:51 +0000146
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000147 // Okay: add the default argument to the parameter
148 Param->setDefaultArg(DefaultArg.take());
149}
150
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000151/// ActOnParamUnparsedDefaultArgument - We've seen a default
152/// argument for a function parameter, but we can't parse it yet
153/// because we're inside a class definition. Note that this default
154/// argument will be parsed later.
155void Sema::ActOnParamUnparsedDefaultArgument(DeclTy *param,
156 SourceLocation EqualLoc) {
157 ParmVarDecl *Param = (ParmVarDecl*)param;
158 if (Param)
159 Param->setUnparsedDefaultArg();
160}
161
Douglas Gregor605de8d2008-12-16 21:30:33 +0000162/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
163/// the default argument for the parameter param failed.
164void Sema::ActOnParamDefaultArgumentError(DeclTy *param) {
165 ((ParmVarDecl*)param)->setInvalidDecl();
166}
167
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000168/// CheckExtraCXXDefaultArguments - Check for any extra default
169/// arguments in the declarator, which is not a function declaration
170/// or definition and therefore is not permitted to have default
171/// arguments. This routine should be invoked for every declarator
172/// that is not a function declaration or definition.
173void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
174 // C++ [dcl.fct.default]p3
175 // A default argument expression shall be specified only in the
176 // parameter-declaration-clause of a function declaration or in a
177 // template-parameter (14.1). It shall not be specified for a
178 // parameter pack. If it is specified in a
179 // parameter-declaration-clause, it shall not occur within a
180 // declarator or abstract-declarator of a parameter-declaration.
181 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
182 DeclaratorChunk &chunk = D.getTypeObject(i);
183 if (chunk.Kind == DeclaratorChunk::Function) {
184 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
185 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000186 if (Param->hasUnparsedDefaultArg()) {
187 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
Douglas Gregor605de8d2008-12-16 21:30:33 +0000188 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
189 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
190 delete Toks;
191 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000192 } else if (Param->getDefaultArg()) {
193 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
194 << Param->getDefaultArg()->getSourceRange();
195 Param->setDefaultArg(0);
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000196 }
197 }
198 }
199 }
200}
201
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000202// MergeCXXFunctionDecl - Merge two declarations of the same C++
203// function, once we already know that they have the same
Douglas Gregor083c23e2009-02-16 17:45:42 +0000204// type. Subroutine of MergeFunctionDecl. Returns true if there was an
205// error, false otherwise.
206bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
207 bool Invalid = false;
208
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000209 // C++ [dcl.fct.default]p4:
210 //
211 // For non-template functions, default arguments can be added in
212 // later declarations of a function in the same
213 // scope. Declarations in different scopes have completely
214 // distinct sets of default arguments. That is, declarations in
215 // inner scopes do not acquire default arguments from
216 // declarations in outer scopes, and vice versa. In a given
217 // function declaration, all parameters subsequent to a
218 // parameter with a default argument shall have default
219 // arguments supplied in this or previous declarations. A
220 // default argument shall not be redefined by a later
221 // declaration (not even to the same value).
222 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
223 ParmVarDecl *OldParam = Old->getParamDecl(p);
224 ParmVarDecl *NewParam = New->getParamDecl(p);
225
226 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
227 Diag(NewParam->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000228 diag::err_param_default_argument_redefinition)
229 << NewParam->getDefaultArg()->getSourceRange();
Chris Lattner1336cab2008-11-23 23:12:31 +0000230 Diag(OldParam->getLocation(), diag::note_previous_definition);
Douglas Gregor083c23e2009-02-16 17:45:42 +0000231 Invalid = true;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000232 } else if (OldParam->getDefaultArg()) {
233 // Merge the old default argument into the new parameter
234 NewParam->setDefaultArg(OldParam->getDefaultArg());
235 }
236 }
237
Douglas Gregor083c23e2009-02-16 17:45:42 +0000238 return Invalid;
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000239}
240
241/// CheckCXXDefaultArguments - Verify that the default arguments for a
242/// function declaration are well-formed according to C++
243/// [dcl.fct.default].
244void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
245 unsigned NumParams = FD->getNumParams();
246 unsigned p;
247
248 // Find first parameter with a default argument
249 for (p = 0; p < NumParams; ++p) {
250 ParmVarDecl *Param = FD->getParamDecl(p);
251 if (Param->getDefaultArg())
252 break;
253 }
254
255 // C++ [dcl.fct.default]p4:
256 // In a given function declaration, all parameters
257 // subsequent to a parameter with a default argument shall
258 // have default arguments supplied in this or previous
259 // declarations. A default argument shall not be redefined
260 // by a later declaration (not even to the same value).
261 unsigned LastMissingDefaultArg = 0;
262 for(; p < NumParams; ++p) {
263 ParmVarDecl *Param = FD->getParamDecl(p);
264 if (!Param->getDefaultArg()) {
Douglas Gregor605de8d2008-12-16 21:30:33 +0000265 if (Param->isInvalidDecl())
266 /* We already complained about this parameter. */;
267 else if (Param->getIdentifier())
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000268 Diag(Param->getLocation(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000269 diag::err_param_default_argument_missing_name)
Chris Lattnere46b8792008-11-19 07:32:16 +0000270 << Param->getIdentifier();
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000271 else
272 Diag(Param->getLocation(),
273 diag::err_param_default_argument_missing);
274
275 LastMissingDefaultArg = p;
276 }
277 }
278
279 if (LastMissingDefaultArg > 0) {
280 // Some default arguments were missing. Clear out all of the
281 // default arguments up to (and including) the last missing
282 // default argument, so that we leave the function parameters
283 // in a semantically valid state.
284 for (p = 0; p <= LastMissingDefaultArg; ++p) {
285 ParmVarDecl *Param = FD->getParamDecl(p);
286 if (Param->getDefaultArg()) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +0000287 if (!Param->hasUnparsedDefaultArg())
288 Param->getDefaultArg()->Destroy(Context);
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000289 Param->setDefaultArg(0);
290 }
291 }
292 }
293}
Douglas Gregorec93f442008-04-13 21:30:24 +0000294
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000295/// isCurrentClassName - Determine whether the identifier II is the
296/// name of the class type currently being defined. In the case of
297/// nested classes, this will only return true if II is the name of
298/// the innermost class.
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000299bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
300 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000301 CXXRecordDecl *CurDecl;
302 if (SS) {
303 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
304 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
305 } else
306 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
307
308 if (CurDecl)
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000309 return &II == CurDecl->getIdentifier();
310 else
311 return false;
312}
313
Douglas Gregored3a3982009-03-03 04:44:36 +0000314/// \brief Check the validity of a C++ base class specifier.
315///
316/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
317/// and returns NULL otherwise.
318CXXBaseSpecifier *
319Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
320 SourceRange SpecifierRange,
321 bool Virtual, AccessSpecifier Access,
322 QualType BaseType,
323 SourceLocation BaseLoc) {
324 // C++ [class.union]p1:
325 // A union shall not have base classes.
326 if (Class->isUnion()) {
327 Diag(Class->getLocation(), diag::err_base_clause_on_union)
328 << SpecifierRange;
329 return 0;
330 }
331
332 if (BaseType->isDependentType())
333 return new CXXBaseSpecifier(SpecifierRange, Virtual,
334 Class->getTagKind() == RecordDecl::TK_class,
335 Access, BaseType);
336
337 // Base specifiers must be record types.
338 if (!BaseType->isRecordType()) {
339 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
340 return 0;
341 }
342
343 // C++ [class.union]p1:
344 // A union shall not be used as a base class.
345 if (BaseType->isUnionType()) {
346 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
347 return 0;
348 }
349
350 // C++ [class.derived]p2:
351 // The class-name in a base-specifier shall not be an incompletely
352 // defined class.
Douglas Gregorc84d8932009-03-09 16:13:40 +0000353 if (RequireCompleteType(BaseLoc, BaseType, diag::err_incomplete_base_class,
Douglas Gregor375733c2009-03-10 00:06:19 +0000354 SpecifierRange))
Douglas Gregored3a3982009-03-03 04:44:36 +0000355 return 0;
356
357 // If the base class is polymorphic, the new one is, too.
358 RecordDecl *BaseDecl = BaseType->getAsRecordType()->getDecl();
359 assert(BaseDecl && "Record type has no declaration");
360 BaseDecl = BaseDecl->getDefinition(Context);
361 assert(BaseDecl && "Base type is not incomplete, but has no definition");
362 if (cast<CXXRecordDecl>(BaseDecl)->isPolymorphic())
363 Class->setPolymorphic(true);
364
365 // C++ [dcl.init.aggr]p1:
366 // An aggregate is [...] a class with [...] no base classes [...].
367 Class->setAggregate(false);
368 Class->setPOD(false);
369
370 // Create the base specifier.
371 // FIXME: Allocate via ASTContext?
372 return new CXXBaseSpecifier(SpecifierRange, Virtual,
373 Class->getTagKind() == RecordDecl::TK_class,
374 Access, BaseType);
375}
376
Douglas Gregorec93f442008-04-13 21:30:24 +0000377/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
378/// one entry in the base class list of a class specifier, for
379/// example:
380/// class foo : public bar, virtual private baz {
381/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000382Sema::BaseResult
383Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
384 bool Virtual, AccessSpecifier Access,
385 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorf9ff4b12009-03-09 23:48:35 +0000386 AdjustDeclIfTemplate(classdecl);
387 CXXRecordDecl *Class = cast<CXXRecordDecl>((Decl*)classdecl);
Douglas Gregora60c62e2009-02-09 15:09:02 +0000388 QualType BaseType = QualType::getFromOpaquePtr(basetype);
Douglas Gregored3a3982009-03-03 04:44:36 +0000389 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
390 Virtual, Access,
391 BaseType, BaseLoc))
392 return BaseSpec;
393
394 return true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000395}
Douglas Gregorec93f442008-04-13 21:30:24 +0000396
Douglas Gregored3a3982009-03-03 04:44:36 +0000397/// \brief Performs the actual work of attaching the given base class
398/// specifiers to a C++ class.
399bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
400 unsigned NumBases) {
401 if (NumBases == 0)
402 return false;
Douglas Gregorabed2172008-10-22 17:49:05 +0000403
404 // Used to keep track of which base types we have already seen, so
405 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000406 // that the key is always the unqualified canonical type of the base
407 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000408 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
409
410 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000411 unsigned NumGoodBases = 0;
Douglas Gregored3a3982009-03-03 04:44:36 +0000412 bool Invalid = false;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000413 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000414 QualType NewBaseType
Douglas Gregored3a3982009-03-03 04:44:36 +0000415 = Context.getCanonicalType(Bases[idx]->getType());
Douglas Gregor4fd85902008-10-23 18:13:27 +0000416 NewBaseType = NewBaseType.getUnqualifiedType();
417
Douglas Gregorabed2172008-10-22 17:49:05 +0000418 if (KnownBaseTypes[NewBaseType]) {
419 // C++ [class.mi]p3:
420 // A class shall not be specified as a direct base class of a
421 // derived class more than once.
Douglas Gregored3a3982009-03-03 04:44:36 +0000422 Diag(Bases[idx]->getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000423 diag::err_duplicate_base_class)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000424 << KnownBaseTypes[NewBaseType]->getType()
Douglas Gregored3a3982009-03-03 04:44:36 +0000425 << Bases[idx]->getSourceRange();
Douglas Gregor4fd85902008-10-23 18:13:27 +0000426
427 // Delete the duplicate base class specifier; we're going to
428 // overwrite its pointer later.
Douglas Gregored3a3982009-03-03 04:44:36 +0000429 delete Bases[idx];
430
431 Invalid = true;
Douglas Gregorabed2172008-10-22 17:49:05 +0000432 } else {
433 // Okay, add this new base class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000434 KnownBaseTypes[NewBaseType] = Bases[idx];
435 Bases[NumGoodBases++] = Bases[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000436 }
437 }
438
439 // Attach the remaining base class specifiers to the derived class.
Douglas Gregored3a3982009-03-03 04:44:36 +0000440 Class->setBases(Bases, NumGoodBases);
Douglas Gregor4fd85902008-10-23 18:13:27 +0000441
442 // Delete the remaining (good) base class specifiers, since their
443 // data has been copied into the CXXRecordDecl.
444 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
Douglas Gregored3a3982009-03-03 04:44:36 +0000445 delete Bases[idx];
446
447 return Invalid;
448}
449
450/// ActOnBaseSpecifiers - Attach the given base specifiers to the
451/// class, after checking whether there are any duplicate base
452/// classes.
453void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
454 unsigned NumBases) {
455 if (!ClassDecl || !Bases || !NumBases)
456 return;
457
458 AdjustDeclIfTemplate(ClassDecl);
459 AttachBaseSpecifiers(cast<CXXRecordDecl>((Decl*)ClassDecl),
460 (CXXBaseSpecifier**)(Bases), NumBases);
Douglas Gregorec93f442008-04-13 21:30:24 +0000461}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000462
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000463//===----------------------------------------------------------------------===//
464// C++ class member Handling
465//===----------------------------------------------------------------------===//
466
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000467/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
468/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
469/// bitfield width if there is one and 'InitExpr' specifies the initializer if
470/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
471/// declarators on it.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000472Sema::DeclTy *
473Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
474 ExprTy *BW, ExprTy *InitExpr,
475 DeclTy *LastInGroup) {
476 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor6704b312008-11-17 22:58:34 +0000477 DeclarationName Name = GetNameForDeclarator(D);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000478 Expr *BitWidth = static_cast<Expr*>(BW);
479 Expr *Init = static_cast<Expr*>(InitExpr);
480 SourceLocation Loc = D.getIdentifierLoc();
481
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000482 bool isFunc = D.isFunctionDeclarator();
483
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000484 // C++ 9.2p6: A member shall not be declared to have automatic storage
485 // duration (auto, register) or with the extern storage-class-specifier.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000486 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
487 // data members and cannot be applied to names declared const or static,
488 // and cannot be applied to reference members.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000489 switch (DS.getStorageClassSpec()) {
490 case DeclSpec::SCS_unspecified:
491 case DeclSpec::SCS_typedef:
492 case DeclSpec::SCS_static:
493 // FALL THROUGH.
494 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000495 case DeclSpec::SCS_mutable:
496 if (isFunc) {
497 if (DS.getStorageClassSpecLoc().isValid())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000498 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000499 else
Chris Lattner8ba580c2008-11-19 05:08:23 +0000500 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
501
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000502 // FIXME: It would be nicer if the keyword was ignored only for this
503 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000504 D.getMutableDeclSpec().ClearStorageClassSpecs();
505 } else {
506 QualType T = GetTypeForDeclarator(D, S);
507 diag::kind err = static_cast<diag::kind>(0);
508 if (T->isReferenceType())
509 err = diag::err_mutable_reference;
510 else if (T.isConstQualified())
511 err = diag::err_mutable_const;
512 if (err != 0) {
513 if (DS.getStorageClassSpecLoc().isValid())
514 Diag(DS.getStorageClassSpecLoc(), err);
515 else
516 Diag(DS.getThreadSpecLoc(), err);
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +0000517 // FIXME: It would be nicer if the keyword was ignored only for this
518 // declarator. Otherwise we could get follow-up errors.
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000519 D.getMutableDeclSpec().ClearStorageClassSpecs();
520 }
521 }
522 break;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000523 default:
524 if (DS.getStorageClassSpecLoc().isValid())
525 Diag(DS.getStorageClassSpecLoc(),
526 diag::err_storageclass_invalid_for_member);
527 else
528 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
529 D.getMutableDeclSpec().ClearStorageClassSpecs();
530 }
531
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000532 if (!isFunc &&
Douglas Gregora60c62e2009-02-09 15:09:02 +0000533 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename &&
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000534 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000535 // Check also for this case:
536 //
537 // typedef int f();
538 // f a;
539 //
Douglas Gregora60c62e2009-02-09 15:09:02 +0000540 QualType TDType = QualType::getFromOpaquePtr(DS.getTypeRep());
541 isFunc = TDType->isFunctionType();
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000542 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000543
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000544 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
545 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000546 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000547
548 Decl *Member;
Chris Lattner9cffefc2009-03-05 22:45:59 +0000549 if (isInstField) {
Chris Lattnere384c182009-03-05 23:03:49 +0000550 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth);
551 assert(Member && "HandleField never returns null");
Chris Lattner9cffefc2009-03-05 22:45:59 +0000552 } else {
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000553 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Chris Lattnere384c182009-03-05 23:03:49 +0000554 if (!Member) {
555 if (BitWidth) DeleteExpr(BitWidth);
556 return LastInGroup;
557 }
Chris Lattner432780c2009-03-05 23:01:03 +0000558
559 // Non-instance-fields can't have a bitfield.
560 if (BitWidth) {
561 if (Member->isInvalidDecl()) {
562 // don't emit another diagnostic.
563 } else if (isa<CXXClassVarDecl>(Member)) {
564 // C++ 9.6p3: A bit-field shall not be a static member.
565 // "static member 'A' cannot be a bit-field"
566 Diag(Loc, diag::err_static_not_bitfield)
567 << Name << BitWidth->getSourceRange();
568 } else if (isa<TypedefDecl>(Member)) {
569 // "typedef member 'x' cannot be a bit-field"
570 Diag(Loc, diag::err_typedef_not_bitfield)
571 << Name << BitWidth->getSourceRange();
572 } else {
573 // A function typedef ("typedef int f(); f a;").
574 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
575 Diag(Loc, diag::err_not_integral_type_bitfield)
576 << Name << BitWidth->getSourceRange();
577 }
578
579 DeleteExpr(BitWidth);
580 BitWidth = 0;
581 Member->setInvalidDecl();
582 }
Chris Lattner9cffefc2009-03-05 22:45:59 +0000583 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000584
Douglas Gregor6704b312008-11-17 22:58:34 +0000585 assert((Name || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000586
587 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
588 // specific methods. Use a wrapper class that can be used with all C++ class
589 // member decls.
590 CXXClassMemberWrapper(Member).setAccess(AS);
591
Douglas Gregor15e04622008-11-05 16:20:31 +0000592 // C++ [dcl.init.aggr]p1:
593 // An aggregate is an array or a class (clause 9) with [...] no
594 // private or protected non-static data members (clause 11).
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000595 // A POD must be an aggregate.
596 if (isInstField && (AS == AS_private || AS == AS_protected)) {
597 CXXRecordDecl *Record = cast<CXXRecordDecl>(CurContext);
598 Record->setAggregate(false);
599 Record->setPOD(false);
600 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000601
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000602 if (DS.isVirtualSpecified()) {
603 if (!isFunc || DS.getStorageClassSpec() == DeclSpec::SCS_static) {
604 Diag(DS.getVirtualSpecLoc(), diag::err_virtual_non_function);
Chris Lattner432780c2009-03-05 23:01:03 +0000605 Member->setInvalidDecl();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000606 } else {
Sebastian Redl83faa292009-01-09 19:57:06 +0000607 cast<CXXMethodDecl>(Member)->setVirtual();
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000608 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(CurContext);
609 CurClass->setAggregate(false);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000610 CurClass->setPOD(false);
Sebastian Redla1cf66a2008-11-06 15:59:35 +0000611 CurClass->setPolymorphic(true);
612 }
613 }
Douglas Gregor15e04622008-11-05 16:20:31 +0000614
Sebastian Redl83faa292009-01-09 19:57:06 +0000615 // FIXME: The above definition of virtual is not sufficient. A function is
616 // also virtual if it overrides an already virtual function. This is important
617 // to do here because it decides the validity of a pure specifier.
618
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000619 if (Init) {
620 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
621 // if it declares a static member of const integral or const enumeration
622 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000623 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
624 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000625 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000626 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000627 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
628 CVD->getType()->isIntegralType()) {
629 // constant-initializer
630 if (CheckForConstantInitializer(Init, CVD->getType()))
Chris Lattner432780c2009-03-05 23:01:03 +0000631 Member->setInvalidDecl();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000632
633 } else {
634 // not const integral.
Chris Lattner77d52da2008-11-20 06:06:08 +0000635 Diag(Loc, diag::err_member_initialization)
Anders Carlsson0f5ae032008-12-06 20:05:35 +0000636 << Name << Init->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000637 Member->setInvalidDecl();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000638 }
639
640 } else {
Sebastian Redl83faa292009-01-09 19:57:06 +0000641 // not static member. perhaps virtual function?
642 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member)) {
Sebastian Redl54e4be92009-01-09 22:29:03 +0000643 // With declarators parsed the way they are, the parser cannot
644 // distinguish between a normal initializer and a pure-specifier.
645 // Thus this grotesque test.
Sebastian Redl83faa292009-01-09 19:57:06 +0000646 IntegerLiteral *IL;
647 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
648 Context.getCanonicalType(IL->getType()) == Context.IntTy) {
649 if (MD->isVirtual())
650 MD->setPure();
651 else {
652 Diag(Loc, diag::err_non_virtual_pure)
653 << Name << Init->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000654 Member->setInvalidDecl();
Sebastian Redl83faa292009-01-09 19:57:06 +0000655 }
656 } else {
657 Diag(Loc, diag::err_member_function_initialization)
658 << Name << Init->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000659 Member->setInvalidDecl();
Sebastian Redl83faa292009-01-09 19:57:06 +0000660 }
661 } else {
662 Diag(Loc, diag::err_member_initialization)
663 << Name << Init->getSourceRange();
Chris Lattner432780c2009-03-05 23:01:03 +0000664 Member->setInvalidDecl();
Sebastian Redl83faa292009-01-09 19:57:06 +0000665 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000666 }
667 }
668
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000669 if (isInstField) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000670 FieldCollector->Add(cast<FieldDecl>(Member));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000671 return LastInGroup;
672 }
673 return Member;
674}
675
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000676/// ActOnMemInitializer - Handle a C++ member initializer.
677Sema::MemInitResult
678Sema::ActOnMemInitializer(DeclTy *ConstructorD,
679 Scope *S,
680 IdentifierInfo *MemberOrBase,
681 SourceLocation IdLoc,
682 SourceLocation LParenLoc,
683 ExprTy **Args, unsigned NumArgs,
684 SourceLocation *CommaLocs,
685 SourceLocation RParenLoc) {
686 CXXConstructorDecl *Constructor
687 = dyn_cast<CXXConstructorDecl>((Decl*)ConstructorD);
688 if (!Constructor) {
689 // The user wrote a constructor initializer on a function that is
690 // not a C++ constructor. Ignore the error for now, because we may
691 // have more member initializers coming; we'll diagnose it just
692 // once in ActOnMemInitializers.
693 return true;
694 }
695
696 CXXRecordDecl *ClassDecl = Constructor->getParent();
697
698 // C++ [class.base.init]p2:
699 // Names in a mem-initializer-id are looked up in the scope of the
700 // constructor’s class and, if not found in that scope, are looked
701 // up in the scope containing the constructor’s
702 // definition. [Note: if the constructor’s class contains a member
703 // with the same name as a direct or virtual base class of the
704 // class, a mem-initializer-id naming the member or base class and
705 // composed of a single identifier refers to the class member. A
706 // mem-initializer-id for the hidden base class may be specified
707 // using a qualified name. ]
708 // Look for a member, first.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000709 FieldDecl *Member = 0;
Steve Naroffab63fd62009-01-08 17:28:14 +0000710 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000711 if (Result.first != Result.second)
712 Member = dyn_cast<FieldDecl>(*Result.first);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000713
714 // FIXME: Handle members of an anonymous union.
715
716 if (Member) {
717 // FIXME: Perform direct initialization of the member.
718 return new CXXBaseOrMemberInitializer(Member, (Expr **)Args, NumArgs);
719 }
720
721 // It didn't name a member, so see if it names a class.
Douglas Gregor1075a162009-02-04 17:00:24 +0000722 TypeTy *BaseTy = getTypeName(*MemberOrBase, IdLoc, S, 0/*SS*/);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000723 if (!BaseTy)
Chris Lattner65cae292008-11-19 08:23:25 +0000724 return Diag(IdLoc, diag::err_mem_init_not_member_or_class)
725 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000726
Douglas Gregora60c62e2009-02-09 15:09:02 +0000727 QualType BaseType = QualType::getFromOpaquePtr(BaseTy);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000728 if (!BaseType->isRecordType())
Chris Lattner65cae292008-11-19 08:23:25 +0000729 return Diag(IdLoc, diag::err_base_init_does_not_name_class)
Chris Lattnerb1753422008-11-23 21:45:46 +0000730 << BaseType << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000731
732 // C++ [class.base.init]p2:
733 // [...] Unless the mem-initializer-id names a nonstatic data
734 // member of the constructor’s class or a direct or virtual base
735 // of that class, the mem-initializer is ill-formed. A
736 // mem-initializer-list can initialize a base class using any
737 // name that denotes that base class type.
738
739 // First, check for a direct base class.
740 const CXXBaseSpecifier *DirectBaseSpec = 0;
741 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin();
742 Base != ClassDecl->bases_end(); ++Base) {
743 if (Context.getCanonicalType(BaseType).getUnqualifiedType() ==
744 Context.getCanonicalType(Base->getType()).getUnqualifiedType()) {
745 // We found a direct base of this type. That's what we're
746 // initializing.
747 DirectBaseSpec = &*Base;
748 break;
749 }
750 }
751
752 // Check for a virtual base class.
753 // FIXME: We might be able to short-circuit this if we know in
754 // advance that there are no virtual bases.
755 const CXXBaseSpecifier *VirtualBaseSpec = 0;
756 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
757 // We haven't found a base yet; search the class hierarchy for a
758 // virtual base class.
759 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
760 /*DetectVirtual=*/false);
761 if (IsDerivedFrom(Context.getTypeDeclType(ClassDecl), BaseType, Paths)) {
762 for (BasePaths::paths_iterator Path = Paths.begin();
763 Path != Paths.end(); ++Path) {
764 if (Path->back().Base->isVirtual()) {
765 VirtualBaseSpec = Path->back().Base;
766 break;
767 }
768 }
769 }
770 }
771
772 // C++ [base.class.init]p2:
773 // If a mem-initializer-id is ambiguous because it designates both
774 // a direct non-virtual base class and an inherited virtual base
775 // class, the mem-initializer is ill-formed.
776 if (DirectBaseSpec && VirtualBaseSpec)
Chris Lattner65cae292008-11-19 08:23:25 +0000777 return Diag(IdLoc, diag::err_base_init_direct_and_virtual)
778 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
Douglas Gregora65e8dd2008-11-05 04:29:56 +0000779
780 return new CXXBaseOrMemberInitializer(BaseType, (Expr **)Args, NumArgs);
781}
782
783
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000784void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
785 DeclTy *TagDecl,
786 SourceLocation LBrac,
787 SourceLocation RBrac) {
Douglas Gregored3a3982009-03-03 04:44:36 +0000788 TemplateDecl *Template = AdjustDeclIfTemplate(TagDecl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000789 ActOnFields(S, RLoc, TagDecl,
790 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000791 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Douglas Gregored3a3982009-03-03 04:44:36 +0000792
793 if (!Template)
794 AddImplicitlyDeclaredMembersToClass(cast<CXXRecordDecl>((Decl*)TagDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000795}
796
Douglas Gregore640ab62008-11-03 17:51:48 +0000797/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
798/// special functions, such as the default constructor, copy
799/// constructor, or destructor, to the given C++ class (C++
800/// [special]p1). This routine can only be executed just before the
801/// definition of the class is complete.
802void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000803 QualType ClassType = Context.getTypeDeclType(ClassDecl);
804 ClassType = Context.getCanonicalType(ClassType);
805
Douglas Gregore640ab62008-11-03 17:51:48 +0000806 if (!ClassDecl->hasUserDeclaredConstructor()) {
807 // C++ [class.ctor]p5:
808 // A default constructor for a class X is a constructor of class X
809 // that can be called without an argument. If there is no
810 // user-declared constructor for class X, a default constructor is
811 // implicitly declared. An implicitly-declared default constructor
812 // is an inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000813 DeclarationName Name
814 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000815 CXXConstructorDecl *DefaultCon =
816 CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000817 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000818 Context.getFunctionType(Context.VoidTy,
819 0, 0, false, 0),
820 /*isExplicit=*/false,
821 /*isInline=*/true,
822 /*isImplicitlyDeclared=*/true);
823 DefaultCon->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000824 DefaultCon->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000825 ClassDecl->addDecl(DefaultCon);
Douglas Gregorb9213832008-12-15 21:24:18 +0000826
827 // Notify the class that we've added a constructor.
828 ClassDecl->addedConstructor(Context, DefaultCon);
Douglas Gregore640ab62008-11-03 17:51:48 +0000829 }
830
831 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
832 // C++ [class.copy]p4:
833 // If the class definition does not explicitly declare a copy
834 // constructor, one is declared implicitly.
835
836 // C++ [class.copy]p5:
837 // The implicitly-declared copy constructor for a class X will
838 // have the form
839 //
840 // X::X(const X&)
841 //
842 // if
843 bool HasConstCopyConstructor = true;
844
845 // -- each direct or virtual base class B of X has a copy
846 // constructor whose first parameter is of type const B& or
847 // const volatile B&, and
848 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
849 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
850 const CXXRecordDecl *BaseClassDecl
851 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
852 HasConstCopyConstructor
853 = BaseClassDecl->hasConstCopyConstructor(Context);
854 }
855
856 // -- for all the nonstatic data members of X that are of a
857 // class type M (or array thereof), each such class type
858 // has a copy constructor whose first parameter is of type
859 // const M& or const volatile M&.
860 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
861 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
862 QualType FieldType = (*Field)->getType();
863 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
864 FieldType = Array->getElementType();
865 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
866 const CXXRecordDecl *FieldClassDecl
867 = cast<CXXRecordDecl>(FieldClassType->getDecl());
868 HasConstCopyConstructor
869 = FieldClassDecl->hasConstCopyConstructor(Context);
870 }
871 }
872
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000873 // Otherwise, the implicitly declared copy constructor will have
874 // the form
Douglas Gregore640ab62008-11-03 17:51:48 +0000875 //
876 // X::X(X&)
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000877 QualType ArgType = ClassType;
Douglas Gregore640ab62008-11-03 17:51:48 +0000878 if (HasConstCopyConstructor)
879 ArgType = ArgType.withConst();
880 ArgType = Context.getReferenceType(ArgType);
881
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000882 // An implicitly-declared copy constructor is an inline public
883 // member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000884 DeclarationName Name
885 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregore640ab62008-11-03 17:51:48 +0000886 CXXConstructorDecl *CopyConstructor
887 = CXXConstructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000888 ClassDecl->getLocation(), Name,
Douglas Gregore640ab62008-11-03 17:51:48 +0000889 Context.getFunctionType(Context.VoidTy,
890 &ArgType, 1,
891 false, 0),
892 /*isExplicit=*/false,
893 /*isInline=*/true,
894 /*isImplicitlyDeclared=*/true);
895 CopyConstructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000896 CopyConstructor->setImplicit();
Douglas Gregore640ab62008-11-03 17:51:48 +0000897
898 // Add the parameter to the constructor.
899 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
900 ClassDecl->getLocation(),
901 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000902 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000903 CopyConstructor->setParams(Context, &FromParam, 1);
Douglas Gregore640ab62008-11-03 17:51:48 +0000904
Douglas Gregorb9213832008-12-15 21:24:18 +0000905 ClassDecl->addedConstructor(Context, CopyConstructor);
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000906 ClassDecl->addDecl(CopyConstructor);
Douglas Gregore640ab62008-11-03 17:51:48 +0000907 }
908
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000909 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
910 // Note: The following rules are largely analoguous to the copy
911 // constructor rules. Note that virtual bases are not taken into account
912 // for determining the argument type of the operator. Note also that
913 // operators taking an object instead of a reference are allowed.
914 //
915 // C++ [class.copy]p10:
916 // If the class definition does not explicitly declare a copy
917 // assignment operator, one is declared implicitly.
918 // The implicitly-defined copy assignment operator for a class X
919 // will have the form
920 //
921 // X& X::operator=(const X&)
922 //
923 // if
924 bool HasConstCopyAssignment = true;
925
926 // -- each direct base class B of X has a copy assignment operator
927 // whose parameter is of type const B&, const volatile B& or B,
928 // and
929 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
930 HasConstCopyAssignment && Base != ClassDecl->bases_end(); ++Base) {
931 const CXXRecordDecl *BaseClassDecl
932 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
933 HasConstCopyAssignment = BaseClassDecl->hasConstCopyAssignment(Context);
934 }
935
936 // -- for all the nonstatic data members of X that are of a class
937 // type M (or array thereof), each such class type has a copy
938 // assignment operator whose parameter is of type const M&,
939 // const volatile M& or M.
940 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
941 HasConstCopyAssignment && Field != ClassDecl->field_end(); ++Field) {
942 QualType FieldType = (*Field)->getType();
943 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
944 FieldType = Array->getElementType();
945 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
946 const CXXRecordDecl *FieldClassDecl
947 = cast<CXXRecordDecl>(FieldClassType->getDecl());
948 HasConstCopyAssignment
949 = FieldClassDecl->hasConstCopyAssignment(Context);
950 }
951 }
952
953 // Otherwise, the implicitly declared copy assignment operator will
954 // have the form
955 //
956 // X& X::operator=(X&)
957 QualType ArgType = ClassType;
958 QualType RetType = Context.getReferenceType(ArgType);
959 if (HasConstCopyAssignment)
960 ArgType = ArgType.withConst();
961 ArgType = Context.getReferenceType(ArgType);
962
963 // An implicitly-declared copy assignment operator is an inline public
964 // member of its class.
965 DeclarationName Name =
966 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
967 CXXMethodDecl *CopyAssignment =
968 CXXMethodDecl::Create(Context, ClassDecl, ClassDecl->getLocation(), Name,
969 Context.getFunctionType(RetType, &ArgType, 1,
970 false, 0),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000971 /*isStatic=*/false, /*isInline=*/true);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000972 CopyAssignment->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +0000973 CopyAssignment->setImplicit();
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000974
975 // Add the parameter to the operator.
976 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
977 ClassDecl->getLocation(),
978 /*IdentifierInfo=*/0,
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000979 ArgType, VarDecl::None, 0);
Ted Kremenek8494c962009-01-14 00:42:25 +0000980 CopyAssignment->setParams(Context, &FromParam, 1);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000981
982 // Don't call addedAssignmentOperator. There is no way to distinguish an
983 // implicit from an explicit assignment operator.
Douglas Gregor03b2ad22009-01-12 23:27:07 +0000984 ClassDecl->addDecl(CopyAssignment);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000985 }
986
Douglas Gregorb9213832008-12-15 21:24:18 +0000987 if (!ClassDecl->hasUserDeclaredDestructor()) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000988 // C++ [class.dtor]p2:
989 // If a class has no user-declared destructor, a destructor is
990 // declared implicitly. An implicitly-declared destructor is an
991 // inline public member of its class.
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000992 DeclarationName Name
993 = Context.DeclarationNames.getCXXDestructorName(ClassType);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000994 CXXDestructorDecl *Destructor
995 = CXXDestructorDecl::Create(Context, ClassDecl,
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000996 ClassDecl->getLocation(), Name,
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000997 Context.getFunctionType(Context.VoidTy,
998 0, 0, false, 0),
999 /*isInline=*/true,
1000 /*isImplicitlyDeclared=*/true);
1001 Destructor->setAccess(AS_public);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001002 Destructor->setImplicit();
Douglas Gregor03b2ad22009-01-12 23:27:07 +00001003 ClassDecl->addDecl(Destructor);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001004 }
Douglas Gregore640ab62008-11-03 17:51:48 +00001005}
1006
Douglas Gregor605de8d2008-12-16 21:30:33 +00001007/// ActOnStartDelayedCXXMethodDeclaration - We have completed
1008/// parsing a top-level (non-nested) C++ class, and we are now
1009/// parsing those parts of the given Method declaration that could
1010/// not be parsed earlier (C++ [class.mem]p2), such as default
1011/// arguments. This action should enter the scope of the given
1012/// Method declaration as if we had just parsed the qualified method
1013/// name. However, it should not bring the parameters into scope;
1014/// that will be performed by ActOnDelayedCXXMethodParameter.
1015void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, DeclTy *Method) {
1016 CXXScopeSpec SS;
1017 SS.setScopeRep(((FunctionDecl*)Method)->getDeclContext());
1018 ActOnCXXEnterDeclaratorScope(S, SS);
1019}
1020
1021/// ActOnDelayedCXXMethodParameter - We've already started a delayed
1022/// C++ method declaration. We're (re-)introducing the given
1023/// function parameter into scope for use in parsing later parts of
1024/// the method declaration. For example, we could see an
1025/// ActOnParamDefaultArgument event for this parameter.
1026void Sema::ActOnDelayedCXXMethodParameter(Scope *S, DeclTy *ParamD) {
1027 ParmVarDecl *Param = (ParmVarDecl*)ParamD;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001028
1029 // If this parameter has an unparsed default argument, clear it out
1030 // to make way for the parsed default argument.
1031 if (Param->hasUnparsedDefaultArg())
1032 Param->setDefaultArg(0);
1033
Douglas Gregor605de8d2008-12-16 21:30:33 +00001034 S->AddDecl(Param);
1035 if (Param->getDeclName())
1036 IdResolver.AddDecl(Param);
1037}
1038
1039/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
1040/// processing the delayed method declaration for Method. The method
1041/// declaration is now considered finished. There may be a separate
1042/// ActOnStartOfFunctionDef action later (not necessarily
1043/// immediately!) for this method, if it was also defined inside the
1044/// class body.
1045void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, DeclTy *MethodD) {
1046 FunctionDecl *Method = (FunctionDecl*)MethodD;
1047 CXXScopeSpec SS;
1048 SS.setScopeRep(Method->getDeclContext());
1049 ActOnCXXExitDeclaratorScope(S, SS);
1050
1051 // Now that we have our default arguments, check the constructor
1052 // again. It could produce additional diagnostics or affect whether
1053 // the class has implicitly-declared destructors, among other
1054 // things.
1055 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method)) {
1056 if (CheckConstructor(Constructor))
1057 Constructor->setInvalidDecl();
1058 }
1059
1060 // Check the default arguments, which we may have added.
1061 if (!Method->isInvalidDecl())
1062 CheckCXXDefaultArguments(Method);
1063}
1064
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001065/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
Douglas Gregor605de8d2008-12-16 21:30:33 +00001066/// the well-formedness of the constructor declarator @p D with type @p
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001067/// R. If there are any errors in the declarator, this routine will
1068/// emit diagnostics and return true. Otherwise, it will return
1069/// false. Either way, the type @p R will be updated to reflect a
1070/// well-formed type for the constructor.
1071bool Sema::CheckConstructorDeclarator(Declarator &D, QualType &R,
1072 FunctionDecl::StorageClass& SC) {
1073 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1074 bool isInvalid = false;
1075
1076 // C++ [class.ctor]p3:
1077 // A constructor shall not be virtual (10.3) or static (9.4). A
1078 // constructor can be invoked for a const, volatile or const
1079 // volatile object. A constructor shall not be declared const,
1080 // volatile, or const volatile (9.3.2).
1081 if (isVirtual) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001082 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1083 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
1084 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001085 isInvalid = true;
1086 }
1087 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001088 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
1089 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1090 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001091 isInvalid = true;
1092 SC = FunctionDecl::None;
1093 }
1094 if (D.getDeclSpec().hasTypeSpecifier()) {
1095 // Constructors don't have return types, but the parser will
1096 // happily parse something like:
1097 //
1098 // class X {
1099 // float X(float);
1100 // };
1101 //
1102 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001103 Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
1104 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1105 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001106 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00001107 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001108 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1109 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001110 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1111 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001112 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001113 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1114 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001115 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001116 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
1117 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001118 }
1119
1120 // Rebuild the function type "R" without any type qualifiers (in
1121 // case any of the errors above fired) and with "void" as the
1122 // return type, since constructors don't have return types. We
1123 // *always* have to do this, because GetTypeForDeclarator will
1124 // put in a result type of "int" when none was specified.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001125 const FunctionProtoType *Proto = R->getAsFunctionProtoType();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001126 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
1127 Proto->getNumArgs(),
1128 Proto->isVariadic(),
1129 0);
1130
1131 return isInvalid;
1132}
1133
Douglas Gregor605de8d2008-12-16 21:30:33 +00001134/// CheckConstructor - Checks a fully-formed constructor for
1135/// well-formedness, issuing any diagnostics required. Returns true if
1136/// the constructor declarator is invalid.
1137bool Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
1138 if (Constructor->isInvalidDecl())
1139 return true;
1140
1141 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Constructor->getDeclContext());
1142 bool Invalid = false;
1143
1144 // C++ [class.copy]p3:
1145 // A declaration of a constructor for a class X is ill-formed if
1146 // its first parameter is of type (optionally cv-qualified) X and
1147 // either there are no other parameters or else all other
1148 // parameters have default arguments.
1149 if ((Constructor->getNumParams() == 1) ||
1150 (Constructor->getNumParams() > 1 &&
1151 Constructor->getParamDecl(1)->getDefaultArg() != 0)) {
1152 QualType ParamType = Constructor->getParamDecl(0)->getType();
1153 QualType ClassTy = Context.getTagDeclType(ClassDecl);
1154 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
1155 Diag(Constructor->getLocation(), diag::err_constructor_byvalue_arg)
1156 << SourceRange(Constructor->getParamDecl(0)->getLocation());
1157 Invalid = true;
1158 }
1159 }
1160
1161 // Notify the class that we've added a constructor.
1162 ClassDecl->addedConstructor(Context, Constructor);
1163
1164 return Invalid;
1165}
1166
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001167/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
1168/// the well-formednes of the destructor declarator @p D with type @p
1169/// R. If there are any errors in the declarator, this routine will
1170/// emit diagnostics and return true. Otherwise, it will return
1171/// false. Either way, the type @p R will be updated to reflect a
1172/// well-formed type for the destructor.
1173bool Sema::CheckDestructorDeclarator(Declarator &D, QualType &R,
1174 FunctionDecl::StorageClass& SC) {
1175 bool isInvalid = false;
1176
1177 // C++ [class.dtor]p1:
1178 // [...] A typedef-name that names a class is a class-name
1179 // (7.1.3); however, a typedef-name that names a class shall not
1180 // be used as the identifier in the declarator for a destructor
1181 // declaration.
Douglas Gregora60c62e2009-02-09 15:09:02 +00001182 QualType DeclaratorType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1183 if (DeclaratorType->getAsTypedefType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001184 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
Douglas Gregora60c62e2009-02-09 15:09:02 +00001185 << DeclaratorType;
Douglas Gregorbd19fdb2008-11-10 14:41:22 +00001186 isInvalid = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001187 }
1188
1189 // C++ [class.dtor]p2:
1190 // A destructor is used to destroy objects of its class type. A
1191 // destructor takes no parameters, and no return type can be
1192 // specified for it (not even void). The address of a destructor
1193 // shall not be taken. A destructor shall not be static. A
1194 // destructor can be invoked for a const, volatile or const
1195 // volatile object. A destructor shall not be declared const,
1196 // volatile or const volatile (9.3.2).
1197 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001198 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
1199 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1200 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001201 isInvalid = true;
1202 SC = FunctionDecl::None;
1203 }
1204 if (D.getDeclSpec().hasTypeSpecifier()) {
1205 // Destructors don't have return types, but the parser will
1206 // happily parse something like:
1207 //
1208 // class X {
1209 // float ~X();
1210 // };
1211 //
1212 // The return type will be eliminated later.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001213 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
1214 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1215 << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001216 }
Douglas Gregor4fa58902009-02-26 23:50:07 +00001217 if (R->getAsFunctionProtoType()->getTypeQuals() != 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001218 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1219 if (FTI.TypeQuals & QualType::Const)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001220 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1221 << "const" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001222 if (FTI.TypeQuals & QualType::Volatile)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001223 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1224 << "volatile" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001225 if (FTI.TypeQuals & QualType::Restrict)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001226 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
1227 << "restrict" << SourceRange(D.getIdentifierLoc());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001228 }
1229
1230 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001231 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001232 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
1233
1234 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001235 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001236 }
1237
1238 // Make sure the destructor isn't variadic.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001239 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001240 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
1241
1242 // Rebuild the function type "R" without any type qualifiers or
1243 // parameters (in case any of the errors above fired) and with
1244 // "void" as the return type, since destructors don't have return
1245 // types. We *always* have to do this, because GetTypeForDeclarator
1246 // will put in a result type of "int" when none was specified.
1247 R = Context.getFunctionType(Context.VoidTy, 0, 0, false, 0);
1248
1249 return isInvalid;
1250}
1251
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001252/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
1253/// well-formednes of the conversion function declarator @p D with
1254/// type @p R. If there are any errors in the declarator, this routine
1255/// will emit diagnostics and return true. Otherwise, it will return
1256/// false. Either way, the type @p R will be updated to reflect a
1257/// well-formed type for the conversion operator.
1258bool Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
1259 FunctionDecl::StorageClass& SC) {
1260 bool isInvalid = false;
1261
1262 // C++ [class.conv.fct]p1:
1263 // Neither parameter types nor return type can be specified. The
1264 // type of a conversion function (8.3.5) is “function taking no
1265 // parameter returning conversion-type-id.”
1266 if (SC == FunctionDecl::Static) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001267 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
1268 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
1269 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001270 isInvalid = true;
1271 SC = FunctionDecl::None;
1272 }
1273 if (D.getDeclSpec().hasTypeSpecifier()) {
1274 // Conversion functions don't have return types, but the parser will
1275 // happily parse something like:
1276 //
1277 // class X {
1278 // float operator bool();
1279 // };
1280 //
1281 // The return type will be changed later anyway.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001282 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
1283 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
1284 << SourceRange(D.getIdentifierLoc());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001285 }
1286
1287 // Make sure we don't have any parameters.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001288 if (R->getAsFunctionProtoType()->getNumArgs() > 0) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001289 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
1290
1291 // Delete the parameters.
Chris Lattner5c6139b2009-01-20 21:06:38 +00001292 D.getTypeObject(0).Fun.freeArgs();
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001293 }
1294
1295 // Make sure the conversion function isn't variadic.
Douglas Gregor4fa58902009-02-26 23:50:07 +00001296 if (R->getAsFunctionProtoType()->isVariadic())
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001297 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
1298
1299 // C++ [class.conv.fct]p4:
1300 // The conversion-type-id shall not represent a function type nor
1301 // an array type.
1302 QualType ConvType = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1303 if (ConvType->isArrayType()) {
1304 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
1305 ConvType = Context.getPointerType(ConvType);
1306 } else if (ConvType->isFunctionType()) {
1307 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
1308 ConvType = Context.getPointerType(ConvType);
1309 }
1310
1311 // Rebuild the function type "R" without any parameters (in case any
1312 // of the errors above fired) and with the conversion type as the
1313 // return type.
1314 R = Context.getFunctionType(ConvType, 0, 0, false,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001315 R->getAsFunctionProtoType()->getTypeQuals());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001316
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001317 // C++0x explicit conversion operators.
1318 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
1319 Diag(D.getDeclSpec().getExplicitSpecLoc(),
1320 diag::warn_explicit_conversion_functions)
1321 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
1322
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001323 return isInvalid;
1324}
1325
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001326/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
1327/// the declaration of the given C++ conversion function. This routine
1328/// is responsible for recording the conversion function in the C++
1329/// class, if possible.
1330Sema::DeclTy *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
1331 assert(Conversion && "Expected to receive a conversion function declaration");
1332
Douglas Gregor98341042008-12-12 08:25:50 +00001333 // Set the lexical context of this conversion function
1334 Conversion->setLexicalDeclContext(CurContext);
1335
1336 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001337
1338 // Make sure we aren't redeclaring the conversion function.
1339 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001340
1341 // C++ [class.conv.fct]p1:
1342 // [...] A conversion function is never used to convert a
1343 // (possibly cv-qualified) object to the (possibly cv-qualified)
1344 // same object type (or a reference to it), to a (possibly
1345 // cv-qualified) base class of that type (or a reference to it),
1346 // or to (possibly cv-qualified) void.
1347 // FIXME: Suppress this warning if the conversion function ends up
1348 // being a virtual function that overrides a virtual function in a
1349 // base class.
1350 QualType ClassType
1351 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
1352 if (const ReferenceType *ConvTypeRef = ConvType->getAsReferenceType())
1353 ConvType = ConvTypeRef->getPointeeType();
1354 if (ConvType->isRecordType()) {
1355 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
1356 if (ConvType == ClassType)
Chris Lattner8d756812008-11-20 06:13:02 +00001357 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001358 << ClassType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001359 else if (IsDerivedFrom(ClassType, ConvType))
Chris Lattner8d756812008-11-20 06:13:02 +00001360 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001361 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001362 } else if (ConvType->isVoidType()) {
Chris Lattner8d756812008-11-20 06:13:02 +00001363 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001364 << ClassType << ConvType;
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001365 }
1366
Douglas Gregor853dd392008-12-26 15:00:45 +00001367 if (Conversion->getPreviousDeclaration()) {
1368 OverloadedFunctionDecl *Conversions = ClassDecl->getConversionFunctions();
1369 for (OverloadedFunctionDecl::function_iterator
1370 Conv = Conversions->function_begin(),
1371 ConvEnd = Conversions->function_end();
1372 Conv != ConvEnd; ++Conv) {
1373 if (*Conv == Conversion->getPreviousDeclaration()) {
1374 *Conv = Conversion;
1375 return (DeclTy *)Conversion;
1376 }
1377 }
1378 assert(Conversion->isInvalidDecl() && "Conversion should not get here.");
1379 } else
1380 ClassDecl->addConversionFunction(Context, Conversion);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001381
1382 return (DeclTy *)Conversion;
1383}
1384
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001385//===----------------------------------------------------------------------===//
1386// Namespace Handling
1387//===----------------------------------------------------------------------===//
1388
1389/// ActOnStartNamespaceDef - This is called at the start of a namespace
1390/// definition.
1391Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
1392 SourceLocation IdentLoc,
1393 IdentifierInfo *II,
1394 SourceLocation LBrace) {
1395 NamespaceDecl *Namespc =
1396 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
1397 Namespc->setLBracLoc(LBrace);
1398
1399 Scope *DeclRegionScope = NamespcScope->getParent();
1400
1401 if (II) {
1402 // C++ [namespace.def]p2:
1403 // The identifier in an original-namespace-definition shall not have been
1404 // previously defined in the declarative region in which the
1405 // original-namespace-definition appears. The identifier in an
1406 // original-namespace-definition is the name of the namespace. Subsequently
1407 // in that declarative region, it is treated as an original-namespace-name.
1408
Douglas Gregor09be81b2009-02-04 17:27:36 +00001409 NamedDecl *PrevDecl = LookupName(DeclRegionScope, II, LookupOrdinaryName,
1410 true);
Douglas Gregor8acb7272008-12-11 16:49:14 +00001411
1412 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
1413 // This is an extended namespace definition.
1414 // Attach this namespace decl to the chain of extended namespace
1415 // definitions.
1416 OrigNS->setNextNamespace(Namespc);
1417 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001418
Douglas Gregor8acb7272008-12-11 16:49:14 +00001419 // Remove the previous declaration from the scope.
1420 if (DeclRegionScope->isDeclScope(OrigNS)) {
Douglas Gregor39677622008-12-11 20:41:00 +00001421 IdResolver.RemoveDecl(OrigNS);
1422 DeclRegionScope->RemoveDecl(OrigNS);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001423 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001424 } else if (PrevDecl) {
1425 // This is an invalid name redefinition.
1426 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
1427 << Namespc->getDeclName();
1428 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1429 Namespc->setInvalidDecl();
1430 // Continue on to push Namespc as current DeclContext and return it.
1431 }
1432
1433 PushOnScopeChains(Namespc, DeclRegionScope);
1434 } else {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001435 // FIXME: Handle anonymous namespaces
1436 }
1437
1438 // Although we could have an invalid decl (i.e. the namespace name is a
1439 // redefinition), push it as current DeclContext and try to continue parsing.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001440 // FIXME: We should be able to push Namespc here, so that the
1441 // each DeclContext for the namespace has the declarations
1442 // that showed up in that particular namespace definition.
1443 PushDeclContext(NamespcScope, Namespc);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001444 return Namespc;
1445}
1446
1447/// ActOnFinishNamespaceDef - This callback is called after a namespace is
1448/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
1449void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
1450 Decl *Dcl = static_cast<Decl *>(D);
1451 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
1452 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
1453 Namespc->setRBracLoc(RBrace);
1454 PopDeclContext();
1455}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001456
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001457Sema::DeclTy *Sema::ActOnUsingDirective(Scope *S,
1458 SourceLocation UsingLoc,
1459 SourceLocation NamespcLoc,
1460 const CXXScopeSpec &SS,
1461 SourceLocation IdentLoc,
1462 IdentifierInfo *NamespcName,
1463 AttributeList *AttrList) {
1464 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
1465 assert(NamespcName && "Invalid NamespcName.");
1466 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001467 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001468
Douglas Gregor7a7be652009-02-03 19:21:40 +00001469 UsingDirectiveDecl *UDir = 0;
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001470
Douglas Gregor78d70132009-01-14 22:20:51 +00001471 // Lookup namespace name.
Douglas Gregor7a7be652009-02-03 19:21:40 +00001472 LookupResult R = LookupParsedName(S, &SS, NamespcName,
1473 LookupNamespaceName, false);
1474 if (R.isAmbiguous()) {
1475 DiagnoseAmbiguousLookup(R, NamespcName, IdentLoc);
1476 return 0;
1477 }
Douglas Gregor09be81b2009-02-04 17:27:36 +00001478 if (NamedDecl *NS = R) {
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001479 assert(isa<NamespaceDecl>(NS) && "expected namespace decl");
Douglas Gregor7a7be652009-02-03 19:21:40 +00001480 // C++ [namespace.udir]p1:
1481 // A using-directive specifies that the names in the nominated
1482 // namespace can be used in the scope in which the
1483 // using-directive appears after the using-directive. During
1484 // unqualified name lookup (3.4.1), the names appear as if they
1485 // were declared in the nearest enclosing namespace which
1486 // contains both the using-directive and the nominated
1487 // namespace. [Note: in this context, “contains” means “contains
1488 // directly or indirectly”. ]
1489
1490 // Find enclosing context containing both using-directive and
1491 // nominated namespace.
1492 DeclContext *CommonAncestor = cast<DeclContext>(NS);
1493 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
1494 CommonAncestor = CommonAncestor->getParent();
1495
1496 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc,
1497 NamespcLoc, IdentLoc,
1498 cast<NamespaceDecl>(NS),
1499 CommonAncestor);
1500 PushUsingDirective(S, UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001501 } else {
Chris Lattner954381a2009-01-06 07:24:29 +00001502 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001503 }
1504
Douglas Gregor7a7be652009-02-03 19:21:40 +00001505 // FIXME: We ignore attributes for now.
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001506 delete AttrList;
Douglas Gregor7a7be652009-02-03 19:21:40 +00001507 return UDir;
1508}
1509
1510void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
1511 // If scope has associated entity, then using directive is at namespace
1512 // or translation unit scope. We add UsingDirectiveDecls, into
1513 // it's lookup structure.
1514 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
1515 Ctx->addDecl(UDir);
1516 else
1517 // Otherwise it is block-sope. using-directives will affect lookup
1518 // only to the end of scope.
1519 S->PushUsingDirective(UDir);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +00001520}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001521
1522/// AddCXXDirectInitializerToDecl - This action is called immediately after
1523/// ActOnDeclarator, when a C++ direct initializer is present.
1524/// e.g: "int x(1);"
1525void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
1526 ExprTy **ExprTys, unsigned NumExprs,
1527 SourceLocation *CommaLocs,
1528 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001529 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001530 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001531
1532 // If there is no declaration, there was an error parsing it. Just ignore
1533 // the initializer.
1534 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +00001535 for (unsigned i = 0; i != NumExprs; ++i)
Ted Kremenek0c97e042009-02-07 01:47:29 +00001536 static_cast<Expr *>(ExprTys[i])->Destroy(Context);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001537 return;
1538 }
1539
1540 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1541 if (!VDecl) {
1542 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
1543 RealDecl->setInvalidDecl();
1544 return;
1545 }
1546
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001547 // We will treat direct-initialization as a copy-initialization:
1548 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001549 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
1550 //
1551 // Clients that want to distinguish between the two forms, can check for
1552 // direct initializer using VarDecl::hasCXXDirectInitializer().
1553 // A major benefit is that clients that don't particularly care about which
1554 // exactly form was it (like the CodeGen) can handle both cases without
1555 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001556
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001557 // C++ 8.5p11:
1558 // The form of initialization (using parentheses or '=') is generally
1559 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001560 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +00001561 QualType DeclInitType = VDecl->getType();
1562 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
1563 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001564
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001565 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001566 CXXConstructorDecl *Constructor
Douglas Gregor6428e762008-11-05 15:29:30 +00001567 = PerformInitializationByConstructor(DeclInitType,
1568 (Expr **)ExprTys, NumExprs,
1569 VDecl->getLocation(),
1570 SourceRange(VDecl->getLocation(),
1571 RParenLoc),
Chris Lattner271d4c22008-11-24 05:29:24 +00001572 VDecl->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00001573 IK_Direct);
Douglas Gregor5870a952008-11-03 20:45:27 +00001574 if (!Constructor) {
1575 RealDecl->setInvalidDecl();
1576 }
Douglas Gregor6428e762008-11-05 15:29:30 +00001577
1578 // Let clients know that initialization was done with a direct
1579 // initializer.
1580 VDecl->setCXXDirectInitializer(true);
1581
1582 // FIXME: Add ExprTys and Constructor to the RealDecl as part of
1583 // the initializer.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +00001584 return;
1585 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001586
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001587 if (NumExprs > 1) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001588 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg)
1589 << SourceRange(VDecl->getLocation(), RParenLoc);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001590 RealDecl->setInvalidDecl();
1591 return;
1592 }
1593
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001594 // Let clients know that initialization was done with a direct initializer.
1595 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +00001596
1597 assert(NumExprs == 1 && "Expected 1 expression");
1598 // Set the init expression, handles conversions.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001599 AddInitializerToDecl(Dcl, ExprArg(*this, ExprTys[0]), /*DirectInit=*/true);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +00001600}
Douglas Gregor81c29152008-10-29 00:13:59 +00001601
Douglas Gregor6428e762008-11-05 15:29:30 +00001602/// PerformInitializationByConstructor - Perform initialization by
1603/// constructor (C++ [dcl.init]p14), which may occur as part of
1604/// direct-initialization or copy-initialization. We are initializing
1605/// an object of type @p ClassType with the given arguments @p
1606/// Args. @p Loc is the location in the source code where the
1607/// initializer occurs (e.g., a declaration, member initializer,
1608/// functional cast, etc.) while @p Range covers the whole
1609/// initialization. @p InitEntity is the entity being initialized,
1610/// which may by the name of a declaration or a type. @p Kind is the
1611/// kind of initialization we're performing, which affects whether
1612/// explicit constructors will be considered. When successful, returns
Douglas Gregor5870a952008-11-03 20:45:27 +00001613/// the constructor that will be used to perform the initialization;
Douglas Gregor6428e762008-11-05 15:29:30 +00001614/// when the initialization fails, emits a diagnostic and returns
1615/// null.
Douglas Gregor5870a952008-11-03 20:45:27 +00001616CXXConstructorDecl *
Douglas Gregor6428e762008-11-05 15:29:30 +00001617Sema::PerformInitializationByConstructor(QualType ClassType,
1618 Expr **Args, unsigned NumArgs,
1619 SourceLocation Loc, SourceRange Range,
Chris Lattner271d4c22008-11-24 05:29:24 +00001620 DeclarationName InitEntity,
Douglas Gregor6428e762008-11-05 15:29:30 +00001621 InitializationKind Kind) {
Douglas Gregor5870a952008-11-03 20:45:27 +00001622 const RecordType *ClassRec = ClassType->getAsRecordType();
1623 assert(ClassRec && "Can only initialize a class type here");
1624
1625 // C++ [dcl.init]p14:
1626 //
1627 // If the initialization is direct-initialization, or if it is
1628 // copy-initialization where the cv-unqualified version of the
1629 // source type is the same class as, or a derived class of, the
1630 // class of the destination, constructors are considered. The
1631 // applicable constructors are enumerated (13.3.1.3), and the
1632 // best one is chosen through overload resolution (13.3). The
1633 // constructor so selected is called to initialize the object,
1634 // with the initializer expression(s) as its argument(s). If no
1635 // constructor applies, or the overload resolution is ambiguous,
1636 // the initialization is ill-formed.
Douglas Gregor5870a952008-11-03 20:45:27 +00001637 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1638 OverloadCandidateSet CandidateSet;
Douglas Gregor6428e762008-11-05 15:29:30 +00001639
1640 // Add constructors to the overload set.
Douglas Gregorb9213832008-12-15 21:24:18 +00001641 DeclarationName ConstructorName
1642 = Context.DeclarationNames.getCXXConstructorName(
1643 Context.getCanonicalType(ClassType.getUnqualifiedType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001644 DeclContext::lookup_const_iterator Con, ConEnd;
Steve Naroffab63fd62009-01-08 17:28:14 +00001645 for (llvm::tie(Con, ConEnd) = ClassDecl->lookup(ConstructorName);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001646 Con != ConEnd; ++Con) {
1647 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
Douglas Gregor6428e762008-11-05 15:29:30 +00001648 if ((Kind == IK_Direct) ||
1649 (Kind == IK_Copy && Constructor->isConvertingConstructor()) ||
1650 (Kind == IK_Default && Constructor->isDefaultConstructor()))
1651 AddOverloadCandidate(Constructor, Args, NumArgs, CandidateSet);
1652 }
1653
Douglas Gregorb9213832008-12-15 21:24:18 +00001654 // FIXME: When we decide not to synthesize the implicitly-declared
1655 // constructors, we'll need to make them appear here.
1656
Douglas Gregor5870a952008-11-03 20:45:27 +00001657 OverloadCandidateSet::iterator Best;
Douglas Gregor5870a952008-11-03 20:45:27 +00001658 switch (BestViableFunction(CandidateSet, Best)) {
1659 case OR_Success:
1660 // We found a constructor. Return it.
1661 return cast<CXXConstructorDecl>(Best->Function);
1662
1663 case OR_No_Viable_Function:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001664 if (InitEntity)
1665 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001666 << InitEntity << Range;
Douglas Gregor538a4c22009-02-02 17:43:21 +00001667 else
1668 Diag(Loc, diag::err_ovl_no_viable_function_in_init)
Chris Lattner4a526112009-02-17 07:29:20 +00001669 << ClassType << Range;
Sebastian Redlfd9f2ac2008-11-22 13:44:36 +00001670 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor5870a952008-11-03 20:45:27 +00001671 return 0;
1672
1673 case OR_Ambiguous:
Douglas Gregor538a4c22009-02-02 17:43:21 +00001674 if (InitEntity)
1675 Diag(Loc, diag::err_ovl_ambiguous_init) << InitEntity << Range;
1676 else
1677 Diag(Loc, diag::err_ovl_ambiguous_init) << ClassType << Range;
Douglas Gregor5870a952008-11-03 20:45:27 +00001678 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1679 return 0;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001680
1681 case OR_Deleted:
1682 if (InitEntity)
1683 Diag(Loc, diag::err_ovl_deleted_init)
1684 << Best->Function->isDeleted()
1685 << InitEntity << Range;
1686 else
1687 Diag(Loc, diag::err_ovl_deleted_init)
1688 << Best->Function->isDeleted()
1689 << InitEntity << Range;
1690 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1691 return 0;
Douglas Gregor5870a952008-11-03 20:45:27 +00001692 }
1693
1694 return 0;
1695}
1696
Douglas Gregor81c29152008-10-29 00:13:59 +00001697/// CompareReferenceRelationship - Compare the two types T1 and T2 to
1698/// determine whether they are reference-related,
1699/// reference-compatible, reference-compatible with added
1700/// qualification, or incompatible, for use in C++ initialization by
1701/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
1702/// type, and the first type (T1) is the pointee type of the reference
1703/// type being initialized.
1704Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001705Sema::CompareReferenceRelationship(QualType T1, QualType T2,
1706 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001707 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
1708 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
1709
1710 T1 = Context.getCanonicalType(T1);
1711 T2 = Context.getCanonicalType(T2);
1712 QualType UnqualT1 = T1.getUnqualifiedType();
1713 QualType UnqualT2 = T2.getUnqualifiedType();
1714
1715 // C++ [dcl.init.ref]p4:
1716 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
1717 // reference-related to “cv2 T2” if T1 is the same type as T2, or
1718 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001719 if (UnqualT1 == UnqualT2)
1720 DerivedToBase = false;
1721 else if (IsDerivedFrom(UnqualT2, UnqualT1))
1722 DerivedToBase = true;
1723 else
Douglas Gregor81c29152008-10-29 00:13:59 +00001724 return Ref_Incompatible;
1725
1726 // At this point, we know that T1 and T2 are reference-related (at
1727 // least).
1728
1729 // C++ [dcl.init.ref]p4:
1730 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
1731 // reference-related to T2 and cv1 is the same cv-qualification
1732 // as, or greater cv-qualification than, cv2. For purposes of
1733 // overload resolution, cases for which cv1 is greater
1734 // cv-qualification than cv2 are identified as
1735 // reference-compatible with added qualification (see 13.3.3.2).
1736 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1737 return Ref_Compatible;
1738 else if (T1.isMoreQualifiedThan(T2))
1739 return Ref_Compatible_With_Added_Qualification;
1740 else
1741 return Ref_Related;
1742}
1743
1744/// CheckReferenceInit - Check the initialization of a reference
1745/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1746/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001747/// list), and DeclType is the type of the declaration. When ICS is
1748/// non-null, this routine will compute the implicit conversion
1749/// sequence according to C++ [over.ics.ref] and will not produce any
1750/// diagnostics; when ICS is null, it will emit diagnostics when any
1751/// errors are found. Either way, a return value of true indicates
1752/// that there was a failure, a return value of false indicates that
1753/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001754///
1755/// When @p SuppressUserConversions, user-defined conversions are
1756/// suppressed.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001757/// When @p AllowExplicit, we also permit explicit user-defined
1758/// conversion functions.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001759bool
1760Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001761 ImplicitConversionSequence *ICS,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001762 bool SuppressUserConversions,
1763 bool AllowExplicit) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001764 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1765
1766 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1767 QualType T2 = Init->getType();
1768
Douglas Gregor45014fd2008-11-10 20:40:00 +00001769 // If the initializer is the address of an overloaded function, try
1770 // to resolve the overloaded function. If all goes well, T2 is the
1771 // type of the resulting function.
1772 if (T2->isOverloadType()) {
1773 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Init, DeclType,
1774 ICS != 0);
1775 if (Fn) {
1776 // Since we're performing this reference-initialization for
1777 // real, update the initializer with the resulting function.
Douglas Gregoraa57e862009-02-18 21:56:37 +00001778 if (!ICS) {
1779 if (DiagnoseUseOfDecl(Fn, Init->getSourceRange().getBegin()))
1780 return true;
1781
Douglas Gregor45014fd2008-11-10 20:40:00 +00001782 FixOverloadedFunctionReference(Init, Fn);
Douglas Gregoraa57e862009-02-18 21:56:37 +00001783 }
Douglas Gregor45014fd2008-11-10 20:40:00 +00001784
1785 T2 = Fn->getType();
1786 }
1787 }
1788
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001789 // Compute some basic properties of the types and the initializer.
1790 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001791 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001792 ReferenceCompareResult RefRelationship
1793 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1794
1795 // Most paths end in a failed conversion.
1796 if (ICS)
1797 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001798
1799 // C++ [dcl.init.ref]p5:
1800 // A reference to type “cv1 T1” is initialized by an expression
1801 // of type “cv2 T2” as follows:
1802
1803 // -- If the initializer expression
1804
1805 bool BindsDirectly = false;
1806 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1807 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001808 //
1809 // Note that the bit-field check is skipped if we are just computing
1810 // the implicit conversion sequence (C++ [over.best.ics]p2).
1811 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1812 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001813 BindsDirectly = true;
1814
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001815 if (ICS) {
1816 // C++ [over.ics.ref]p1:
1817 // When a parameter of reference type binds directly (8.5.3)
1818 // to an argument expression, the implicit conversion sequence
1819 // is the identity conversion, unless the argument expression
1820 // has a type that is a derived class of the parameter type,
1821 // in which case the implicit conversion sequence is a
1822 // derived-to-base Conversion (13.3.3.1).
1823 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1824 ICS->Standard.First = ICK_Identity;
1825 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1826 ICS->Standard.Third = ICK_Identity;
1827 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1828 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001829 ICS->Standard.ReferenceBinding = true;
1830 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001831
1832 // Nothing more to do: the inaccessibility/ambiguity check for
1833 // derived-to-base conversions is suppressed when we're
1834 // computing the implicit conversion sequence (C++
1835 // [over.best.ics]p2).
1836 return false;
1837 } else {
1838 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001839 // FIXME: Binding to a subobject of the lvalue is going to require
1840 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001841 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001842 }
1843 }
1844
1845 // -- has a class type (i.e., T2 is a class type) and can be
1846 // implicitly converted to an lvalue of type “cv3 T3,”
1847 // where “cv1 T1” is reference-compatible with “cv3 T3”
1848 // 92) (this conversion is selected by enumerating the
1849 // applicable conversion functions (13.3.1.6) and choosing
1850 // the best one through overload resolution (13.3)),
Douglas Gregore6985fe2008-11-10 16:14:15 +00001851 if (!SuppressUserConversions && T2->isRecordType()) {
1852 // FIXME: Look for conversions in base classes!
1853 CXXRecordDecl *T2RecordDecl
1854 = dyn_cast<CXXRecordDecl>(T2->getAsRecordType()->getDecl());
Douglas Gregor81c29152008-10-29 00:13:59 +00001855
Douglas Gregore6985fe2008-11-10 16:14:15 +00001856 OverloadCandidateSet CandidateSet;
1857 OverloadedFunctionDecl *Conversions
1858 = T2RecordDecl->getConversionFunctions();
1859 for (OverloadedFunctionDecl::function_iterator Func
1860 = Conversions->function_begin();
1861 Func != Conversions->function_end(); ++Func) {
1862 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
1863
1864 // If the conversion function doesn't return a reference type,
1865 // it can't be considered for this conversion.
1866 // FIXME: This will change when we support rvalue references.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00001867 if (Conv->getConversionType()->isReferenceType() &&
1868 (AllowExplicit || !Conv->isExplicit()))
Douglas Gregore6985fe2008-11-10 16:14:15 +00001869 AddConversionCandidate(Conv, Init, DeclType, CandidateSet);
1870 }
1871
1872 OverloadCandidateSet::iterator Best;
1873 switch (BestViableFunction(CandidateSet, Best)) {
1874 case OR_Success:
1875 // This is a direct binding.
1876 BindsDirectly = true;
1877
1878 if (ICS) {
1879 // C++ [over.ics.ref]p1:
1880 //
1881 // [...] If the parameter binds directly to the result of
1882 // applying a conversion function to the argument
1883 // expression, the implicit conversion sequence is a
1884 // user-defined conversion sequence (13.3.3.1.2), with the
1885 // second standard conversion sequence either an identity
1886 // conversion or, if the conversion function returns an
1887 // entity of a type that is a derived class of the parameter
1888 // type, a derived-to-base Conversion.
1889 ICS->ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
1890 ICS->UserDefined.Before = Best->Conversions[0].Standard;
1891 ICS->UserDefined.After = Best->FinalConversion;
1892 ICS->UserDefined.ConversionFunction = Best->Function;
1893 assert(ICS->UserDefined.After.ReferenceBinding &&
1894 ICS->UserDefined.After.DirectBinding &&
1895 "Expected a direct reference binding!");
1896 return false;
1897 } else {
1898 // Perform the conversion.
1899 // FIXME: Binding to a subobject of the lvalue is going to require
1900 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001901 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregore6985fe2008-11-10 16:14:15 +00001902 }
1903 break;
1904
1905 case OR_Ambiguous:
1906 assert(false && "Ambiguous reference binding conversions not implemented.");
1907 return true;
1908
1909 case OR_No_Viable_Function:
Douglas Gregoraa57e862009-02-18 21:56:37 +00001910 case OR_Deleted:
1911 // There was no suitable conversion, or we found a deleted
1912 // conversion; continue with other checks.
Douglas Gregore6985fe2008-11-10 16:14:15 +00001913 break;
1914 }
1915 }
1916
Douglas Gregor81c29152008-10-29 00:13:59 +00001917 if (BindsDirectly) {
1918 // C++ [dcl.init.ref]p4:
1919 // [...] In all cases where the reference-related or
1920 // reference-compatible relationship of two types is used to
1921 // establish the validity of a reference binding, and T1 is a
1922 // base class of T2, a program that necessitates such a binding
1923 // is ill-formed if T1 is an inaccessible (clause 11) or
1924 // ambiguous (10.2) base class of T2.
1925 //
1926 // Note that we only check this condition when we're allowed to
1927 // complain about errors, because we should not be checking for
1928 // ambiguity (or inaccessibility) unless the reference binding
1929 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001930 if (DerivedToBase)
1931 return CheckDerivedToBaseConversion(T2, T1,
1932 Init->getSourceRange().getBegin(),
1933 Init->getSourceRange());
1934 else
1935 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001936 }
1937
1938 // -- Otherwise, the reference shall be to a non-volatile const
1939 // type (i.e., cv1 shall be const).
1940 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001941 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001942 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00001943 diag::err_not_reference_to_const_init)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001944 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
1945 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00001946 return true;
1947 }
1948
1949 // -- If the initializer expression is an rvalue, with T2 a
1950 // class type, and “cv1 T1” is reference-compatible with
1951 // “cv2 T2,” the reference is bound in one of the
1952 // following ways (the choice is implementation-defined):
1953 //
1954 // -- The reference is bound to the object represented by
1955 // the rvalue (see 3.10) or to a sub-object within that
1956 // object.
1957 //
1958 // -- A temporary of type “cv1 T2” [sic] is created, and
1959 // a constructor is called to copy the entire rvalue
1960 // object into the temporary. The reference is bound to
1961 // the temporary or to a sub-object within the
1962 // temporary.
1963 //
Douglas Gregor81c29152008-10-29 00:13:59 +00001964 // The constructor that would be used to make the copy
1965 // shall be callable whether or not the copy is actually
1966 // done.
1967 //
1968 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1969 // freedom, so we will always take the first option and never build
1970 // a temporary in this case. FIXME: We will, however, have to check
1971 // for the presence of a copy constructor in C++98/03 mode.
1972 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001973 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1974 if (ICS) {
1975 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1976 ICS->Standard.First = ICK_Identity;
1977 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1978 ICS->Standard.Third = ICK_Identity;
1979 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1980 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001981 ICS->Standard.ReferenceBinding = true;
1982 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001983 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001984 // FIXME: Binding to a subobject of the rvalue is going to require
1985 // more AST annotation than this.
Douglas Gregor70d26122008-11-12 17:17:38 +00001986 ImpCastExprToType(Init, T1, /*isLvalue=*/true);
Douglas Gregor81c29152008-10-29 00:13:59 +00001987 }
1988 return false;
1989 }
1990
1991 // -- Otherwise, a temporary of type “cv1 T1” is created and
1992 // initialized from the initializer expression using the
1993 // rules for a non-reference copy initialization (8.5). The
1994 // reference is then bound to the temporary. If T1 is
1995 // reference-related to T2, cv1 must be the same
1996 // cv-qualification as, or greater cv-qualification than,
1997 // cv2; otherwise, the program is ill-formed.
1998 if (RefRelationship == Ref_Related) {
1999 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2000 // we would be reference-compatible or reference-compatible with
2001 // added qualification. But that wasn't the case, so the reference
2002 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002003 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00002004 Diag(Init->getSourceRange().getBegin(),
Chris Lattner70b93d82008-11-18 22:52:51 +00002005 diag::err_reference_init_drops_quals)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002006 << T1 << (InitLvalue != Expr::LV_Valid? "temporary" : "value")
2007 << T2 << Init->getSourceRange();
Douglas Gregor81c29152008-10-29 00:13:59 +00002008 return true;
2009 }
2010
Douglas Gregorb206cc42009-01-30 23:27:23 +00002011 // If at least one of the types is a class type, the types are not
2012 // related, and we aren't allowed any user conversions, the
2013 // reference binding fails. This case is important for breaking
2014 // recursion, since TryImplicitConversion below will attempt to
2015 // create a temporary through the use of a copy constructor.
2016 if (SuppressUserConversions && RefRelationship == Ref_Incompatible &&
2017 (T1->isRecordType() || T2->isRecordType())) {
2018 if (!ICS)
2019 Diag(Init->getSourceRange().getBegin(),
2020 diag::err_typecheck_convert_incompatible)
2021 << DeclType << Init->getType() << "initializing" << Init->getSourceRange();
2022 return true;
2023 }
2024
Douglas Gregor81c29152008-10-29 00:13:59 +00002025 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002026 if (ICS) {
2027 /// C++ [over.ics.ref]p2:
2028 ///
2029 /// When a parameter of reference type is not bound directly to
2030 /// an argument expression, the conversion sequence is the one
2031 /// required to convert the argument expression to the
2032 /// underlying type of the reference according to
2033 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
2034 /// to copy-initializing a temporary of the underlying type with
2035 /// the argument expression. Any difference in top-level
2036 /// cv-qualification is subsumed by the initialization itself
2037 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00002038 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002039 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
2040 } else {
Douglas Gregor6fd35572008-12-19 17:40:08 +00002041 return PerformImplicitConversion(Init, T1, "initializing");
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002042 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002043}
Douglas Gregore60e5d32008-11-06 22:13:31 +00002044
2045/// CheckOverloadedOperatorDeclaration - Check whether the declaration
2046/// of this overloaded operator is well-formed. If so, returns false;
2047/// otherwise, emits appropriate diagnostics and returns true.
2048bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002049 assert(FnDecl && FnDecl->isOverloadedOperator() &&
Douglas Gregore60e5d32008-11-06 22:13:31 +00002050 "Expected an overloaded operator declaration");
2051
Douglas Gregore60e5d32008-11-06 22:13:31 +00002052 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
2053
2054 // C++ [over.oper]p5:
2055 // The allocation and deallocation functions, operator new,
2056 // operator new[], operator delete and operator delete[], are
2057 // described completely in 3.7.3. The attributes and restrictions
2058 // found in the rest of this subclause do not apply to them unless
2059 // explicitly stated in 3.7.3.
2060 // FIXME: Write a separate routine for checking this. For now, just
2061 // allow it.
2062 if (Op == OO_New || Op == OO_Array_New ||
2063 Op == OO_Delete || Op == OO_Array_Delete)
2064 return false;
2065
2066 // C++ [over.oper]p6:
2067 // An operator function shall either be a non-static member
2068 // function or be a non-member function and have at least one
2069 // parameter whose type is a class, a reference to a class, an
2070 // enumeration, or a reference to an enumeration.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002071 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
2072 if (MethodDecl->isStatic())
2073 return Diag(FnDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002074 diag::err_operator_overload_static) << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002075 } else {
2076 bool ClassOrEnumParam = false;
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002077 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
2078 ParamEnd = FnDecl->param_end();
2079 Param != ParamEnd; ++Param) {
2080 QualType ParamType = (*Param)->getType().getNonReferenceType();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002081 if (ParamType->isRecordType() || ParamType->isEnumeralType()) {
2082 ClassOrEnumParam = true;
2083 break;
2084 }
2085 }
2086
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002087 if (!ClassOrEnumParam)
2088 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002089 diag::err_operator_overload_needs_class_or_enum)
Chris Lattner271d4c22008-11-24 05:29:24 +00002090 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002091 }
2092
2093 // C++ [over.oper]p8:
2094 // An operator function cannot have default arguments (8.3.6),
2095 // except where explicitly stated below.
2096 //
2097 // Only the function-call operator allows default arguments
2098 // (C++ [over.call]p1).
2099 if (Op != OO_Call) {
2100 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
2101 Param != FnDecl->param_end(); ++Param) {
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002102 if ((*Param)->hasUnparsedDefaultArg())
2103 return Diag((*Param)->getLocation(),
2104 diag::err_operator_overload_default_arg)
2105 << FnDecl->getDeclName();
2106 else if (Expr *DefArg = (*Param)->getDefaultArg())
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002107 return Diag((*Param)->getLocation(),
Chris Lattner77d52da2008-11-20 06:06:08 +00002108 diag::err_operator_overload_default_arg)
Chris Lattner271d4c22008-11-24 05:29:24 +00002109 << FnDecl->getDeclName() << DefArg->getSourceRange();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002110 }
2111 }
2112
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002113 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
2114 { false, false, false }
2115#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
2116 , { Unary, Binary, MemberOnly }
2117#include "clang/Basic/OperatorKinds.def"
2118 };
Douglas Gregore60e5d32008-11-06 22:13:31 +00002119
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002120 bool CanBeUnaryOperator = OperatorUses[Op][0];
2121 bool CanBeBinaryOperator = OperatorUses[Op][1];
2122 bool MustBeMemberOperator = OperatorUses[Op][2];
Douglas Gregore60e5d32008-11-06 22:13:31 +00002123
2124 // C++ [over.oper]p8:
2125 // [...] Operator functions cannot have more or fewer parameters
2126 // than the number required for the corresponding operator, as
2127 // described in the rest of this subclause.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002128 unsigned NumParams = FnDecl->getNumParams()
2129 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002130 if (Op != OO_Call &&
2131 ((NumParams == 1 && !CanBeUnaryOperator) ||
2132 (NumParams == 2 && !CanBeBinaryOperator) ||
2133 (NumParams < 1) || (NumParams > 2))) {
2134 // We have the wrong number of parameters.
Chris Lattnerbb002332008-11-21 07:57:12 +00002135 unsigned ErrorKind;
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002136 if (CanBeUnaryOperator && CanBeBinaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002137 ErrorKind = 2; // 2 -> unary or binary.
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002138 } else if (CanBeUnaryOperator) {
Chris Lattnerbb002332008-11-21 07:57:12 +00002139 ErrorKind = 0; // 0 -> unary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002140 } else {
Chris Lattnera7021ee2008-11-21 07:50:02 +00002141 assert(CanBeBinaryOperator &&
2142 "All non-call overloaded operators are unary or binary!");
Chris Lattnerbb002332008-11-21 07:57:12 +00002143 ErrorKind = 1; // 1 -> binary
Douglas Gregor9c6210b2008-11-10 13:38:07 +00002144 }
Douglas Gregore60e5d32008-11-06 22:13:31 +00002145
Chris Lattnerbb002332008-11-21 07:57:12 +00002146 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
Chris Lattner271d4c22008-11-24 05:29:24 +00002147 << FnDecl->getDeclName() << NumParams << ErrorKind;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002148 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002149
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002150 // Overloaded operators other than operator() cannot be variadic.
2151 if (Op != OO_Call &&
Douglas Gregor4fa58902009-02-26 23:50:07 +00002152 FnDecl->getType()->getAsFunctionProtoType()->isVariadic()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002153 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
Chris Lattner271d4c22008-11-24 05:29:24 +00002154 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002155 }
2156
2157 // Some operators must be non-static member functions.
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002158 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
2159 return Diag(FnDecl->getLocation(),
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002160 diag::err_operator_overload_must_be_member)
Chris Lattner271d4c22008-11-24 05:29:24 +00002161 << FnDecl->getDeclName();
Douglas Gregore60e5d32008-11-06 22:13:31 +00002162 }
2163
2164 // C++ [over.inc]p1:
2165 // The user-defined function called operator++ implements the
2166 // prefix and postfix ++ operator. If this function is a member
2167 // function with no parameters, or a non-member function with one
2168 // parameter of class or enumeration type, it defines the prefix
2169 // increment operator ++ for objects of that type. If the function
2170 // is a member function with one parameter (which shall be of type
2171 // int) or a non-member function with two parameters (the second
2172 // of which shall be of type int), it defines the postfix
2173 // increment operator ++ for objects of that type.
2174 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
2175 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
2176 bool ParamIsInt = false;
2177 if (const BuiltinType *BT = LastParam->getType()->getAsBuiltinType())
2178 ParamIsInt = BT->getKind() == BuiltinType::Int;
2179
Chris Lattnera7021ee2008-11-21 07:50:02 +00002180 if (!ParamIsInt)
2181 return Diag(LastParam->getLocation(),
2182 diag::err_operator_overload_post_incdec_must_be_int)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002183 << LastParam->getType() << (Op == OO_MinusMinus);
Douglas Gregore60e5d32008-11-06 22:13:31 +00002184 }
2185
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00002186 // Notify the class if it got an assignment operator.
2187 if (Op == OO_Equal) {
2188 // Would have returned earlier otherwise.
2189 assert(isa<CXXMethodDecl>(FnDecl) &&
2190 "Overloaded = not member, but not filtered.");
2191 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
2192 Method->getParent()->addedAssignmentOperator(Context, Method);
2193 }
2194
Douglas Gregor682a8cf2008-11-17 16:14:12 +00002195 return false;
Douglas Gregore60e5d32008-11-06 22:13:31 +00002196}
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002197
Douglas Gregord8028382009-01-05 19:45:36 +00002198/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
2199/// linkage specification, including the language and (if present)
2200/// the '{'. ExternLoc is the location of the 'extern', LangLoc is
2201/// the location of the language string literal, which is provided
2202/// by Lang/StrSize. LBraceLoc, if valid, provides the location of
2203/// the '{' brace. Otherwise, this linkage specification does not
2204/// have any braces.
2205Sema::DeclTy *Sema::ActOnStartLinkageSpecification(Scope *S,
2206 SourceLocation ExternLoc,
2207 SourceLocation LangLoc,
2208 const char *Lang,
2209 unsigned StrSize,
2210 SourceLocation LBraceLoc) {
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002211 LinkageSpecDecl::LanguageIDs Language;
2212 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2213 Language = LinkageSpecDecl::lang_c;
2214 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2215 Language = LinkageSpecDecl::lang_cxx;
2216 else {
Douglas Gregord8028382009-01-05 19:45:36 +00002217 Diag(LangLoc, diag::err_bad_language);
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002218 return 0;
2219 }
2220
2221 // FIXME: Add all the various semantics of linkage specifications
2222
Douglas Gregord8028382009-01-05 19:45:36 +00002223 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
2224 LangLoc, Language,
2225 LBraceLoc.isValid());
Douglas Gregor03b2ad22009-01-12 23:27:07 +00002226 CurContext->addDecl(D);
Douglas Gregord8028382009-01-05 19:45:36 +00002227 PushDeclContext(S, D);
2228 return D;
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002229}
2230
Douglas Gregord8028382009-01-05 19:45:36 +00002231/// ActOnFinishLinkageSpecification - Completely the definition of
2232/// the C++ linkage specification LinkageSpec. If RBraceLoc is
2233/// valid, it's the position of the closing '}' brace in a linkage
2234/// specification that uses braces.
2235Sema::DeclTy *Sema::ActOnFinishLinkageSpecification(Scope *S,
2236 DeclTy *LinkageSpec,
2237 SourceLocation RBraceLoc) {
2238 if (LinkageSpec)
2239 PopDeclContext();
2240 return LinkageSpec;
Chris Lattnerf58d52b2008-12-17 07:09:26 +00002241}
2242
Sebastian Redl743c8162008-12-22 19:15:10 +00002243/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
2244/// handler.
2245Sema::DeclTy *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D)
2246{
2247 QualType ExDeclType = GetTypeForDeclarator(D, S);
2248 SourceLocation Begin = D.getDeclSpec().getSourceRange().getBegin();
2249
2250 bool Invalid = false;
2251
2252 // Arrays and functions decay.
2253 if (ExDeclType->isArrayType())
2254 ExDeclType = Context.getArrayDecayedType(ExDeclType);
2255 else if (ExDeclType->isFunctionType())
2256 ExDeclType = Context.getPointerType(ExDeclType);
2257
2258 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
2259 // The exception-declaration shall not denote a pointer or reference to an
2260 // incomplete type, other than [cv] void*.
2261 QualType BaseType = ExDeclType;
2262 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002263 unsigned DK = diag::err_catch_incomplete;
Sebastian Redl743c8162008-12-22 19:15:10 +00002264 if (const PointerType *Ptr = BaseType->getAsPointerType()) {
2265 BaseType = Ptr->getPointeeType();
2266 Mode = 1;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002267 DK = diag::err_catch_incomplete_ptr;
Sebastian Redl743c8162008-12-22 19:15:10 +00002268 } else if(const ReferenceType *Ref = BaseType->getAsReferenceType()) {
2269 BaseType = Ref->getPointeeType();
2270 Mode = 2;
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002271 DK = diag::err_catch_incomplete_ref;
Sebastian Redl743c8162008-12-22 19:15:10 +00002272 }
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002273 if ((Mode == 0 || !BaseType->isVoidType()) &&
Douglas Gregorc84d8932009-03-09 16:13:40 +00002274 RequireCompleteType(Begin, BaseType, DK))
Sebastian Redl743c8162008-12-22 19:15:10 +00002275 Invalid = true;
Sebastian Redl743c8162008-12-22 19:15:10 +00002276
Sebastian Redl237116b2008-12-22 21:35:02 +00002277 // FIXME: Need to test for ability to copy-construct and destroy the
2278 // exception variable.
2279 // FIXME: Need to check for abstract classes.
2280
Sebastian Redl743c8162008-12-22 19:15:10 +00002281 IdentifierInfo *II = D.getIdentifier();
Douglas Gregor09be81b2009-02-04 17:27:36 +00002282 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Sebastian Redl743c8162008-12-22 19:15:10 +00002283 // The scope should be freshly made just for us. There is just no way
2284 // it contains any previous declaration.
2285 assert(!S->isDeclScope(PrevDecl));
2286 if (PrevDecl->isTemplateParameter()) {
2287 // Maybe we will complain about the shadowed template parameter.
2288 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2289
2290 }
2291 }
2292
2293 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +00002294 II, ExDeclType, VarDecl::None, Begin);
Sebastian Redl743c8162008-12-22 19:15:10 +00002295 if (D.getInvalidType() || Invalid)
2296 ExDecl->setInvalidDecl();
2297
2298 if (D.getCXXScopeSpec().isSet()) {
2299 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
2300 << D.getCXXScopeSpec().getRange();
2301 ExDecl->setInvalidDecl();
2302 }
2303
2304 // Add the exception declaration into this scope.
2305 S->AddDecl(ExDecl);
2306 if (II)
2307 IdResolver.AddDecl(ExDecl);
2308
2309 ProcessDeclAttributes(ExDecl, D);
2310 return ExDecl;
2311}