blob: 4a2f0b43f63db6d37a7035bb664f34292015850f [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"
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +000015#include "clang/AST/ASTConsumer.h"
Douglas Gregorec93f442008-04-13 21:30:24 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor05904022008-10-22 21:13:31 +000017#include "clang/AST/TypeOrdering.h"
Chris Lattner97316c02008-04-10 02:22:51 +000018#include "clang/AST/StmtVisitor.h"
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +000019#include "clang/Lex/Preprocessor.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000020#include "clang/Basic/Diagnostic.h"
Daniel Dunbar8d03cbe2008-08-11 03:27:53 +000021#include "clang/Parse/DeclSpec.h"
Chris Lattner97316c02008-04-10 02:22:51 +000022#include "llvm/Support/Compiler.h"
Douglas Gregord2baafd2008-10-21 16:13:35 +000023#include <algorithm> // for std::equal
Douglas Gregorabed2172008-10-22 17:49:05 +000024#include <map>
Chris Lattnerac7b83a2008-04-08 05:04:30 +000025
26using namespace clang;
27
Chris Lattner97316c02008-04-10 02:22:51 +000028//===----------------------------------------------------------------------===//
29// CheckDefaultArgumentVisitor
30//===----------------------------------------------------------------------===//
31
Chris Lattnerb1856db2008-04-12 23:52:44 +000032namespace {
33 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
34 /// the default argument of a parameter to determine whether it
35 /// contains any ill-formed subexpressions. For example, this will
36 /// diagnose the use of local variables or parameters within the
37 /// default argument expression.
38 class VISIBILITY_HIDDEN CheckDefaultArgumentVisitor
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000039 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
Chris Lattnerb1856db2008-04-12 23:52:44 +000040 Expr *DefaultArg;
41 Sema *S;
Chris Lattner97316c02008-04-10 02:22:51 +000042
Chris Lattnerb1856db2008-04-12 23:52:44 +000043 public:
44 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
45 : DefaultArg(defarg), S(s) {}
Chris Lattner97316c02008-04-10 02:22:51 +000046
Chris Lattnerb1856db2008-04-12 23:52:44 +000047 bool VisitExpr(Expr *Node);
48 bool VisitDeclRefExpr(DeclRefExpr *DRE);
49 };
Chris Lattner97316c02008-04-10 02:22:51 +000050
Chris Lattnerb1856db2008-04-12 23:52:44 +000051 /// VisitExpr - Visit all of the children of this expression.
52 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
53 bool IsInvalid = false;
Chris Lattnerd5a56aa2008-07-26 22:17:49 +000054 for (Stmt::child_iterator I = Node->child_begin(),
55 E = Node->child_end(); I != E; ++I)
56 IsInvalid |= Visit(*I);
Chris Lattnerb1856db2008-04-12 23:52:44 +000057 return IsInvalid;
Chris Lattner97316c02008-04-10 02:22:51 +000058 }
59
Chris Lattnerb1856db2008-04-12 23:52:44 +000060 /// VisitDeclRefExpr - Visit a reference to a declaration, to
61 /// determine whether this declaration can be used in the default
62 /// argument expression.
63 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
Douglas Gregord2baafd2008-10-21 16:13:35 +000064 NamedDecl *Decl = DRE->getDecl();
Chris Lattnerb1856db2008-04-12 23:52:44 +000065 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
66 // C++ [dcl.fct.default]p9
67 // Default arguments are evaluated each time the function is
68 // called. The order of evaluation of function arguments is
69 // unspecified. Consequently, parameters of a function shall not
70 // be used in default argument expressions, even if they are not
71 // evaluated. Parameters of a function declared before a default
72 // argument expression are in scope and can hide namespace and
73 // class member names.
74 return S->Diag(DRE->getSourceRange().getBegin(),
75 diag::err_param_default_argument_references_param,
76 Param->getName(), DefaultArg->getSourceRange());
Steve Naroff72a6ebc2008-04-15 22:42:06 +000077 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
Chris Lattnerb1856db2008-04-12 23:52:44 +000078 // C++ [dcl.fct.default]p7
79 // Local variables shall not be used in default argument
80 // expressions.
Steve Naroff72a6ebc2008-04-15 22:42:06 +000081 if (VDecl->isBlockVarDecl())
82 return S->Diag(DRE->getSourceRange().getBegin(),
83 diag::err_param_default_argument_references_local,
84 VDecl->getName(), DefaultArg->getSourceRange());
Chris Lattnerb1856db2008-04-12 23:52:44 +000085 }
Chris Lattner97316c02008-04-10 02:22:51 +000086
Douglas Gregor3becfd82008-11-03 22:47:57 +000087 // C++ [dcl.fct.default]p8:
88 // The keyword this shall not be used in a default argument of a
89 // member function.
90 // Note: this requirement is already diagnosed by
91 // Sema::ActOnCXXThis, because the use of "this" inside a default
92 // argument doesn't occur inside the body of a non-static member
93 // function.
Chris Lattnerb1856db2008-04-12 23:52:44 +000094
95 return false;
96 }
Chris Lattner97316c02008-04-10 02:22:51 +000097}
98
99/// ActOnParamDefaultArgument - Check whether the default argument
100/// provided for a function parameter is well-formed. If so, attach it
101/// to the parameter declaration.
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000102void
103Sema::ActOnParamDefaultArgument(DeclTy *param, SourceLocation EqualLoc,
104 ExprTy *defarg) {
105 ParmVarDecl *Param = (ParmVarDecl *)param;
106 llvm::OwningPtr<Expr> DefaultArg((Expr *)defarg);
107 QualType ParamType = Param->getType();
108
109 // Default arguments are only permitted in C++
110 if (!getLangOptions().CPlusPlus) {
111 Diag(EqualLoc, diag::err_param_default_argument,
112 DefaultArg->getSourceRange());
113 return;
114 }
115
116 // C++ [dcl.fct.default]p5
117 // A default argument expression is implicitly converted (clause
118 // 4) to the parameter type. The default argument expression has
119 // the same semantic constraints as the initializer expression in
120 // a declaration of a variable of the parameter type, using the
121 // copy-initialization semantics (8.5).
122 //
123 // FIXME: CheckSingleAssignmentConstraints has the wrong semantics
124 // for C++ (since we want copy-initialization, not copy-assignment),
125 // but we don't have the right semantics implemented yet. Because of
126 // this, our error message is also very poor.
127 QualType DefaultArgType = DefaultArg->getType();
128 Expr *DefaultArgPtr = DefaultArg.get();
129 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(ParamType,
130 DefaultArgPtr);
131 if (DefaultArgPtr != DefaultArg.get()) {
132 DefaultArg.take();
133 DefaultArg.reset(DefaultArgPtr);
134 }
135 if (DiagnoseAssignmentResult(ConvTy, DefaultArg->getLocStart(),
136 ParamType, DefaultArgType, DefaultArg.get(),
137 "in default argument")) {
138 return;
139 }
140
Chris Lattner97316c02008-04-10 02:22:51 +0000141 // Check that the default argument is well-formed
Chris Lattnerb1856db2008-04-12 23:52:44 +0000142 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg.get(), this);
Chris Lattner97316c02008-04-10 02:22:51 +0000143 if (DefaultArgChecker.Visit(DefaultArg.get()))
144 return;
145
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000146 // Okay: add the default argument to the parameter
147 Param->setDefaultArg(DefaultArg.take());
148}
149
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000150/// CheckExtraCXXDefaultArguments - Check for any extra default
151/// arguments in the declarator, which is not a function declaration
152/// or definition and therefore is not permitted to have default
153/// arguments. This routine should be invoked for every declarator
154/// that is not a function declaration or definition.
155void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
156 // C++ [dcl.fct.default]p3
157 // A default argument expression shall be specified only in the
158 // parameter-declaration-clause of a function declaration or in a
159 // template-parameter (14.1). It shall not be specified for a
160 // parameter pack. If it is specified in a
161 // parameter-declaration-clause, it shall not occur within a
162 // declarator or abstract-declarator of a parameter-declaration.
163 for (unsigned i = 0; i < D.getNumTypeObjects(); ++i) {
164 DeclaratorChunk &chunk = D.getTypeObject(i);
165 if (chunk.Kind == DeclaratorChunk::Function) {
166 for (unsigned argIdx = 0; argIdx < chunk.Fun.NumArgs; ++argIdx) {
167 ParmVarDecl *Param = (ParmVarDecl *)chunk.Fun.ArgInfo[argIdx].Param;
168 if (Param->getDefaultArg()) {
169 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc,
170 Param->getDefaultArg()->getSourceRange());
171 Param->setDefaultArg(0);
172 }
173 }
174 }
175 }
176}
177
Chris Lattnerac7b83a2008-04-08 05:04:30 +0000178// MergeCXXFunctionDecl - Merge two declarations of the same C++
179// function, once we already know that they have the same
180// type. Subroutine of MergeFunctionDecl.
181FunctionDecl *
182Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
183 // C++ [dcl.fct.default]p4:
184 //
185 // For non-template functions, default arguments can be added in
186 // later declarations of a function in the same
187 // scope. Declarations in different scopes have completely
188 // distinct sets of default arguments. That is, declarations in
189 // inner scopes do not acquire default arguments from
190 // declarations in outer scopes, and vice versa. In a given
191 // function declaration, all parameters subsequent to a
192 // parameter with a default argument shall have default
193 // arguments supplied in this or previous declarations. A
194 // default argument shall not be redefined by a later
195 // declaration (not even to the same value).
196 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
197 ParmVarDecl *OldParam = Old->getParamDecl(p);
198 ParmVarDecl *NewParam = New->getParamDecl(p);
199
200 if(OldParam->getDefaultArg() && NewParam->getDefaultArg()) {
201 Diag(NewParam->getLocation(),
202 diag::err_param_default_argument_redefinition,
203 NewParam->getDefaultArg()->getSourceRange());
204 Diag(OldParam->getLocation(), diag::err_previous_definition);
205 } else if (OldParam->getDefaultArg()) {
206 // Merge the old default argument into the new parameter
207 NewParam->setDefaultArg(OldParam->getDefaultArg());
208 }
209 }
210
211 return New;
212}
213
214/// CheckCXXDefaultArguments - Verify that the default arguments for a
215/// function declaration are well-formed according to C++
216/// [dcl.fct.default].
217void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
218 unsigned NumParams = FD->getNumParams();
219 unsigned p;
220
221 // Find first parameter with a default argument
222 for (p = 0; p < NumParams; ++p) {
223 ParmVarDecl *Param = FD->getParamDecl(p);
224 if (Param->getDefaultArg())
225 break;
226 }
227
228 // C++ [dcl.fct.default]p4:
229 // In a given function declaration, all parameters
230 // subsequent to a parameter with a default argument shall
231 // have default arguments supplied in this or previous
232 // declarations. A default argument shall not be redefined
233 // by a later declaration (not even to the same value).
234 unsigned LastMissingDefaultArg = 0;
235 for(; p < NumParams; ++p) {
236 ParmVarDecl *Param = FD->getParamDecl(p);
237 if (!Param->getDefaultArg()) {
238 if (Param->getIdentifier())
239 Diag(Param->getLocation(),
240 diag::err_param_default_argument_missing_name,
241 Param->getIdentifier()->getName());
242 else
243 Diag(Param->getLocation(),
244 diag::err_param_default_argument_missing);
245
246 LastMissingDefaultArg = p;
247 }
248 }
249
250 if (LastMissingDefaultArg > 0) {
251 // Some default arguments were missing. Clear out all of the
252 // default arguments up to (and including) the last missing
253 // default argument, so that we leave the function parameters
254 // in a semantically valid state.
255 for (p = 0; p <= LastMissingDefaultArg; ++p) {
256 ParmVarDecl *Param = FD->getParamDecl(p);
257 if (Param->getDefaultArg()) {
258 delete Param->getDefaultArg();
259 Param->setDefaultArg(0);
260 }
261 }
262 }
263}
Douglas Gregorec93f442008-04-13 21:30:24 +0000264
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000265/// isCurrentClassName - Determine whether the identifier II is the
266/// name of the class type currently being defined. In the case of
267/// nested classes, this will only return true if II is the name of
268/// the innermost class.
269bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *) {
270 if (CXXRecordDecl *CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext))
271 return &II == CurDecl->getIdentifier();
272 else
273 return false;
274}
275
Douglas Gregorec93f442008-04-13 21:30:24 +0000276/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
277/// one entry in the base class list of a class specifier, for
278/// example:
279/// class foo : public bar, virtual private baz {
280/// 'public bar' and 'virtual private baz' are each base-specifiers.
Douglas Gregorabed2172008-10-22 17:49:05 +0000281Sema::BaseResult
282Sema::ActOnBaseSpecifier(DeclTy *classdecl, SourceRange SpecifierRange,
283 bool Virtual, AccessSpecifier Access,
284 TypeTy *basetype, SourceLocation BaseLoc) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000285 RecordDecl *Decl = (RecordDecl*)classdecl;
286 QualType BaseType = Context.getTypeDeclType((TypeDecl*)basetype);
287
288 // Base specifiers must be record types.
289 if (!BaseType->isRecordType()) {
290 Diag(BaseLoc, diag::err_base_must_be_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000291 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000292 }
293
294 // C++ [class.union]p1:
295 // A union shall not be used as a base class.
296 if (BaseType->isUnionType()) {
297 Diag(BaseLoc, diag::err_union_as_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000298 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000299 }
300
301 // C++ [class.union]p1:
302 // A union shall not have base classes.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +0000303 if (Decl->isUnion()) {
Douglas Gregorec93f442008-04-13 21:30:24 +0000304 Diag(Decl->getLocation(), diag::err_base_clause_on_union,
305 SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000306 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000307 }
308
309 // C++ [class.derived]p2:
310 // The class-name in a base-specifier shall not be an incompletely
311 // defined class.
312 if (BaseType->isIncompleteType()) {
313 Diag(BaseLoc, diag::err_incomplete_base_class, SpecifierRange);
Douglas Gregorabed2172008-10-22 17:49:05 +0000314 return true;
Douglas Gregorec93f442008-04-13 21:30:24 +0000315 }
316
Douglas Gregorabed2172008-10-22 17:49:05 +0000317 // Create the base specifier.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000318 return new CXXBaseSpecifier(SpecifierRange, Virtual,
319 BaseType->isClassType(), Access, BaseType);
Douglas Gregorabed2172008-10-22 17:49:05 +0000320}
Douglas Gregorec93f442008-04-13 21:30:24 +0000321
Douglas Gregorabed2172008-10-22 17:49:05 +0000322/// ActOnBaseSpecifiers - Attach the given base specifiers to the
323/// class, after checking whether there are any duplicate base
324/// classes.
325void Sema::ActOnBaseSpecifiers(DeclTy *ClassDecl, BaseTy **Bases,
326 unsigned NumBases) {
327 if (NumBases == 0)
328 return;
329
330 // Used to keep track of which base types we have already seen, so
331 // that we can properly diagnose redundant direct base types. Note
Douglas Gregor4fd85902008-10-23 18:13:27 +0000332 // that the key is always the unqualified canonical type of the base
333 // class.
Douglas Gregorabed2172008-10-22 17:49:05 +0000334 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
335
336 // Copy non-redundant base specifiers into permanent storage.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000337 CXXBaseSpecifier **BaseSpecs = (CXXBaseSpecifier **)Bases;
338 unsigned NumGoodBases = 0;
339 for (unsigned idx = 0; idx < NumBases; ++idx) {
Douglas Gregorabed2172008-10-22 17:49:05 +0000340 QualType NewBaseType
Douglas Gregor4fd85902008-10-23 18:13:27 +0000341 = Context.getCanonicalType(BaseSpecs[idx]->getType());
342 NewBaseType = NewBaseType.getUnqualifiedType();
343
Douglas Gregorabed2172008-10-22 17:49:05 +0000344 if (KnownBaseTypes[NewBaseType]) {
345 // C++ [class.mi]p3:
346 // A class shall not be specified as a direct base class of a
347 // derived class more than once.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000348 Diag(BaseSpecs[idx]->getSourceRange().getBegin(),
Douglas Gregorabed2172008-10-22 17:49:05 +0000349 diag::err_duplicate_base_class,
350 KnownBaseTypes[NewBaseType]->getType().getAsString(),
Douglas Gregor4fd85902008-10-23 18:13:27 +0000351 BaseSpecs[idx]->getSourceRange());
352
353 // Delete the duplicate base class specifier; we're going to
354 // overwrite its pointer later.
355 delete BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000356 } else {
357 // Okay, add this new base class.
Douglas Gregor4fd85902008-10-23 18:13:27 +0000358 KnownBaseTypes[NewBaseType] = BaseSpecs[idx];
359 BaseSpecs[NumGoodBases++] = BaseSpecs[idx];
Douglas Gregorabed2172008-10-22 17:49:05 +0000360 }
361 }
362
363 // Attach the remaining base class specifiers to the derived class.
364 CXXRecordDecl *Decl = (CXXRecordDecl*)ClassDecl;
Douglas Gregor4fd85902008-10-23 18:13:27 +0000365 Decl->setBases(BaseSpecs, NumGoodBases);
366
367 // Delete the remaining (good) base class specifiers, since their
368 // data has been copied into the CXXRecordDecl.
369 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
370 delete BaseSpecs[idx];
Douglas Gregorec93f442008-04-13 21:30:24 +0000371}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000372
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000373//===----------------------------------------------------------------------===//
374// C++ class member Handling
375//===----------------------------------------------------------------------===//
376
377/// ActOnStartCXXClassDef - This is called at the start of a class/struct/union
378/// definition, when on C++.
379void Sema::ActOnStartCXXClassDef(Scope *S, DeclTy *D, SourceLocation LBrace) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000380 CXXRecordDecl *Dcl = cast<CXXRecordDecl>(static_cast<Decl *>(D));
381 PushDeclContext(Dcl);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000382 FieldCollector->StartClass();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000383
384 if (Dcl->getIdentifier()) {
385 // C++ [class]p2:
386 // [...] The class-name is also inserted into the scope of the
387 // class itself; this is known as the injected-class-name. For
388 // purposes of access checking, the injected-class-name is treated
389 // as if it were a public member name.
390 TypedefDecl *InjectedClassName
391 = TypedefDecl::Create(Context, Dcl, LBrace, Dcl->getIdentifier(),
392 Context.getTypeDeclType(Dcl), /*PrevDecl=*/0);
393 PushOnScopeChains(InjectedClassName, S);
394 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000395}
396
397/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
398/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
399/// bitfield width if there is one and 'InitExpr' specifies the initializer if
400/// any. 'LastInGroup' is non-null for cases where one declspec has multiple
401/// declarators on it.
402///
403/// NOTE: Because of CXXFieldDecl's inability to be chained like ScopedDecls, if
404/// an instance field is declared, a new CXXFieldDecl is created but the method
405/// does *not* return it; it returns LastInGroup instead. The other C++ members
406/// (which are all ScopedDecls) are returned after appending them to
407/// LastInGroup.
408Sema::DeclTy *
409Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
410 ExprTy *BW, ExprTy *InitExpr,
411 DeclTy *LastInGroup) {
412 const DeclSpec &DS = D.getDeclSpec();
413 IdentifierInfo *II = D.getIdentifier();
414 Expr *BitWidth = static_cast<Expr*>(BW);
415 Expr *Init = static_cast<Expr*>(InitExpr);
416 SourceLocation Loc = D.getIdentifierLoc();
417
418 // C++ 9.2p6: A member shall not be declared to have automatic storage
419 // duration (auto, register) or with the extern storage-class-specifier.
420 switch (DS.getStorageClassSpec()) {
421 case DeclSpec::SCS_unspecified:
422 case DeclSpec::SCS_typedef:
423 case DeclSpec::SCS_static:
424 // FALL THROUGH.
425 break;
426 default:
427 if (DS.getStorageClassSpecLoc().isValid())
428 Diag(DS.getStorageClassSpecLoc(),
429 diag::err_storageclass_invalid_for_member);
430 else
431 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
432 D.getMutableDeclSpec().ClearStorageClassSpecs();
433 }
434
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000435 bool isFunc = D.isFunctionDeclarator();
Argiris Kirtzidise2900c62008-10-15 20:23:22 +0000436 if (!isFunc &&
437 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typedef &&
438 D.getNumTypeObjects() == 0) {
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000439 // Check also for this case:
440 //
441 // typedef int f();
442 // f a;
443 //
444 Decl *TD = static_cast<Decl *>(DS.getTypeRep());
445 isFunc = Context.getTypeDeclType(cast<TypeDecl>(TD))->isFunctionType();
446 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000447
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000448 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified &&
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000449 !isFunc);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000450
451 Decl *Member;
452 bool InvalidDecl = false;
453
454 if (isInstField)
455 Member = static_cast<Decl*>(ActOnField(S, Loc, D, BitWidth));
456 else
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000457 Member = static_cast<Decl*>(ActOnDeclarator(S, D, LastInGroup));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000458
459 if (!Member) return LastInGroup;
460
Sanjiv Guptafa451432008-10-31 09:52:39 +0000461 assert((II || isInstField) && "No identifier for non-field ?");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000462
463 // set/getAccess is not part of Decl's interface to avoid bloating it with C++
464 // specific methods. Use a wrapper class that can be used with all C++ class
465 // member decls.
466 CXXClassMemberWrapper(Member).setAccess(AS);
467
468 if (BitWidth) {
469 // C++ 9.6p2: Only when declaring an unnamed bit-field may the
470 // constant-expression be a value equal to zero.
471 // FIXME: Check this.
472
473 if (D.isFunctionDeclarator()) {
474 // FIXME: Emit diagnostic about only constructors taking base initializers
475 // or something similar, when constructor support is in place.
476 Diag(Loc, diag::err_not_bitfield_type,
477 II->getName(), BitWidth->getSourceRange());
478 InvalidDecl = true;
479
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000480 } else if (isInstField) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000481 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000482 if (!cast<FieldDecl>(Member)->getType()->isIntegralType()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000483 Diag(Loc, diag::err_not_integral_type_bitfield,
484 II->getName(), BitWidth->getSourceRange());
485 InvalidDecl = true;
486 }
487
Argiris Kirtzidis1f0d4c22008-10-08 22:20:31 +0000488 } else if (isa<FunctionDecl>(Member)) {
489 // A function typedef ("typedef int f(); f a;").
490 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
491 Diag(Loc, diag::err_not_integral_type_bitfield,
492 II->getName(), BitWidth->getSourceRange());
493 InvalidDecl = true;
494
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000495 } else if (isa<TypedefDecl>(Member)) {
496 // "cannot declare 'A' to be a bit-field type"
497 Diag(Loc, diag::err_not_bitfield_type, II->getName(),
498 BitWidth->getSourceRange());
499 InvalidDecl = true;
500
501 } else {
502 assert(isa<CXXClassVarDecl>(Member) &&
503 "Didn't we cover all member kinds?");
504 // C++ 9.6p3: A bit-field shall not be a static member.
505 // "static member 'A' cannot be a bit-field"
506 Diag(Loc, diag::err_static_not_bitfield, II->getName(),
507 BitWidth->getSourceRange());
508 InvalidDecl = true;
509 }
510 }
511
512 if (Init) {
513 // C++ 9.2p4: A member-declarator can contain a constant-initializer only
514 // if it declares a static member of const integral or const enumeration
515 // type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000516 if (CXXClassVarDecl *CVD = dyn_cast<CXXClassVarDecl>(Member)) {
517 // ...static member of...
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000518 CVD->setInit(Init);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000519 // ...const integral or const enumeration type.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000520 if (Context.getCanonicalType(CVD->getType()).isConstQualified() &&
521 CVD->getType()->isIntegralType()) {
522 // constant-initializer
523 if (CheckForConstantInitializer(Init, CVD->getType()))
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000524 InvalidDecl = true;
525
526 } else {
527 // not const integral.
528 Diag(Loc, diag::err_member_initialization,
529 II->getName(), Init->getSourceRange());
530 InvalidDecl = true;
531 }
532
533 } else {
534 // not static member.
535 Diag(Loc, diag::err_member_initialization,
536 II->getName(), Init->getSourceRange());
537 InvalidDecl = true;
538 }
539 }
540
541 if (InvalidDecl)
542 Member->setInvalidDecl();
543
544 if (isInstField) {
545 FieldCollector->Add(cast<CXXFieldDecl>(Member));
546 return LastInGroup;
547 }
548 return Member;
549}
550
551void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
552 DeclTy *TagDecl,
553 SourceLocation LBrac,
554 SourceLocation RBrac) {
555 ActOnFields(S, RLoc, TagDecl,
556 (DeclTy**)FieldCollector->getCurFields(),
Daniel Dunbarf3944442008-10-03 02:03:53 +0000557 FieldCollector->getCurNumFields(), LBrac, RBrac, 0);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000558}
559
Douglas Gregore640ab62008-11-03 17:51:48 +0000560/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
561/// special functions, such as the default constructor, copy
562/// constructor, or destructor, to the given C++ class (C++
563/// [special]p1). This routine can only be executed just before the
564/// definition of the class is complete.
565void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
566 if (!ClassDecl->hasUserDeclaredConstructor()) {
567 // C++ [class.ctor]p5:
568 // A default constructor for a class X is a constructor of class X
569 // that can be called without an argument. If there is no
570 // user-declared constructor for class X, a default constructor is
571 // implicitly declared. An implicitly-declared default constructor
572 // is an inline public member of its class.
573 CXXConstructorDecl *DefaultCon =
574 CXXConstructorDecl::Create(Context, ClassDecl,
575 ClassDecl->getLocation(),
576 ClassDecl->getIdentifier(),
577 Context.getFunctionType(Context.VoidTy,
578 0, 0, false, 0),
579 /*isExplicit=*/false,
580 /*isInline=*/true,
581 /*isImplicitlyDeclared=*/true);
582 DefaultCon->setAccess(AS_public);
583 ClassDecl->addConstructor(Context, DefaultCon);
584 }
585
586 if (!ClassDecl->hasUserDeclaredCopyConstructor()) {
587 // C++ [class.copy]p4:
588 // If the class definition does not explicitly declare a copy
589 // constructor, one is declared implicitly.
590
591 // C++ [class.copy]p5:
592 // The implicitly-declared copy constructor for a class X will
593 // have the form
594 //
595 // X::X(const X&)
596 //
597 // if
598 bool HasConstCopyConstructor = true;
599
600 // -- each direct or virtual base class B of X has a copy
601 // constructor whose first parameter is of type const B& or
602 // const volatile B&, and
603 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
604 HasConstCopyConstructor && Base != ClassDecl->bases_end(); ++Base) {
605 const CXXRecordDecl *BaseClassDecl
606 = cast<CXXRecordDecl>(Base->getType()->getAsRecordType()->getDecl());
607 HasConstCopyConstructor
608 = BaseClassDecl->hasConstCopyConstructor(Context);
609 }
610
611 // -- for all the nonstatic data members of X that are of a
612 // class type M (or array thereof), each such class type
613 // has a copy constructor whose first parameter is of type
614 // const M& or const volatile M&.
615 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin();
616 HasConstCopyConstructor && Field != ClassDecl->field_end(); ++Field) {
617 QualType FieldType = (*Field)->getType();
618 if (const ArrayType *Array = Context.getAsArrayType(FieldType))
619 FieldType = Array->getElementType();
620 if (const RecordType *FieldClassType = FieldType->getAsRecordType()) {
621 const CXXRecordDecl *FieldClassDecl
622 = cast<CXXRecordDecl>(FieldClassType->getDecl());
623 HasConstCopyConstructor
624 = FieldClassDecl->hasConstCopyConstructor(Context);
625 }
626 }
627
628 // Otherwise, the implicitly declared copy constructor will have
629 // the form
630 //
631 // X::X(X&)
632 QualType ArgType = Context.getTypeDeclType(ClassDecl);
633 if (HasConstCopyConstructor)
634 ArgType = ArgType.withConst();
635 ArgType = Context.getReferenceType(ArgType);
636
637 // An implicitly-declared copy constructor is an inline public
638 // member of its class.
639 CXXConstructorDecl *CopyConstructor
640 = CXXConstructorDecl::Create(Context, ClassDecl,
641 ClassDecl->getLocation(),
642 ClassDecl->getIdentifier(),
643 Context.getFunctionType(Context.VoidTy,
644 &ArgType, 1,
645 false, 0),
646 /*isExplicit=*/false,
647 /*isInline=*/true,
648 /*isImplicitlyDeclared=*/true);
649 CopyConstructor->setAccess(AS_public);
650
651 // Add the parameter to the constructor.
652 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
653 ClassDecl->getLocation(),
654 /*IdentifierInfo=*/0,
655 ArgType, VarDecl::None, 0, 0);
656 CopyConstructor->setParams(&FromParam, 1);
657
658 ClassDecl->addConstructor(Context, CopyConstructor);
659 }
660
661 // FIXME: Implicit destructor
662 // FIXME: Implicit copy assignment operator
663}
664
Argiris Kirtzidis448b4e42008-08-09 00:39:29 +0000665void Sema::ActOnFinishCXXClassDef(DeclTy *D) {
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000666 CXXRecordDecl *Rec = cast<CXXRecordDecl>(static_cast<Decl *>(D));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000667 FieldCollector->FinishClass();
Douglas Gregore640ab62008-11-03 17:51:48 +0000668 AddImplicitlyDeclaredMembersToClass(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000669 PopDeclContext();
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +0000670
671 // Everything, including inline method definitions, have been parsed.
672 // Let the consumer know of the new TagDecl definition.
673 Consumer.HandleTagDeclDefinition(Rec);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000674}
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000675
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000676/// ActOnConstructorDeclarator - Called by ActOnDeclarator to complete
677/// the declaration of the given C++ constructor ConDecl that was
678/// built from declarator D. This routine is responsible for checking
679/// that the newly-created constructor declaration is well-formed and
680/// for recording it in the C++ class. Example:
681///
682/// @code
683/// class X {
684/// X(); // X::X() will be the ConDecl.
685/// };
686/// @endcode
687Sema::DeclTy *Sema::ActOnConstructorDeclarator(CXXConstructorDecl *ConDecl) {
688 assert(ConDecl && "Expected to receive a constructor declaration");
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000689
690 // Check default arguments on the constructor
691 CheckCXXDefaultArguments(ConDecl);
692
Douglas Gregorccabf082008-10-31 20:25:05 +0000693 CXXRecordDecl *ClassDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
694 if (!ClassDecl) {
695 ConDecl->setInvalidDecl();
696 return ConDecl;
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000697 }
698
Douglas Gregorccabf082008-10-31 20:25:05 +0000699 // Make sure this constructor is an overload of the existing
700 // constructors.
701 OverloadedFunctionDecl::function_iterator MatchedDecl;
702 if (!IsOverload(ConDecl, ClassDecl->getConstructors(), MatchedDecl)) {
703 Diag(ConDecl->getLocation(),
704 diag::err_constructor_redeclared,
705 SourceRange(ConDecl->getLocation()));
706 Diag((*MatchedDecl)->getLocation(),
707 diag::err_previous_declaration,
708 SourceRange((*MatchedDecl)->getLocation()));
709 ConDecl->setInvalidDecl();
710 return ConDecl;
711 }
712
713
714 // C++ [class.copy]p3:
715 // A declaration of a constructor for a class X is ill-formed if
716 // its first parameter is of type (optionally cv-qualified) X and
717 // either there are no other parameters or else all other
718 // parameters have default arguments.
719 if ((ConDecl->getNumParams() == 1) ||
720 (ConDecl->getNumParams() > 1 &&
721 ConDecl->getParamDecl(1)->getDefaultArg() != 0)) {
722 QualType ParamType = ConDecl->getParamDecl(0)->getType();
723 QualType ClassTy = Context.getTagDeclType(
724 const_cast<CXXRecordDecl*>(ConDecl->getParent()));
725 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
726 Diag(ConDecl->getLocation(),
727 diag::err_constructor_byvalue_arg,
728 SourceRange(ConDecl->getParamDecl(0)->getLocation()));
729 ConDecl->setInvalidDecl();
730 return 0;
731 }
732 }
733
734 // Add this constructor to the set of constructors of the current
735 // class.
736 ClassDecl->addConstructor(Context, ConDecl);
Douglas Gregorb72e9da2008-10-31 16:23:19 +0000737
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000738 return (DeclTy *)ConDecl;
739}
740
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000741//===----------------------------------------------------------------------===//
742// Namespace Handling
743//===----------------------------------------------------------------------===//
744
745/// ActOnStartNamespaceDef - This is called at the start of a namespace
746/// definition.
747Sema::DeclTy *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
748 SourceLocation IdentLoc,
749 IdentifierInfo *II,
750 SourceLocation LBrace) {
751 NamespaceDecl *Namespc =
752 NamespaceDecl::Create(Context, CurContext, IdentLoc, II);
753 Namespc->setLBracLoc(LBrace);
754
755 Scope *DeclRegionScope = NamespcScope->getParent();
756
757 if (II) {
758 // C++ [namespace.def]p2:
759 // The identifier in an original-namespace-definition shall not have been
760 // previously defined in the declarative region in which the
761 // original-namespace-definition appears. The identifier in an
762 // original-namespace-definition is the name of the namespace. Subsequently
763 // in that declarative region, it is treated as an original-namespace-name.
764
765 Decl *PrevDecl =
Argiris Kirtzidisda64ff42008-10-14 18:28:48 +0000766 LookupDecl(II, Decl::IDNS_Tag | Decl::IDNS_Ordinary, DeclRegionScope,
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000767 /*enableLazyBuiltinCreation=*/false);
768
Argiris Kirtzidisad9de132008-09-10 02:11:07 +0000769 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, DeclRegionScope)) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000770 if (NamespaceDecl *OrigNS = dyn_cast<NamespaceDecl>(PrevDecl)) {
771 // This is an extended namespace definition.
772 // Attach this namespace decl to the chain of extended namespace
773 // definitions.
774 NamespaceDecl *NextNS = OrigNS;
775 while (NextNS->getNextNamespace())
776 NextNS = NextNS->getNextNamespace();
777
778 NextNS->setNextNamespace(Namespc);
779 Namespc->setOriginalNamespace(OrigNS);
780
781 // We won't add this decl to the current scope. We want the namespace
782 // name to return the original namespace decl during a name lookup.
783 } else {
784 // This is an invalid name redefinition.
785 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind,
786 Namespc->getName());
787 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
788 Namespc->setInvalidDecl();
789 // Continue on to push Namespc as current DeclContext and return it.
790 }
791 } else {
792 // This namespace name is declared for the first time.
793 PushOnScopeChains(Namespc, DeclRegionScope);
794 }
795 }
796 else {
797 // FIXME: Handle anonymous namespaces
798 }
799
800 // Although we could have an invalid decl (i.e. the namespace name is a
801 // redefinition), push it as current DeclContext and try to continue parsing.
802 PushDeclContext(Namespc->getOriginalNamespace());
803 return Namespc;
804}
805
806/// ActOnFinishNamespaceDef - This callback is called after a namespace is
807/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
808void Sema::ActOnFinishNamespaceDef(DeclTy *D, SourceLocation RBrace) {
809 Decl *Dcl = static_cast<Decl *>(D);
810 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
811 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
812 Namespc->setRBracLoc(RBrace);
813 PopDeclContext();
814}
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000815
816
817/// AddCXXDirectInitializerToDecl - This action is called immediately after
818/// ActOnDeclarator, when a C++ direct initializer is present.
819/// e.g: "int x(1);"
820void Sema::AddCXXDirectInitializerToDecl(DeclTy *Dcl, SourceLocation LParenLoc,
821 ExprTy **ExprTys, unsigned NumExprs,
822 SourceLocation *CommaLocs,
823 SourceLocation RParenLoc) {
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000824 assert(NumExprs != 0 && ExprTys && "missing expressions");
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000825 Decl *RealDecl = static_cast<Decl *>(Dcl);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000826
827 // If there is no declaration, there was an error parsing it. Just ignore
828 // the initializer.
829 if (RealDecl == 0) {
Ted Kremenek85b4c492008-10-06 20:35:04 +0000830 for (unsigned i = 0; i != NumExprs; ++i)
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000831 delete static_cast<Expr *>(ExprTys[i]);
832 return;
833 }
834
835 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
836 if (!VDecl) {
837 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
838 RealDecl->setInvalidDecl();
839 return;
840 }
841
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000842 // We will treat direct-initialization as a copy-initialization:
843 // int x(1); -as-> int x = 1;
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000844 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
845 //
846 // Clients that want to distinguish between the two forms, can check for
847 // direct initializer using VarDecl::hasCXXDirectInitializer().
848 // A major benefit is that clients that don't particularly care about which
849 // exactly form was it (like the CodeGen) can handle both cases without
850 // special case code.
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000851
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000852 // C++ 8.5p11:
853 // The form of initialization (using parentheses or '=') is generally
854 // insignificant, but does matter when the entity being initialized has a
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000855 // class type.
Douglas Gregor5870a952008-11-03 20:45:27 +0000856 QualType DeclInitType = VDecl->getType();
857 if (const ArrayType *Array = Context.getAsArrayType(DeclInitType))
858 DeclInitType = Array->getElementType();
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000859
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000860 if (VDecl->getType()->isRecordType()) {
Douglas Gregor5870a952008-11-03 20:45:27 +0000861 CXXConstructorDecl *Constructor
862 = PerformDirectInitForClassType(DeclInitType, (Expr **)ExprTys, NumExprs,
863 VDecl->getLocation(),
864 SourceRange(VDecl->getLocation(),
865 RParenLoc),
866 VDecl->getName(),
867 /*HasInitializer=*/true);
868 if (!Constructor) {
869 RealDecl->setInvalidDecl();
870 }
Argiris Kirtzidisffcb5032008-10-06 18:37:09 +0000871 return;
872 }
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000873
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000874 if (NumExprs > 1) {
875 Diag(CommaLocs[0], diag::err_builtin_direct_init_more_than_one_arg,
876 SourceRange(VDecl->getLocation(), RParenLoc));
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000877 RealDecl->setInvalidDecl();
878 return;
879 }
880
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000881 // Let clients know that initialization was done with a direct initializer.
882 VDecl->setCXXDirectInitializer(true);
Argiris Kirtzidisbca33bf2008-10-06 23:08:37 +0000883
884 assert(NumExprs == 1 && "Expected 1 expression");
885 // Set the init expression, handles conversions.
886 AddInitializerToDecl(Dcl, ExprTys[0]);
Argiris Kirtzidis9e55d462008-10-06 17:10:33 +0000887}
Douglas Gregor81c29152008-10-29 00:13:59 +0000888
Douglas Gregor5870a952008-11-03 20:45:27 +0000889/// PerformDirectInitForClassType - Perform direct-initialization (C++
890/// [dcl.init]) for a value of the given class type with the given set
891/// of arguments (@p Args). @p Loc is the location in the source code
892/// where the initializer occurs (e.g., a declaration, member
893/// initializer, functional cast, etc.) while @p Range covers the
894/// whole initialization. @p HasInitializer is true if the initializer
895/// was actually written in the source code. When successful, returns
896/// the constructor that will be used to perform the initialization;
897/// when the initialization fails, emits a diagnostic and returns null.
898CXXConstructorDecl *
899Sema::PerformDirectInitForClassType(QualType ClassType,
900 Expr **Args, unsigned NumArgs,
901 SourceLocation Loc, SourceRange Range,
902 std::string InitEntity,
903 bool HasInitializer) {
904 const RecordType *ClassRec = ClassType->getAsRecordType();
905 assert(ClassRec && "Can only initialize a class type here");
906
907 // C++ [dcl.init]p14:
908 //
909 // If the initialization is direct-initialization, or if it is
910 // copy-initialization where the cv-unqualified version of the
911 // source type is the same class as, or a derived class of, the
912 // class of the destination, constructors are considered. The
913 // applicable constructors are enumerated (13.3.1.3), and the
914 // best one is chosen through overload resolution (13.3). The
915 // constructor so selected is called to initialize the object,
916 // with the initializer expression(s) as its argument(s). If no
917 // constructor applies, or the overload resolution is ambiguous,
918 // the initialization is ill-formed.
919 //
920 // FIXME: We don't check cv-qualifiers on the class type, because we
921 // don't yet keep track of whether a class type is a POD class type
922 // (or a "trivial" class type, as is used in C++0x).
923 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
924 OverloadCandidateSet CandidateSet;
925 OverloadCandidateSet::iterator Best;
926 AddOverloadCandidates(ClassDecl->getConstructors(), Args, NumArgs,
927 CandidateSet);
928 switch (BestViableFunction(CandidateSet, Best)) {
929 case OR_Success:
930 // We found a constructor. Return it.
931 return cast<CXXConstructorDecl>(Best->Function);
932
933 case OR_No_Viable_Function:
934 if (CandidateSet.empty())
935 Diag(Loc, diag::err_ovl_no_viable_function_in_init,
936 InitEntity, Range);
937 else {
938 Diag(Loc, diag::err_ovl_no_viable_function_in_init_with_cands,
939 InitEntity, Range);
940 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
941 }
942 return 0;
943
944 case OR_Ambiguous:
945 Diag(Loc, diag::err_ovl_ambiguous_init,
946 InitEntity, Range);
947 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
948 return 0;
949 }
950
951 return 0;
952}
953
Douglas Gregor81c29152008-10-29 00:13:59 +0000954/// CompareReferenceRelationship - Compare the two types T1 and T2 to
955/// determine whether they are reference-related,
956/// reference-compatible, reference-compatible with added
957/// qualification, or incompatible, for use in C++ initialization by
958/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
959/// type, and the first type (T1) is the pointee type of the reference
960/// type being initialized.
961Sema::ReferenceCompareResult
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000962Sema::CompareReferenceRelationship(QualType T1, QualType T2,
963 bool& DerivedToBase) {
Douglas Gregor81c29152008-10-29 00:13:59 +0000964 assert(!T1->isReferenceType() && "T1 must be the pointee type of the reference type");
965 assert(!T2->isReferenceType() && "T2 cannot be a reference type");
966
967 T1 = Context.getCanonicalType(T1);
968 T2 = Context.getCanonicalType(T2);
969 QualType UnqualT1 = T1.getUnqualifiedType();
970 QualType UnqualT2 = T2.getUnqualifiedType();
971
972 // C++ [dcl.init.ref]p4:
973 // Given types “cv1 T1” and “cv2 T2,” “cv1 T1” is
974 // reference-related to “cv2 T2” if T1 is the same type as T2, or
975 // T1 is a base class of T2.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +0000976 if (UnqualT1 == UnqualT2)
977 DerivedToBase = false;
978 else if (IsDerivedFrom(UnqualT2, UnqualT1))
979 DerivedToBase = true;
980 else
Douglas Gregor81c29152008-10-29 00:13:59 +0000981 return Ref_Incompatible;
982
983 // At this point, we know that T1 and T2 are reference-related (at
984 // least).
985
986 // C++ [dcl.init.ref]p4:
987 // "cv1 T1” is reference-compatible with “cv2 T2” if T1 is
988 // reference-related to T2 and cv1 is the same cv-qualification
989 // as, or greater cv-qualification than, cv2. For purposes of
990 // overload resolution, cases for which cv1 is greater
991 // cv-qualification than cv2 are identified as
992 // reference-compatible with added qualification (see 13.3.3.2).
993 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
994 return Ref_Compatible;
995 else if (T1.isMoreQualifiedThan(T2))
996 return Ref_Compatible_With_Added_Qualification;
997 else
998 return Ref_Related;
999}
1000
1001/// CheckReferenceInit - Check the initialization of a reference
1002/// variable with the given initializer (C++ [dcl.init.ref]). Init is
1003/// the initializer (either a simple initializer or an initializer
Douglas Gregorb3dff482008-10-29 23:31:03 +00001004/// list), and DeclType is the type of the declaration. When ICS is
1005/// non-null, this routine will compute the implicit conversion
1006/// sequence according to C++ [over.ics.ref] and will not produce any
1007/// diagnostics; when ICS is null, it will emit diagnostics when any
1008/// errors are found. Either way, a return value of true indicates
1009/// that there was a failure, a return value of false indicates that
1010/// the reference initialization succeeded.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001011///
1012/// When @p SuppressUserConversions, user-defined conversions are
1013/// suppressed.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001014bool
1015Sema::CheckReferenceInit(Expr *&Init, QualType &DeclType,
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001016 ImplicitConversionSequence *ICS,
1017 bool SuppressUserConversions) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001018 assert(DeclType->isReferenceType() && "Reference init needs a reference");
1019
1020 QualType T1 = DeclType->getAsReferenceType()->getPointeeType();
1021 QualType T2 = Init->getType();
1022
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001023 // Compute some basic properties of the types and the initializer.
1024 bool DerivedToBase = false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001025 Expr::isLvalueResult InitLvalue = Init->isLvalue(Context);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001026 ReferenceCompareResult RefRelationship
1027 = CompareReferenceRelationship(T1, T2, DerivedToBase);
1028
1029 // Most paths end in a failed conversion.
1030 if (ICS)
1031 ICS->ConversionKind = ImplicitConversionSequence::BadConversion;
Douglas Gregor81c29152008-10-29 00:13:59 +00001032
1033 // C++ [dcl.init.ref]p5:
1034 // A reference to type “cv1 T1” is initialized by an expression
1035 // of type “cv2 T2” as follows:
1036
1037 // -- If the initializer expression
1038
1039 bool BindsDirectly = false;
1040 // -- is an lvalue (but is not a bit-field), and “cv1 T1” is
1041 // reference-compatible with “cv2 T2,” or
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001042 //
1043 // Note that the bit-field check is skipped if we are just computing
1044 // the implicit conversion sequence (C++ [over.best.ics]p2).
1045 if (InitLvalue == Expr::LV_Valid && (ICS || !Init->isBitField()) &&
1046 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001047 BindsDirectly = true;
1048
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001049 if (ICS) {
1050 // C++ [over.ics.ref]p1:
1051 // When a parameter of reference type binds directly (8.5.3)
1052 // to an argument expression, the implicit conversion sequence
1053 // is the identity conversion, unless the argument expression
1054 // has a type that is a derived class of the parameter type,
1055 // in which case the implicit conversion sequence is a
1056 // derived-to-base Conversion (13.3.3.1).
1057 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1058 ICS->Standard.First = ICK_Identity;
1059 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1060 ICS->Standard.Third = ICK_Identity;
1061 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1062 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001063 ICS->Standard.ReferenceBinding = true;
1064 ICS->Standard.DirectBinding = true;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001065
1066 // Nothing more to do: the inaccessibility/ambiguity check for
1067 // derived-to-base conversions is suppressed when we're
1068 // computing the implicit conversion sequence (C++
1069 // [over.best.ics]p2).
1070 return false;
1071 } else {
1072 // Perform the conversion.
Douglas Gregor81c29152008-10-29 00:13:59 +00001073 // FIXME: Binding to a subobject of the lvalue is going to require
1074 // more AST annotation than this.
1075 ImpCastExprToType(Init, T1);
1076 }
1077 }
1078
1079 // -- has a class type (i.e., T2 is a class type) and can be
1080 // implicitly converted to an lvalue of type “cv3 T3,”
1081 // where “cv1 T1” is reference-compatible with “cv3 T3”
1082 // 92) (this conversion is selected by enumerating the
1083 // applicable conversion functions (13.3.1.6) and choosing
1084 // the best one through overload resolution (13.3)),
1085 // FIXME: Implement this second bullet, once we have conversion
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001086 // functions. Also remember C++ [over.ics.ref]p1, second part.
Douglas Gregor81c29152008-10-29 00:13:59 +00001087
1088 if (BindsDirectly) {
1089 // C++ [dcl.init.ref]p4:
1090 // [...] In all cases where the reference-related or
1091 // reference-compatible relationship of two types is used to
1092 // establish the validity of a reference binding, and T1 is a
1093 // base class of T2, a program that necessitates such a binding
1094 // is ill-formed if T1 is an inaccessible (clause 11) or
1095 // ambiguous (10.2) base class of T2.
1096 //
1097 // Note that we only check this condition when we're allowed to
1098 // complain about errors, because we should not be checking for
1099 // ambiguity (or inaccessibility) unless the reference binding
1100 // actually happens.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001101 if (DerivedToBase)
1102 return CheckDerivedToBaseConversion(T2, T1,
1103 Init->getSourceRange().getBegin(),
1104 Init->getSourceRange());
1105 else
1106 return false;
Douglas Gregor81c29152008-10-29 00:13:59 +00001107 }
1108
1109 // -- Otherwise, the reference shall be to a non-volatile const
1110 // type (i.e., cv1 shall be const).
1111 if (T1.getCVRQualifiers() != QualType::Const) {
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001112 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001113 Diag(Init->getSourceRange().getBegin(),
1114 diag::err_not_reference_to_const_init,
1115 T1.getAsString(),
1116 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1117 T2.getAsString(), Init->getSourceRange());
1118 return true;
1119 }
1120
1121 // -- If the initializer expression is an rvalue, with T2 a
1122 // class type, and “cv1 T1” is reference-compatible with
1123 // “cv2 T2,” the reference is bound in one of the
1124 // following ways (the choice is implementation-defined):
1125 //
1126 // -- The reference is bound to the object represented by
1127 // the rvalue (see 3.10) or to a sub-object within that
1128 // object.
1129 //
1130 // -- A temporary of type “cv1 T2” [sic] is created, and
1131 // a constructor is called to copy the entire rvalue
1132 // object into the temporary. The reference is bound to
1133 // the temporary or to a sub-object within the
1134 // temporary.
1135 //
1136 //
1137 // The constructor that would be used to make the copy
1138 // shall be callable whether or not the copy is actually
1139 // done.
1140 //
1141 // Note that C++0x [dcl.ref.init]p5 takes away this implementation
1142 // freedom, so we will always take the first option and never build
1143 // a temporary in this case. FIXME: We will, however, have to check
1144 // for the presence of a copy constructor in C++98/03 mode.
1145 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001146 RefRelationship >= Ref_Compatible_With_Added_Qualification) {
1147 if (ICS) {
1148 ICS->ConversionKind = ImplicitConversionSequence::StandardConversion;
1149 ICS->Standard.First = ICK_Identity;
1150 ICS->Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
1151 ICS->Standard.Third = ICK_Identity;
1152 ICS->Standard.FromTypePtr = T2.getAsOpaquePtr();
1153 ICS->Standard.ToTypePtr = T1.getAsOpaquePtr();
Douglas Gregor0e343382008-10-29 14:50:44 +00001154 ICS->Standard.ReferenceBinding = true;
1155 ICS->Standard.DirectBinding = false;
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001156 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001157 // FIXME: Binding to a subobject of the rvalue is going to require
1158 // more AST annotation than this.
1159 ImpCastExprToType(Init, T1);
1160 }
1161 return false;
1162 }
1163
1164 // -- Otherwise, a temporary of type “cv1 T1” is created and
1165 // initialized from the initializer expression using the
1166 // rules for a non-reference copy initialization (8.5). The
1167 // reference is then bound to the temporary. If T1 is
1168 // reference-related to T2, cv1 must be the same
1169 // cv-qualification as, or greater cv-qualification than,
1170 // cv2; otherwise, the program is ill-formed.
1171 if (RefRelationship == Ref_Related) {
1172 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
1173 // we would be reference-compatible or reference-compatible with
1174 // added qualification. But that wasn't the case, so the reference
1175 // initialization fails.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001176 if (!ICS)
Douglas Gregor81c29152008-10-29 00:13:59 +00001177 Diag(Init->getSourceRange().getBegin(),
1178 diag::err_reference_init_drops_quals,
1179 T1.getAsString(),
1180 InitLvalue != Expr::LV_Valid? "temporary" : "value",
1181 T2.getAsString(), Init->getSourceRange());
1182 return true;
1183 }
1184
1185 // Actually try to convert the initializer to T1.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001186 if (ICS) {
1187 /// C++ [over.ics.ref]p2:
1188 ///
1189 /// When a parameter of reference type is not bound directly to
1190 /// an argument expression, the conversion sequence is the one
1191 /// required to convert the argument expression to the
1192 /// underlying type of the reference according to
1193 /// 13.3.3.1. Conceptually, this conversion sequence corresponds
1194 /// to copy-initializing a temporary of the underlying type with
1195 /// the argument expression. Any difference in top-level
1196 /// cv-qualification is subsumed by the initialization itself
1197 /// and does not constitute a conversion.
Douglas Gregora3b34bb2008-11-03 19:09:14 +00001198 *ICS = TryImplicitConversion(Init, T1, SuppressUserConversions);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001199 return ICS->ConversionKind == ImplicitConversionSequence::BadConversion;
1200 } else {
Douglas Gregor81c29152008-10-29 00:13:59 +00001201 return PerformImplicitConversion(Init, T1);
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001202 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001203}