1 //===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ declarations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/CXXFieldCollector.h"
16 #include "clang/Sema/Scope.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/AST/ASTConsumer.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/CXXInheritance.h"
23 #include "clang/AST/DeclVisitor.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/ParsedTemplate.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "llvm/ADT/DenseSet.h"
33 #include "llvm/ADT/STLExtras.h"
37 using namespace clang
;
39 //===----------------------------------------------------------------------===//
40 // CheckDefaultArgumentVisitor
41 //===----------------------------------------------------------------------===//
44 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
45 /// the default argument of a parameter to determine whether it
46 /// contains any ill-formed subexpressions. For example, this will
47 /// diagnose the use of local variables or parameters within the
48 /// default argument expression.
49 class CheckDefaultArgumentVisitor
50 : public StmtVisitor
<CheckDefaultArgumentVisitor
, bool> {
55 CheckDefaultArgumentVisitor(Expr
*defarg
, Sema
*s
)
56 : DefaultArg(defarg
), S(s
) {}
58 bool VisitExpr(Expr
*Node
);
59 bool VisitDeclRefExpr(DeclRefExpr
*DRE
);
60 bool VisitCXXThisExpr(CXXThisExpr
*ThisE
);
63 /// VisitExpr - Visit all of the children of this expression.
64 bool CheckDefaultArgumentVisitor::VisitExpr(Expr
*Node
) {
65 bool IsInvalid
= false;
66 for (Stmt::child_iterator I
= Node
->child_begin(),
67 E
= Node
->child_end(); I
!= E
; ++I
)
68 IsInvalid
|= Visit(*I
);
72 /// VisitDeclRefExpr - Visit a reference to a declaration, to
73 /// determine whether this declaration can be used in the default
74 /// argument expression.
75 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr
*DRE
) {
76 NamedDecl
*Decl
= DRE
->getDecl();
77 if (ParmVarDecl
*Param
= dyn_cast
<ParmVarDecl
>(Decl
)) {
78 // C++ [dcl.fct.default]p9
79 // Default arguments are evaluated each time the function is
80 // called. The order of evaluation of function arguments is
81 // unspecified. Consequently, parameters of a function shall not
82 // be used in default argument expressions, even if they are not
83 // evaluated. Parameters of a function declared before a default
84 // argument expression are in scope and can hide namespace and
85 // class member names.
86 return S
->Diag(DRE
->getSourceRange().getBegin(),
87 diag::err_param_default_argument_references_param
)
88 << Param
->getDeclName() << DefaultArg
->getSourceRange();
89 } else if (VarDecl
*VDecl
= dyn_cast
<VarDecl
>(Decl
)) {
90 // C++ [dcl.fct.default]p7
91 // Local variables shall not be used in default argument
93 if (VDecl
->isLocalVarDecl())
94 return S
->Diag(DRE
->getSourceRange().getBegin(),
95 diag::err_param_default_argument_references_local
)
96 << VDecl
->getDeclName() << DefaultArg
->getSourceRange();
102 /// VisitCXXThisExpr - Visit a C++ "this" expression.
103 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr
*ThisE
) {
104 // C++ [dcl.fct.default]p8:
105 // The keyword this shall not be used in a default argument of a
107 return S
->Diag(ThisE
->getSourceRange().getBegin(),
108 diag::err_param_default_argument_references_this
)
109 << ThisE
->getSourceRange();
114 Sema::SetParamDefaultArgument(ParmVarDecl
*Param
, Expr
*Arg
,
115 SourceLocation EqualLoc
) {
116 if (RequireCompleteType(Param
->getLocation(), Param
->getType(),
117 diag::err_typecheck_decl_incomplete_type
)) {
118 Param
->setInvalidDecl();
122 // C++ [dcl.fct.default]p5
123 // A default argument expression is implicitly converted (clause
124 // 4) to the parameter type. The default argument expression has
125 // the same semantic constraints as the initializer expression in
126 // a declaration of a variable of the parameter type, using the
127 // copy-initialization semantics (8.5).
128 InitializedEntity Entity
= InitializedEntity::InitializeParameter(Context
,
130 InitializationKind Kind
= InitializationKind::CreateCopy(Param
->getLocation(),
132 InitializationSequence
InitSeq(*this, Entity
, Kind
, &Arg
, 1);
133 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
,
134 MultiExprArg(*this, &Arg
, 1));
135 if (Result
.isInvalid())
137 Arg
= Result
.takeAs
<Expr
>();
139 CheckImplicitConversions(Arg
, EqualLoc
);
140 Arg
= MaybeCreateExprWithCleanups(Arg
);
142 // Okay: add the default argument to the parameter
143 Param
->setDefaultArg(Arg
);
145 // We have already instantiated this parameter; provide each of the
146 // instantiations with the uninstantiated default argument.
147 UnparsedDefaultArgInstantiationsMap::iterator InstPos
148 = UnparsedDefaultArgInstantiations
.find(Param
);
149 if (InstPos
!= UnparsedDefaultArgInstantiations
.end()) {
150 for (unsigned I
= 0, N
= InstPos
->second
.size(); I
!= N
; ++I
)
151 InstPos
->second
[I
]->setUninstantiatedDefaultArg(Arg
);
153 // We're done tracking this parameter's instantiations.
154 UnparsedDefaultArgInstantiations
.erase(InstPos
);
160 /// ActOnParamDefaultArgument - Check whether the default argument
161 /// provided for a function parameter is well-formed. If so, attach it
162 /// to the parameter declaration.
164 Sema::ActOnParamDefaultArgument(Decl
*param
, SourceLocation EqualLoc
,
166 if (!param
|| !DefaultArg
)
169 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(param
);
170 UnparsedDefaultArgLocs
.erase(Param
);
172 // Default arguments are only permitted in C++
173 if (!getLangOptions().CPlusPlus
) {
174 Diag(EqualLoc
, diag::err_param_default_argument
)
175 << DefaultArg
->getSourceRange();
176 Param
->setInvalidDecl();
180 // Check for unexpanded parameter packs.
181 if (DiagnoseUnexpandedParameterPack(DefaultArg
, UPPC_DefaultArgument
)) {
182 Param
->setInvalidDecl();
186 // Check that the default argument is well-formed
187 CheckDefaultArgumentVisitor
DefaultArgChecker(DefaultArg
, this);
188 if (DefaultArgChecker
.Visit(DefaultArg
)) {
189 Param
->setInvalidDecl();
193 SetParamDefaultArgument(Param
, DefaultArg
, EqualLoc
);
196 /// ActOnParamUnparsedDefaultArgument - We've seen a default
197 /// argument for a function parameter, but we can't parse it yet
198 /// because we're inside a class definition. Note that this default
199 /// argument will be parsed later.
200 void Sema::ActOnParamUnparsedDefaultArgument(Decl
*param
,
201 SourceLocation EqualLoc
,
202 SourceLocation ArgLoc
) {
206 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(param
);
208 Param
->setUnparsedDefaultArg();
210 UnparsedDefaultArgLocs
[Param
] = ArgLoc
;
213 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
214 /// the default argument for the parameter param failed.
215 void Sema::ActOnParamDefaultArgumentError(Decl
*param
) {
219 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(param
);
221 Param
->setInvalidDecl();
223 UnparsedDefaultArgLocs
.erase(Param
);
226 /// CheckExtraCXXDefaultArguments - Check for any extra default
227 /// arguments in the declarator, which is not a function declaration
228 /// or definition and therefore is not permitted to have default
229 /// arguments. This routine should be invoked for every declarator
230 /// that is not a function declaration or definition.
231 void Sema::CheckExtraCXXDefaultArguments(Declarator
&D
) {
232 // C++ [dcl.fct.default]p3
233 // A default argument expression shall be specified only in the
234 // parameter-declaration-clause of a function declaration or in a
235 // template-parameter (14.1). It shall not be specified for a
236 // parameter pack. If it is specified in a
237 // parameter-declaration-clause, it shall not occur within a
238 // declarator or abstract-declarator of a parameter-declaration.
239 for (unsigned i
= 0, e
= D
.getNumTypeObjects(); i
!= e
; ++i
) {
240 DeclaratorChunk
&chunk
= D
.getTypeObject(i
);
241 if (chunk
.Kind
== DeclaratorChunk::Function
) {
242 for (unsigned argIdx
= 0, e
= chunk
.Fun
.NumArgs
; argIdx
!= e
; ++argIdx
) {
244 cast
<ParmVarDecl
>(chunk
.Fun
.ArgInfo
[argIdx
].Param
);
245 if (Param
->hasUnparsedDefaultArg()) {
246 CachedTokens
*Toks
= chunk
.Fun
.ArgInfo
[argIdx
].DefaultArgTokens
;
247 Diag(Param
->getLocation(), diag::err_param_default_argument_nonfunc
)
248 << SourceRange((*Toks
)[1].getLocation(), Toks
->back().getLocation());
250 chunk
.Fun
.ArgInfo
[argIdx
].DefaultArgTokens
= 0;
251 } else if (Param
->getDefaultArg()) {
252 Diag(Param
->getLocation(), diag::err_param_default_argument_nonfunc
)
253 << Param
->getDefaultArg()->getSourceRange();
254 Param
->setDefaultArg(0);
261 // MergeCXXFunctionDecl - Merge two declarations of the same C++
262 // function, once we already know that they have the same
263 // type. Subroutine of MergeFunctionDecl. Returns true if there was an
264 // error, false otherwise.
265 bool Sema::MergeCXXFunctionDecl(FunctionDecl
*New
, FunctionDecl
*Old
) {
266 bool Invalid
= false;
268 // C++ [dcl.fct.default]p4:
269 // For non-template functions, default arguments can be added in
270 // later declarations of a function in the same
271 // scope. Declarations in different scopes have completely
272 // distinct sets of default arguments. That is, declarations in
273 // inner scopes do not acquire default arguments from
274 // declarations in outer scopes, and vice versa. In a given
275 // function declaration, all parameters subsequent to a
276 // parameter with a default argument shall have default
277 // arguments supplied in this or previous declarations. A
278 // default argument shall not be redefined by a later
279 // declaration (not even to the same value).
281 // C++ [dcl.fct.default]p6:
282 // Except for member functions of class templates, the default arguments
283 // in a member function definition that appears outside of the class
284 // definition are added to the set of default arguments provided by the
285 // member function declaration in the class definition.
286 for (unsigned p
= 0, NumParams
= Old
->getNumParams(); p
< NumParams
; ++p
) {
287 ParmVarDecl
*OldParam
= Old
->getParamDecl(p
);
288 ParmVarDecl
*NewParam
= New
->getParamDecl(p
);
290 if (OldParam
->hasDefaultArg() && NewParam
->hasDefaultArg()) {
291 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
292 // hint here. Alternatively, we could walk the type-source information
293 // for NewParam to find the last source location in the type... but it
294 // isn't worth the effort right now. This is the kind of test case that
295 // is hard to get right:
298 // void g(int (*fp)(int) = f);
299 // void g(int (*fp)(int) = &f);
300 Diag(NewParam
->getLocation(),
301 diag::err_param_default_argument_redefinition
)
302 << NewParam
->getDefaultArgRange();
304 // Look for the function declaration where the default argument was
305 // actually written, which may be a declaration prior to Old.
306 for (FunctionDecl
*Older
= Old
->getPreviousDeclaration();
307 Older
; Older
= Older
->getPreviousDeclaration()) {
308 if (!Older
->getParamDecl(p
)->hasDefaultArg())
311 OldParam
= Older
->getParamDecl(p
);
314 Diag(OldParam
->getLocation(), diag::note_previous_definition
)
315 << OldParam
->getDefaultArgRange();
317 } else if (OldParam
->hasDefaultArg()) {
318 // Merge the old default argument into the new parameter.
319 // It's important to use getInit() here; getDefaultArg()
320 // strips off any top-level ExprWithCleanups.
321 NewParam
->setHasInheritedDefaultArg();
322 if (OldParam
->hasUninstantiatedDefaultArg())
323 NewParam
->setUninstantiatedDefaultArg(
324 OldParam
->getUninstantiatedDefaultArg());
326 NewParam
->setDefaultArg(OldParam
->getInit());
327 } else if (NewParam
->hasDefaultArg()) {
328 if (New
->getDescribedFunctionTemplate()) {
329 // Paragraph 4, quoted above, only applies to non-template functions.
330 Diag(NewParam
->getLocation(),
331 diag::err_param_default_argument_template_redecl
)
332 << NewParam
->getDefaultArgRange();
333 Diag(Old
->getLocation(), diag::note_template_prev_declaration
)
335 } else if (New
->getTemplateSpecializationKind()
336 != TSK_ImplicitInstantiation
&&
337 New
->getTemplateSpecializationKind() != TSK_Undeclared
) {
338 // C++ [temp.expr.spec]p21:
339 // Default function arguments shall not be specified in a declaration
340 // or a definition for one of the following explicit specializations:
341 // - the explicit specialization of a function template;
342 // - the explicit specialization of a member function template;
343 // - the explicit specialization of a member function of a class
344 // template where the class template specialization to which the
345 // member function specialization belongs is implicitly
347 Diag(NewParam
->getLocation(), diag::err_template_spec_default_arg
)
348 << (New
->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization
)
349 << New
->getDeclName()
350 << NewParam
->getDefaultArgRange();
351 } else if (New
->getDeclContext()->isDependentContext()) {
352 // C++ [dcl.fct.default]p6 (DR217):
353 // Default arguments for a member function of a class template shall
354 // be specified on the initial declaration of the member function
355 // within the class template.
357 // Reading the tea leaves a bit in DR217 and its reference to DR205
358 // leads me to the conclusion that one cannot add default function
359 // arguments for an out-of-line definition of a member function of a
362 if (CXXRecordDecl
*Record
363 = dyn_cast
<CXXRecordDecl
>(New
->getDeclContext())) {
364 if (Record
->getDescribedClassTemplate())
366 else if (isa
<ClassTemplatePartialSpecializationDecl
>(Record
))
372 Diag(NewParam
->getLocation(),
373 diag::err_param_default_argument_member_template_redecl
)
375 << NewParam
->getDefaultArgRange();
380 if (CheckEquivalentExceptionSpec(Old
, New
))
386 /// CheckCXXDefaultArguments - Verify that the default arguments for a
387 /// function declaration are well-formed according to C++
388 /// [dcl.fct.default].
389 void Sema::CheckCXXDefaultArguments(FunctionDecl
*FD
) {
390 unsigned NumParams
= FD
->getNumParams();
393 // Find first parameter with a default argument
394 for (p
= 0; p
< NumParams
; ++p
) {
395 ParmVarDecl
*Param
= FD
->getParamDecl(p
);
396 if (Param
->hasDefaultArg())
400 // C++ [dcl.fct.default]p4:
401 // In a given function declaration, all parameters
402 // subsequent to a parameter with a default argument shall
403 // have default arguments supplied in this or previous
404 // declarations. A default argument shall not be redefined
405 // by a later declaration (not even to the same value).
406 unsigned LastMissingDefaultArg
= 0;
407 for (; p
< NumParams
; ++p
) {
408 ParmVarDecl
*Param
= FD
->getParamDecl(p
);
409 if (!Param
->hasDefaultArg()) {
410 if (Param
->isInvalidDecl())
411 /* We already complained about this parameter. */;
412 else if (Param
->getIdentifier())
413 Diag(Param
->getLocation(),
414 diag::err_param_default_argument_missing_name
)
415 << Param
->getIdentifier();
417 Diag(Param
->getLocation(),
418 diag::err_param_default_argument_missing
);
420 LastMissingDefaultArg
= p
;
424 if (LastMissingDefaultArg
> 0) {
425 // Some default arguments were missing. Clear out all of the
426 // default arguments up to (and including) the last missing
427 // default argument, so that we leave the function parameters
428 // in a semantically valid state.
429 for (p
= 0; p
<= LastMissingDefaultArg
; ++p
) {
430 ParmVarDecl
*Param
= FD
->getParamDecl(p
);
431 if (Param
->hasDefaultArg()) {
432 Param
->setDefaultArg(0);
438 /// isCurrentClassName - Determine whether the identifier II is the
439 /// name of the class type currently being defined. In the case of
440 /// nested classes, this will only return true if II is the name of
441 /// the innermost class.
442 bool Sema::isCurrentClassName(const IdentifierInfo
&II
, Scope
*,
443 const CXXScopeSpec
*SS
) {
444 assert(getLangOptions().CPlusPlus
&& "No class names in C!");
446 CXXRecordDecl
*CurDecl
;
447 if (SS
&& SS
->isSet() && !SS
->isInvalid()) {
448 DeclContext
*DC
= computeDeclContext(*SS
, true);
449 CurDecl
= dyn_cast_or_null
<CXXRecordDecl
>(DC
);
451 CurDecl
= dyn_cast_or_null
<CXXRecordDecl
>(CurContext
);
453 if (CurDecl
&& CurDecl
->getIdentifier())
454 return &II
== CurDecl
->getIdentifier();
459 /// \brief Check the validity of a C++ base class specifier.
461 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
462 /// and returns NULL otherwise.
464 Sema::CheckBaseSpecifier(CXXRecordDecl
*Class
,
465 SourceRange SpecifierRange
,
466 bool Virtual
, AccessSpecifier Access
,
467 TypeSourceInfo
*TInfo
,
468 SourceLocation EllipsisLoc
) {
469 QualType BaseType
= TInfo
->getType();
471 // C++ [class.union]p1:
472 // A union shall not have base classes.
473 if (Class
->isUnion()) {
474 Diag(Class
->getLocation(), diag::err_base_clause_on_union
)
479 if (EllipsisLoc
.isValid() &&
480 !TInfo
->getType()->containsUnexpandedParameterPack()) {
481 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
482 << TInfo
->getTypeLoc().getSourceRange();
483 EllipsisLoc
= SourceLocation();
486 if (BaseType
->isDependentType())
487 return new (Context
) CXXBaseSpecifier(SpecifierRange
, Virtual
,
488 Class
->getTagKind() == TTK_Class
,
489 Access
, TInfo
, EllipsisLoc
);
491 SourceLocation BaseLoc
= TInfo
->getTypeLoc().getBeginLoc();
493 // Base specifiers must be record types.
494 if (!BaseType
->isRecordType()) {
495 Diag(BaseLoc
, diag::err_base_must_be_class
) << SpecifierRange
;
499 // C++ [class.union]p1:
500 // A union shall not be used as a base class.
501 if (BaseType
->isUnionType()) {
502 Diag(BaseLoc
, diag::err_union_as_base_class
) << SpecifierRange
;
506 // C++ [class.derived]p2:
507 // The class-name in a base-specifier shall not be an incompletely
509 if (RequireCompleteType(BaseLoc
, BaseType
,
510 PDiag(diag::err_incomplete_base_class
)
511 << SpecifierRange
)) {
512 Class
->setInvalidDecl();
516 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
517 RecordDecl
*BaseDecl
= BaseType
->getAs
<RecordType
>()->getDecl();
518 assert(BaseDecl
&& "Record type has no declaration");
519 BaseDecl
= BaseDecl
->getDefinition();
520 assert(BaseDecl
&& "Base type is not incomplete, but has no definition");
521 CXXRecordDecl
* CXXBaseDecl
= cast
<CXXRecordDecl
>(BaseDecl
);
522 assert(CXXBaseDecl
&& "Base type is not a C++ type");
524 // C++ [class.derived]p2:
525 // If a class is marked with the class-virt-specifier final and it appears
526 // as a base-type-specifier in a base-clause (10 class.derived), the program
528 if (CXXBaseDecl
->hasAttr
<FinalAttr
>()) {
529 Diag(BaseLoc
, diag::err_class_marked_final_used_as_base
)
530 << CXXBaseDecl
->getDeclName();
531 Diag(CXXBaseDecl
->getLocation(), diag::note_previous_decl
)
532 << CXXBaseDecl
->getDeclName();
536 if (BaseDecl
->isInvalidDecl())
537 Class
->setInvalidDecl();
539 // Create the base specifier.
540 return new (Context
) CXXBaseSpecifier(SpecifierRange
, Virtual
,
541 Class
->getTagKind() == TTK_Class
,
542 Access
, TInfo
, EllipsisLoc
);
545 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
546 /// one entry in the base class list of a class specifier, for
548 /// class foo : public bar, virtual private baz {
549 /// 'public bar' and 'virtual private baz' are each base-specifiers.
551 Sema::ActOnBaseSpecifier(Decl
*classdecl
, SourceRange SpecifierRange
,
552 bool Virtual
, AccessSpecifier Access
,
553 ParsedType basetype
, SourceLocation BaseLoc
,
554 SourceLocation EllipsisLoc
) {
558 AdjustDeclIfTemplate(classdecl
);
559 CXXRecordDecl
*Class
= dyn_cast
<CXXRecordDecl
>(classdecl
);
563 TypeSourceInfo
*TInfo
= 0;
564 GetTypeFromParser(basetype
, &TInfo
);
566 if (EllipsisLoc
.isInvalid() &&
567 DiagnoseUnexpandedParameterPack(SpecifierRange
.getBegin(), TInfo
,
571 if (CXXBaseSpecifier
*BaseSpec
= CheckBaseSpecifier(Class
, SpecifierRange
,
572 Virtual
, Access
, TInfo
,
579 /// \brief Performs the actual work of attaching the given base class
580 /// specifiers to a C++ class.
581 bool Sema::AttachBaseSpecifiers(CXXRecordDecl
*Class
, CXXBaseSpecifier
**Bases
,
586 // Used to keep track of which base types we have already seen, so
587 // that we can properly diagnose redundant direct base types. Note
588 // that the key is always the unqualified canonical type of the base
590 std::map
<QualType
, CXXBaseSpecifier
*, QualTypeOrdering
> KnownBaseTypes
;
592 // Copy non-redundant base specifiers into permanent storage.
593 unsigned NumGoodBases
= 0;
594 bool Invalid
= false;
595 for (unsigned idx
= 0; idx
< NumBases
; ++idx
) {
597 = Context
.getCanonicalType(Bases
[idx
]->getType());
598 NewBaseType
= NewBaseType
.getLocalUnqualifiedType();
599 if (!Class
->hasObjectMember()) {
600 if (const RecordType
*FDTTy
=
601 NewBaseType
.getTypePtr()->getAs
<RecordType
>())
602 if (FDTTy
->getDecl()->hasObjectMember())
603 Class
->setHasObjectMember(true);
606 if (KnownBaseTypes
[NewBaseType
]) {
608 // A class shall not be specified as a direct base class of a
609 // derived class more than once.
610 Diag(Bases
[idx
]->getSourceRange().getBegin(),
611 diag::err_duplicate_base_class
)
612 << KnownBaseTypes
[NewBaseType
]->getType()
613 << Bases
[idx
]->getSourceRange();
615 // Delete the duplicate base class specifier; we're going to
616 // overwrite its pointer later.
617 Context
.Deallocate(Bases
[idx
]);
621 // Okay, add this new base class.
622 KnownBaseTypes
[NewBaseType
] = Bases
[idx
];
623 Bases
[NumGoodBases
++] = Bases
[idx
];
627 // Attach the remaining base class specifiers to the derived class.
628 Class
->setBases(Bases
, NumGoodBases
);
630 // Delete the remaining (good) base class specifiers, since their
631 // data has been copied into the CXXRecordDecl.
632 for (unsigned idx
= 0; idx
< NumGoodBases
; ++idx
)
633 Context
.Deallocate(Bases
[idx
]);
638 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
639 /// class, after checking whether there are any duplicate base
641 void Sema::ActOnBaseSpecifiers(Decl
*ClassDecl
, BaseTy
**Bases
,
643 if (!ClassDecl
|| !Bases
|| !NumBases
)
646 AdjustDeclIfTemplate(ClassDecl
);
647 AttachBaseSpecifiers(cast
<CXXRecordDecl
>(ClassDecl
),
648 (CXXBaseSpecifier
**)(Bases
), NumBases
);
651 static CXXRecordDecl
*GetClassForType(QualType T
) {
652 if (const RecordType
*RT
= T
->getAs
<RecordType
>())
653 return cast
<CXXRecordDecl
>(RT
->getDecl());
654 else if (const InjectedClassNameType
*ICT
= T
->getAs
<InjectedClassNameType
>())
655 return ICT
->getDecl();
660 /// \brief Determine whether the type \p Derived is a C++ class that is
661 /// derived from the type \p Base.
662 bool Sema::IsDerivedFrom(QualType Derived
, QualType Base
) {
663 if (!getLangOptions().CPlusPlus
)
666 CXXRecordDecl
*DerivedRD
= GetClassForType(Derived
);
670 CXXRecordDecl
*BaseRD
= GetClassForType(Base
);
674 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
675 return DerivedRD
->hasDefinition() && DerivedRD
->isDerivedFrom(BaseRD
);
678 /// \brief Determine whether the type \p Derived is a C++ class that is
679 /// derived from the type \p Base.
680 bool Sema::IsDerivedFrom(QualType Derived
, QualType Base
, CXXBasePaths
&Paths
) {
681 if (!getLangOptions().CPlusPlus
)
684 CXXRecordDecl
*DerivedRD
= GetClassForType(Derived
);
688 CXXRecordDecl
*BaseRD
= GetClassForType(Base
);
692 return DerivedRD
->isDerivedFrom(BaseRD
, Paths
);
695 void Sema::BuildBasePathArray(const CXXBasePaths
&Paths
,
696 CXXCastPath
&BasePathArray
) {
697 assert(BasePathArray
.empty() && "Base path array must be empty!");
698 assert(Paths
.isRecordingPaths() && "Must record paths!");
700 const CXXBasePath
&Path
= Paths
.front();
702 // We first go backward and check if we have a virtual base.
703 // FIXME: It would be better if CXXBasePath had the base specifier for
704 // the nearest virtual base.
706 for (unsigned I
= Path
.size(); I
!= 0; --I
) {
707 if (Path
[I
- 1].Base
->isVirtual()) {
713 // Now add all bases.
714 for (unsigned I
= Start
, E
= Path
.size(); I
!= E
; ++I
)
715 BasePathArray
.push_back(const_cast<CXXBaseSpecifier
*>(Path
[I
].Base
));
718 /// \brief Determine whether the given base path includes a virtual
720 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath
&BasePath
) {
721 for (CXXCastPath::const_iterator B
= BasePath
.begin(),
722 BEnd
= BasePath
.end();
724 if ((*B
)->isVirtual())
730 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
731 /// conversion (where Derived and Base are class types) is
732 /// well-formed, meaning that the conversion is unambiguous (and
733 /// that all of the base classes are accessible). Returns true
734 /// and emits a diagnostic if the code is ill-formed, returns false
735 /// otherwise. Loc is the location where this routine should point to
736 /// if there is an error, and Range is the source range to highlight
737 /// if there is an error.
739 Sema::CheckDerivedToBaseConversion(QualType Derived
, QualType Base
,
740 unsigned InaccessibleBaseID
,
741 unsigned AmbigiousBaseConvID
,
742 SourceLocation Loc
, SourceRange Range
,
743 DeclarationName Name
,
744 CXXCastPath
*BasePath
) {
745 // First, determine whether the path from Derived to Base is
746 // ambiguous. This is slightly more expensive than checking whether
747 // the Derived to Base conversion exists, because here we need to
748 // explore multiple paths to determine if there is an ambiguity.
749 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
750 /*DetectVirtual=*/false);
751 bool DerivationOkay
= IsDerivedFrom(Derived
, Base
, Paths
);
752 assert(DerivationOkay
&&
753 "Can only be used with a derived-to-base conversion");
754 (void)DerivationOkay
;
756 if (!Paths
.isAmbiguous(Context
.getCanonicalType(Base
).getUnqualifiedType())) {
757 if (InaccessibleBaseID
) {
758 // Check that the base class can be accessed.
759 switch (CheckBaseClassAccess(Loc
, Base
, Derived
, Paths
.front(),
760 InaccessibleBaseID
)) {
761 case AR_inaccessible
:
770 // Build a base path if necessary.
772 BuildBasePathArray(Paths
, *BasePath
);
776 // We know that the derived-to-base conversion is ambiguous, and
777 // we're going to produce a diagnostic. Perform the derived-to-base
778 // search just one more time to compute all of the possible paths so
779 // that we can print them out. This is more expensive than any of
780 // the previous derived-to-base checks we've done, but at this point
781 // performance isn't as much of an issue.
783 Paths
.setRecordingPaths(true);
784 bool StillOkay
= IsDerivedFrom(Derived
, Base
, Paths
);
785 assert(StillOkay
&& "Can only be used with a derived-to-base conversion");
788 // Build up a textual representation of the ambiguous paths, e.g.,
789 // D -> B -> A, that will be used to illustrate the ambiguous
790 // conversions in the diagnostic. We only print one of the paths
791 // to each base class subobject.
792 std::string PathDisplayStr
= getAmbiguousPathsDisplayString(Paths
);
794 Diag(Loc
, AmbigiousBaseConvID
)
795 << Derived
<< Base
<< PathDisplayStr
<< Range
<< Name
;
800 Sema::CheckDerivedToBaseConversion(QualType Derived
, QualType Base
,
801 SourceLocation Loc
, SourceRange Range
,
802 CXXCastPath
*BasePath
,
804 return CheckDerivedToBaseConversion(Derived
, Base
,
806 : diag::err_upcast_to_inaccessible_base
,
807 diag::err_ambiguous_derived_to_base_conv
,
808 Loc
, Range
, DeclarationName(),
813 /// @brief Builds a string representing ambiguous paths from a
814 /// specific derived class to different subobjects of the same base
817 /// This function builds a string that can be used in error messages
818 /// to show the different paths that one can take through the
819 /// inheritance hierarchy to go from the derived class to different
820 /// subobjects of a base class. The result looks something like this:
822 /// struct D -> struct B -> struct A
823 /// struct D -> struct C -> struct A
825 std::string
Sema::getAmbiguousPathsDisplayString(CXXBasePaths
&Paths
) {
826 std::string PathDisplayStr
;
827 std::set
<unsigned> DisplayedPaths
;
828 for (CXXBasePaths::paths_iterator Path
= Paths
.begin();
829 Path
!= Paths
.end(); ++Path
) {
830 if (DisplayedPaths
.insert(Path
->back().SubobjectNumber
).second
) {
831 // We haven't displayed a path to this particular base
832 // class subobject yet.
833 PathDisplayStr
+= "\n ";
834 PathDisplayStr
+= Context
.getTypeDeclType(Paths
.getOrigin()).getAsString();
835 for (CXXBasePath::const_iterator Element
= Path
->begin();
836 Element
!= Path
->end(); ++Element
)
837 PathDisplayStr
+= " -> " + Element
->Base
->getType().getAsString();
841 return PathDisplayStr
;
844 //===----------------------------------------------------------------------===//
845 // C++ class member Handling
846 //===----------------------------------------------------------------------===//
848 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
849 Decl
*Sema::ActOnAccessSpecifier(AccessSpecifier Access
,
850 SourceLocation ASLoc
,
851 SourceLocation ColonLoc
) {
852 assert(Access
!= AS_none
&& "Invalid kind for syntactic access specifier!");
853 AccessSpecDecl
*ASDecl
= AccessSpecDecl::Create(Context
, Access
, CurContext
,
855 CurContext
->addHiddenDecl(ASDecl
);
859 /// CheckOverrideControl - Check C++0x override control semantics.
860 void Sema::CheckOverrideControl(const Decl
*D
) {
861 const CXXMethodDecl
*MD
= llvm::dyn_cast
<CXXMethodDecl
>(D
);
862 if (!MD
|| !MD
->isVirtual())
865 if (MD
->isDependentContext())
868 // C++0x [class.virtual]p3:
869 // If a virtual function is marked with the virt-specifier override and does
870 // not override a member function of a base class,
871 // the program is ill-formed.
872 bool HasOverriddenMethods
=
873 MD
->begin_overridden_methods() != MD
->end_overridden_methods();
874 if (MD
->hasAttr
<OverrideAttr
>() && !HasOverriddenMethods
) {
875 Diag(MD
->getLocation(),
876 diag::err_function_marked_override_not_overriding
)
877 << MD
->getDeclName();
881 // C++0x [class.derived]p8:
882 // In a class definition marked with the class-virt-specifier explicit,
883 // if a virtual member function that is neither implicitly-declared nor a
884 // destructor overrides a member function of a base class and it is not
885 // marked with the virt-specifier override, the program is ill-formed.
886 if (MD
->getParent()->hasAttr
<ExplicitAttr
>() && !isa
<CXXDestructorDecl
>(MD
) &&
887 HasOverriddenMethods
&& !MD
->hasAttr
<OverrideAttr
>()) {
888 llvm::SmallVector
<const CXXMethodDecl
*, 4>
889 OverriddenMethods(MD
->begin_overridden_methods(),
890 MD
->end_overridden_methods());
892 Diag(MD
->getLocation(), diag::err_function_overriding_without_override
)
894 << (unsigned)OverriddenMethods
.size();
896 for (unsigned I
= 0; I
!= OverriddenMethods
.size(); ++I
)
897 Diag(OverriddenMethods
[I
]->getLocation(),
898 diag::note_overridden_virtual_function
);
902 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
903 /// function overrides a virtual member function marked 'final', according to
904 /// C++0x [class.virtual]p3.
905 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl
*New
,
906 const CXXMethodDecl
*Old
) {
907 if (!Old
->hasAttr
<FinalAttr
>())
910 Diag(New
->getLocation(), diag::err_final_function_overridden
)
911 << New
->getDeclName();
912 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
916 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
917 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
918 /// bitfield width if there is one and 'InitExpr' specifies the initializer if
921 Sema::ActOnCXXMemberDeclarator(Scope
*S
, AccessSpecifier AS
, Declarator
&D
,
922 MultiTemplateParamsArg TemplateParameterLists
,
923 ExprTy
*BW
, const VirtSpecifiers
&VS
,
924 ExprTy
*InitExpr
, bool IsDefinition
,
926 const DeclSpec
&DS
= D
.getDeclSpec();
927 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
928 DeclarationName Name
= NameInfo
.getName();
929 SourceLocation Loc
= NameInfo
.getLoc();
931 // For anonymous bitfields, the location should point to the type.
933 Loc
= D
.getSourceRange().getBegin();
935 Expr
*BitWidth
= static_cast<Expr
*>(BW
);
936 Expr
*Init
= static_cast<Expr
*>(InitExpr
);
938 assert(isa
<CXXRecordDecl
>(CurContext
));
939 assert(!DS
.isFriendSpecified());
942 if (D
.isFunctionDeclarator())
944 else if (D
.getNumTypeObjects() == 0 &&
945 D
.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename
) {
946 QualType TDType
= GetTypeFromParser(DS
.getRepAsType());
947 isFunc
= TDType
->isFunctionType();
950 // C++ 9.2p6: A member shall not be declared to have automatic storage
951 // duration (auto, register) or with the extern storage-class-specifier.
952 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
953 // data members and cannot be applied to names declared const or static,
954 // and cannot be applied to reference members.
955 switch (DS
.getStorageClassSpec()) {
956 case DeclSpec::SCS_unspecified
:
957 case DeclSpec::SCS_typedef
:
958 case DeclSpec::SCS_static
:
961 case DeclSpec::SCS_mutable
:
963 if (DS
.getStorageClassSpecLoc().isValid())
964 Diag(DS
.getStorageClassSpecLoc(), diag::err_mutable_function
);
966 Diag(DS
.getThreadSpecLoc(), diag::err_mutable_function
);
968 // FIXME: It would be nicer if the keyword was ignored only for this
969 // declarator. Otherwise we could get follow-up errors.
970 D
.getMutableDeclSpec().ClearStorageClassSpecs();
974 if (DS
.getStorageClassSpecLoc().isValid())
975 Diag(DS
.getStorageClassSpecLoc(),
976 diag::err_storageclass_invalid_for_member
);
978 Diag(DS
.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member
);
979 D
.getMutableDeclSpec().ClearStorageClassSpecs();
982 bool isInstField
= ((DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
||
983 DS
.getStorageClassSpec() == DeclSpec::SCS_mutable
) &&
988 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
991 if (SS
.isSet() && !SS
.isInvalid()) {
992 // The user provided a superfluous scope specifier inside a class
999 if ((DC
= computeDeclContext(SS
, false)) && DC
->Equals(CurContext
))
1000 Diag(D
.getIdentifierLoc(), diag::warn_member_extra_qualification
)
1001 << Name
<< FixItHint::CreateRemoval(SS
.getRange());
1003 Diag(D
.getIdentifierLoc(), diag::err_member_qualification
)
1004 << Name
<< SS
.getRange();
1009 // FIXME: Check for template parameters!
1010 // FIXME: Check that the name is an identifier!
1011 Member
= HandleField(S
, cast
<CXXRecordDecl
>(CurContext
), Loc
, D
, BitWidth
,
1013 assert(Member
&& "HandleField never returns null");
1015 Member
= HandleDeclarator(S
, D
, move(TemplateParameterLists
), IsDefinition
);
1020 // Non-instance-fields can't have a bitfield.
1022 if (Member
->isInvalidDecl()) {
1023 // don't emit another diagnostic.
1024 } else if (isa
<VarDecl
>(Member
)) {
1025 // C++ 9.6p3: A bit-field shall not be a static member.
1026 // "static member 'A' cannot be a bit-field"
1027 Diag(Loc
, diag::err_static_not_bitfield
)
1028 << Name
<< BitWidth
->getSourceRange();
1029 } else if (isa
<TypedefDecl
>(Member
)) {
1030 // "typedef member 'x' cannot be a bit-field"
1031 Diag(Loc
, diag::err_typedef_not_bitfield
)
1032 << Name
<< BitWidth
->getSourceRange();
1034 // A function typedef ("typedef int f(); f a;").
1035 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1036 Diag(Loc
, diag::err_not_integral_type_bitfield
)
1037 << Name
<< cast
<ValueDecl
>(Member
)->getType()
1038 << BitWidth
->getSourceRange();
1042 Member
->setInvalidDecl();
1045 Member
->setAccess(AS
);
1047 // If we have declared a member function template, set the access of the
1048 // templated declaration as well.
1049 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(Member
))
1050 FunTmpl
->getTemplatedDecl()->setAccess(AS
);
1053 if (VS
.isOverrideSpecified()) {
1054 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(Member
);
1055 if (!MD
|| !MD
->isVirtual()) {
1056 Diag(Member
->getLocStart(),
1057 diag::override_keyword_only_allowed_on_virtual_member_functions
)
1058 << "override" << FixItHint::CreateRemoval(VS
.getOverrideLoc());
1060 MD
->addAttr(new (Context
) OverrideAttr(VS
.getOverrideLoc(), Context
));
1062 if (VS
.isFinalSpecified()) {
1063 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(Member
);
1064 if (!MD
|| !MD
->isVirtual()) {
1065 Diag(Member
->getLocStart(),
1066 diag::override_keyword_only_allowed_on_virtual_member_functions
)
1067 << "final" << FixItHint::CreateRemoval(VS
.getFinalLoc());
1069 MD
->addAttr(new (Context
) FinalAttr(VS
.getFinalLoc(), Context
));
1072 CheckOverrideControl(Member
);
1074 assert((Name
|| isInstField
) && "No identifier for non-field ?");
1077 AddInitializerToDecl(Member
, Init
, false);
1078 if (Deleted
) // FIXME: Source location is not very good.
1079 SetDeclDeleted(Member
, D
.getSourceRange().getBegin());
1082 FieldCollector
->Add(cast
<FieldDecl
>(Member
));
1088 /// \brief Find the direct and/or virtual base specifiers that
1089 /// correspond to the given base type, for use in base initialization
1090 /// within a constructor.
1091 static bool FindBaseInitializer(Sema
&SemaRef
,
1092 CXXRecordDecl
*ClassDecl
,
1094 const CXXBaseSpecifier
*&DirectBaseSpec
,
1095 const CXXBaseSpecifier
*&VirtualBaseSpec
) {
1096 // First, check for a direct base class.
1098 for (CXXRecordDecl::base_class_const_iterator Base
1099 = ClassDecl
->bases_begin();
1100 Base
!= ClassDecl
->bases_end(); ++Base
) {
1101 if (SemaRef
.Context
.hasSameUnqualifiedType(BaseType
, Base
->getType())) {
1102 // We found a direct base of this type. That's what we're
1104 DirectBaseSpec
= &*Base
;
1109 // Check for a virtual base class.
1110 // FIXME: We might be able to short-circuit this if we know in advance that
1111 // there are no virtual bases.
1112 VirtualBaseSpec
= 0;
1113 if (!DirectBaseSpec
|| !DirectBaseSpec
->isVirtual()) {
1114 // We haven't found a base yet; search the class hierarchy for a
1115 // virtual base class.
1116 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1117 /*DetectVirtual=*/false);
1118 if (SemaRef
.IsDerivedFrom(SemaRef
.Context
.getTypeDeclType(ClassDecl
),
1120 for (CXXBasePaths::paths_iterator Path
= Paths
.begin();
1121 Path
!= Paths
.end(); ++Path
) {
1122 if (Path
->back().Base
->isVirtual()) {
1123 VirtualBaseSpec
= Path
->back().Base
;
1130 return DirectBaseSpec
|| VirtualBaseSpec
;
1133 /// ActOnMemInitializer - Handle a C++ member initializer.
1135 Sema::ActOnMemInitializer(Decl
*ConstructorD
,
1138 IdentifierInfo
*MemberOrBase
,
1139 ParsedType TemplateTypeTy
,
1140 SourceLocation IdLoc
,
1141 SourceLocation LParenLoc
,
1142 ExprTy
**Args
, unsigned NumArgs
,
1143 SourceLocation RParenLoc
,
1144 SourceLocation EllipsisLoc
) {
1148 AdjustDeclIfTemplate(ConstructorD
);
1150 CXXConstructorDecl
*Constructor
1151 = dyn_cast
<CXXConstructorDecl
>(ConstructorD
);
1153 // The user wrote a constructor initializer on a function that is
1154 // not a C++ constructor. Ignore the error for now, because we may
1155 // have more member initializers coming; we'll diagnose it just
1156 // once in ActOnMemInitializers.
1160 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
1162 // C++ [class.base.init]p2:
1163 // Names in a mem-initializer-id are looked up in the scope of the
1164 // constructor's class and, if not found in that scope, are looked
1165 // up in the scope containing the constructor's definition.
1166 // [Note: if the constructor's class contains a member with the
1167 // same name as a direct or virtual base class of the class, a
1168 // mem-initializer-id naming the member or base class and composed
1169 // of a single identifier refers to the class member. A
1170 // mem-initializer-id for the hidden base class may be specified
1171 // using a qualified name. ]
1172 if (!SS
.getScopeRep() && !TemplateTypeTy
) {
1173 // Look for a member, first.
1174 FieldDecl
*Member
= 0;
1175 DeclContext::lookup_result Result
1176 = ClassDecl
->lookup(MemberOrBase
);
1177 if (Result
.first
!= Result
.second
) {
1178 Member
= dyn_cast
<FieldDecl
>(*Result
.first
);
1181 if (EllipsisLoc
.isValid())
1182 Diag(EllipsisLoc
, diag::err_pack_expansion_member_init
)
1183 << MemberOrBase
<< SourceRange(IdLoc
, RParenLoc
);
1185 return BuildMemberInitializer(Member
, (Expr
**)Args
, NumArgs
, IdLoc
,
1186 LParenLoc
, RParenLoc
);
1189 // Handle anonymous union case.
1190 if (IndirectFieldDecl
* IndirectField
1191 = dyn_cast
<IndirectFieldDecl
>(*Result
.first
)) {
1192 if (EllipsisLoc
.isValid())
1193 Diag(EllipsisLoc
, diag::err_pack_expansion_member_init
)
1194 << MemberOrBase
<< SourceRange(IdLoc
, RParenLoc
);
1196 return BuildMemberInitializer(IndirectField
, (Expr
**)Args
,
1198 LParenLoc
, RParenLoc
);
1202 // It didn't name a member, so see if it names a class.
1204 TypeSourceInfo
*TInfo
= 0;
1206 if (TemplateTypeTy
) {
1207 BaseType
= GetTypeFromParser(TemplateTypeTy
, &TInfo
);
1209 LookupResult
R(*this, MemberOrBase
, IdLoc
, LookupOrdinaryName
);
1210 LookupParsedName(R
, S
, &SS
);
1212 TypeDecl
*TyD
= R
.getAsSingle
<TypeDecl
>();
1214 if (R
.isAmbiguous()) return true;
1216 // We don't want access-control diagnostics here.
1217 R
.suppressDiagnostics();
1219 if (SS
.isSet() && isDependentScopeSpecifier(SS
)) {
1220 bool NotUnknownSpecialization
= false;
1221 DeclContext
*DC
= computeDeclContext(SS
, false);
1222 if (CXXRecordDecl
*Record
= dyn_cast_or_null
<CXXRecordDecl
>(DC
))
1223 NotUnknownSpecialization
= !Record
->hasAnyDependentBases();
1225 if (!NotUnknownSpecialization
) {
1226 // When the scope specifier can refer to a member of an unknown
1227 // specialization, we take it as a type name.
1228 BaseType
= CheckTypenameType(ETK_None
,
1229 (NestedNameSpecifier
*)SS
.getScopeRep(),
1230 *MemberOrBase
, SourceLocation(),
1231 SS
.getRange(), IdLoc
);
1232 if (BaseType
.isNull())
1236 R
.setLookupName(MemberOrBase
);
1240 // If no results were found, try to correct typos.
1241 if (R
.empty() && BaseType
.isNull() &&
1242 CorrectTypo(R
, S
, &SS
, ClassDecl
, 0, CTC_NoKeywords
) &&
1243 R
.isSingleResult()) {
1244 if (FieldDecl
*Member
= R
.getAsSingle
<FieldDecl
>()) {
1245 if (Member
->getDeclContext()->getRedeclContext()->Equals(ClassDecl
)) {
1246 // We have found a non-static data member with a similar
1247 // name to what was typed; complain and initialize that
1249 Diag(R
.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest
)
1250 << MemberOrBase
<< true << R
.getLookupName()
1251 << FixItHint::CreateReplacement(R
.getNameLoc(),
1252 R
.getLookupName().getAsString());
1253 Diag(Member
->getLocation(), diag::note_previous_decl
)
1254 << Member
->getDeclName();
1256 return BuildMemberInitializer(Member
, (Expr
**)Args
, NumArgs
, IdLoc
,
1257 LParenLoc
, RParenLoc
);
1259 } else if (TypeDecl
*Type
= R
.getAsSingle
<TypeDecl
>()) {
1260 const CXXBaseSpecifier
*DirectBaseSpec
;
1261 const CXXBaseSpecifier
*VirtualBaseSpec
;
1262 if (FindBaseInitializer(*this, ClassDecl
,
1263 Context
.getTypeDeclType(Type
),
1264 DirectBaseSpec
, VirtualBaseSpec
)) {
1265 // We have found a direct or virtual base class with a
1266 // similar name to what was typed; complain and initialize
1268 Diag(R
.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest
)
1269 << MemberOrBase
<< false << R
.getLookupName()
1270 << FixItHint::CreateReplacement(R
.getNameLoc(),
1271 R
.getLookupName().getAsString());
1273 const CXXBaseSpecifier
*BaseSpec
= DirectBaseSpec
? DirectBaseSpec
1275 Diag(BaseSpec
->getSourceRange().getBegin(),
1276 diag::note_base_class_specified_here
)
1277 << BaseSpec
->getType()
1278 << BaseSpec
->getSourceRange();
1285 if (!TyD
&& BaseType
.isNull()) {
1286 Diag(IdLoc
, diag::err_mem_init_not_member_or_class
)
1287 << MemberOrBase
<< SourceRange(IdLoc
, RParenLoc
);
1292 if (BaseType
.isNull()) {
1293 BaseType
= Context
.getTypeDeclType(TyD
);
1295 NestedNameSpecifier
*Qualifier
=
1296 static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
1298 // FIXME: preserve source range information
1299 BaseType
= Context
.getElaboratedType(ETK_None
, Qualifier
, BaseType
);
1305 TInfo
= Context
.getTrivialTypeSourceInfo(BaseType
, IdLoc
);
1307 return BuildBaseInitializer(BaseType
, TInfo
, (Expr
**)Args
, NumArgs
,
1308 LParenLoc
, RParenLoc
, ClassDecl
, EllipsisLoc
);
1311 /// Checks an initializer expression for use of uninitialized fields, such as
1312 /// containing the field that is being initialized. Returns true if there is an
1313 /// uninitialized field was used an updates the SourceLocation parameter; false
1315 static bool InitExprContainsUninitializedFields(const Stmt
*S
,
1316 const ValueDecl
*LhsField
,
1317 SourceLocation
*L
) {
1318 assert(isa
<FieldDecl
>(LhsField
) || isa
<IndirectFieldDecl
>(LhsField
));
1320 if (isa
<CallExpr
>(S
)) {
1321 // Do not descend into function calls or constructors, as the use
1322 // of an uninitialized field may be valid. One would have to inspect
1323 // the contents of the function/ctor to determine if it is safe or not.
1324 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1325 // may be safe, depending on what the function/ctor does.
1328 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(S
)) {
1329 const NamedDecl
*RhsField
= ME
->getMemberDecl();
1331 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(RhsField
)) {
1332 // The member expression points to a static data member.
1333 assert(VD
->isStaticDataMember() &&
1334 "Member points to non-static data member!");
1339 if (isa
<EnumConstantDecl
>(RhsField
)) {
1340 // The member expression points to an enum.
1344 if (RhsField
== LhsField
) {
1345 // Initializing a field with itself. Throw a warning.
1346 // But wait; there are exceptions!
1347 // Exception #1: The field may not belong to this record.
1348 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1349 const Expr
*base
= ME
->getBase();
1350 if (base
!= NULL
&& !isa
<CXXThisExpr
>(base
->IgnoreParenCasts())) {
1351 // Even though the field matches, it does not belong to this record.
1354 // None of the exceptions triggered; return true to indicate an
1355 // uninitialized field was used.
1356 *L
= ME
->getMemberLoc();
1359 } else if (isa
<SizeOfAlignOfExpr
>(S
)) {
1360 // sizeof/alignof doesn't reference contents, do not warn.
1362 } else if (const UnaryOperator
*UOE
= dyn_cast
<UnaryOperator
>(S
)) {
1363 // address-of doesn't reference contents (the pointer may be dereferenced
1364 // in the same expression but it would be rare; and weird).
1365 if (UOE
->getOpcode() == UO_AddrOf
)
1368 for (Stmt::const_child_iterator it
= S
->child_begin(), e
= S
->child_end();
1371 // An expression such as 'member(arg ?: "")' may trigger this.
1374 if (InitExprContainsUninitializedFields(*it
, LhsField
, L
))
1381 Sema::BuildMemberInitializer(ValueDecl
*Member
, Expr
**Args
,
1382 unsigned NumArgs
, SourceLocation IdLoc
,
1383 SourceLocation LParenLoc
,
1384 SourceLocation RParenLoc
) {
1385 FieldDecl
*DirectMember
= dyn_cast
<FieldDecl
>(Member
);
1386 IndirectFieldDecl
*IndirectMember
= dyn_cast
<IndirectFieldDecl
>(Member
);
1387 assert((DirectMember
|| IndirectMember
) &&
1388 "Member must be a FieldDecl or IndirectFieldDecl");
1390 if (Member
->isInvalidDecl())
1393 // Diagnose value-uses of fields to initialize themselves, e.g.
1395 // where foo is not also a parameter to the constructor.
1396 // TODO: implement -Wuninitialized and fold this into that framework.
1397 for (unsigned i
= 0; i
< NumArgs
; ++i
) {
1399 if (InitExprContainsUninitializedFields(Args
[i
], Member
, &L
)) {
1400 // FIXME: Return true in the case when other fields are used before being
1401 // uninitialized. For example, let this field be the i'th field. When
1402 // initializing the i'th field, throw a warning if any of the >= i'th
1403 // fields are used, as they are not yet initialized.
1404 // Right now we are only handling the case where the i'th field uses
1405 // itself in its initializer.
1406 Diag(L
, diag::warn_field_is_uninit
);
1410 bool HasDependentArg
= false;
1411 for (unsigned i
= 0; i
< NumArgs
; i
++)
1412 HasDependentArg
|= Args
[i
]->isTypeDependent();
1415 if (Member
->getType()->isDependentType() || HasDependentArg
) {
1416 // Can't check initialization for a member of dependent type or when
1417 // any of the arguments are type-dependent expressions.
1418 Init
= new (Context
) ParenListExpr(Context
, LParenLoc
, Args
, NumArgs
,
1421 // Erase any temporaries within this evaluation context; we're not
1422 // going to track them in the AST, since we'll be rebuilding the
1423 // ASTs during template instantiation.
1424 ExprTemporaries
.erase(
1425 ExprTemporaries
.begin() + ExprEvalContexts
.back().NumTemporaries
,
1426 ExprTemporaries
.end());
1428 // Initialize the member.
1429 InitializedEntity MemberEntity
=
1430 DirectMember
? InitializedEntity::InitializeMember(DirectMember
, 0)
1431 : InitializedEntity::InitializeMember(IndirectMember
, 0);
1432 InitializationKind Kind
=
1433 InitializationKind::CreateDirect(IdLoc
, LParenLoc
, RParenLoc
);
1435 InitializationSequence
InitSeq(*this, MemberEntity
, Kind
, Args
, NumArgs
);
1437 ExprResult MemberInit
=
1438 InitSeq
.Perform(*this, MemberEntity
, Kind
,
1439 MultiExprArg(*this, Args
, NumArgs
), 0);
1440 if (MemberInit
.isInvalid())
1443 CheckImplicitConversions(MemberInit
.get(), LParenLoc
);
1445 // C++0x [class.base.init]p7:
1446 // The initialization of each base and member constitutes a
1448 MemberInit
= MaybeCreateExprWithCleanups(MemberInit
);
1449 if (MemberInit
.isInvalid())
1452 // If we are in a dependent context, template instantiation will
1453 // perform this type-checking again. Just save the arguments that we
1454 // received in a ParenListExpr.
1455 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1456 // of the information that we have about the member
1457 // initializer. However, deconstructing the ASTs is a dicey process,
1458 // and this approach is far more likely to get the corner cases right.
1459 if (CurContext
->isDependentContext())
1460 Init
= new (Context
) ParenListExpr(Context
, LParenLoc
, Args
, NumArgs
,
1463 Init
= MemberInit
.get();
1467 return new (Context
) CXXCtorInitializer(Context
, DirectMember
,
1468 IdLoc
, LParenLoc
, Init
,
1471 return new (Context
) CXXCtorInitializer(Context
, IndirectMember
,
1472 IdLoc
, LParenLoc
, Init
,
1478 Sema::BuildDelegatingInitializer(TypeSourceInfo
*TInfo
,
1479 Expr
**Args
, unsigned NumArgs
,
1480 SourceLocation LParenLoc
,
1481 SourceLocation RParenLoc
,
1482 CXXRecordDecl
*ClassDecl
,
1483 SourceLocation EllipsisLoc
) {
1484 SourceLocation Loc
= TInfo
->getTypeLoc().getLocalSourceRange().getBegin();
1485 if (!LangOpts
.CPlusPlus0x
)
1486 return Diag(Loc
, diag::err_delegation_0x_only
)
1487 << TInfo
->getTypeLoc().getLocalSourceRange();
1489 return Diag(Loc
, diag::err_delegation_unimplemented
)
1490 << TInfo
->getTypeLoc().getLocalSourceRange();
1494 Sema::BuildBaseInitializer(QualType BaseType
, TypeSourceInfo
*BaseTInfo
,
1495 Expr
**Args
, unsigned NumArgs
,
1496 SourceLocation LParenLoc
, SourceLocation RParenLoc
,
1497 CXXRecordDecl
*ClassDecl
,
1498 SourceLocation EllipsisLoc
) {
1499 bool HasDependentArg
= false;
1500 for (unsigned i
= 0; i
< NumArgs
; i
++)
1501 HasDependentArg
|= Args
[i
]->isTypeDependent();
1503 SourceLocation BaseLoc
1504 = BaseTInfo
->getTypeLoc().getLocalSourceRange().getBegin();
1506 if (!BaseType
->isDependentType() && !BaseType
->isRecordType())
1507 return Diag(BaseLoc
, diag::err_base_init_does_not_name_class
)
1508 << BaseType
<< BaseTInfo
->getTypeLoc().getLocalSourceRange();
1510 // C++ [class.base.init]p2:
1511 // [...] Unless the mem-initializer-id names a nonstatic data
1512 // member of the constructor's class or a direct or virtual base
1513 // of that class, the mem-initializer is ill-formed. A
1514 // mem-initializer-list can initialize a base class using any
1515 // name that denotes that base class type.
1516 bool Dependent
= BaseType
->isDependentType() || HasDependentArg
;
1518 if (EllipsisLoc
.isValid()) {
1519 // This is a pack expansion.
1520 if (!BaseType
->containsUnexpandedParameterPack()) {
1521 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
1522 << SourceRange(BaseLoc
, RParenLoc
);
1524 EllipsisLoc
= SourceLocation();
1527 // Check for any unexpanded parameter packs.
1528 if (DiagnoseUnexpandedParameterPack(BaseLoc
, BaseTInfo
, UPPC_Initializer
))
1531 for (unsigned I
= 0; I
!= NumArgs
; ++I
)
1532 if (DiagnoseUnexpandedParameterPack(Args
[I
]))
1536 // Check for direct and virtual base classes.
1537 const CXXBaseSpecifier
*DirectBaseSpec
= 0;
1538 const CXXBaseSpecifier
*VirtualBaseSpec
= 0;
1540 if (Context
.hasSameUnqualifiedType(QualType(ClassDecl
->getTypeForDecl(),0),
1542 return BuildDelegatingInitializer(BaseTInfo
, Args
, NumArgs
,
1543 LParenLoc
, RParenLoc
, ClassDecl
,
1546 FindBaseInitializer(*this, ClassDecl
, BaseType
, DirectBaseSpec
,
1549 // C++ [base.class.init]p2:
1550 // Unless the mem-initializer-id names a nonstatic data member of the
1551 // constructor's class or a direct or virtual base of that class, the
1552 // mem-initializer is ill-formed.
1553 if (!DirectBaseSpec
&& !VirtualBaseSpec
) {
1554 // If the class has any dependent bases, then it's possible that
1555 // one of those types will resolve to the same type as
1556 // BaseType. Therefore, just treat this as a dependent base
1557 // class initialization. FIXME: Should we try to check the
1558 // initialization anyway? It seems odd.
1559 if (ClassDecl
->hasAnyDependentBases())
1562 return Diag(BaseLoc
, diag::err_not_direct_base_or_virtual
)
1563 << BaseType
<< Context
.getTypeDeclType(ClassDecl
)
1564 << BaseTInfo
->getTypeLoc().getLocalSourceRange();
1569 // Can't check initialization for a base of dependent type or when
1570 // any of the arguments are type-dependent expressions.
1572 = Owned(new (Context
) ParenListExpr(Context
, LParenLoc
, Args
, NumArgs
,
1575 // Erase any temporaries within this evaluation context; we're not
1576 // going to track them in the AST, since we'll be rebuilding the
1577 // ASTs during template instantiation.
1578 ExprTemporaries
.erase(
1579 ExprTemporaries
.begin() + ExprEvalContexts
.back().NumTemporaries
,
1580 ExprTemporaries
.end());
1582 return new (Context
) CXXCtorInitializer(Context
, BaseTInfo
,
1583 /*IsVirtual=*/false,
1585 BaseInit
.takeAs
<Expr
>(),
1590 // C++ [base.class.init]p2:
1591 // If a mem-initializer-id is ambiguous because it designates both
1592 // a direct non-virtual base class and an inherited virtual base
1593 // class, the mem-initializer is ill-formed.
1594 if (DirectBaseSpec
&& VirtualBaseSpec
)
1595 return Diag(BaseLoc
, diag::err_base_init_direct_and_virtual
)
1596 << BaseType
<< BaseTInfo
->getTypeLoc().getLocalSourceRange();
1598 CXXBaseSpecifier
*BaseSpec
1599 = const_cast<CXXBaseSpecifier
*>(DirectBaseSpec
);
1601 BaseSpec
= const_cast<CXXBaseSpecifier
*>(VirtualBaseSpec
);
1603 // Initialize the base.
1604 InitializedEntity BaseEntity
=
1605 InitializedEntity::InitializeBase(Context
, BaseSpec
, VirtualBaseSpec
);
1606 InitializationKind Kind
=
1607 InitializationKind::CreateDirect(BaseLoc
, LParenLoc
, RParenLoc
);
1609 InitializationSequence
InitSeq(*this, BaseEntity
, Kind
, Args
, NumArgs
);
1611 ExprResult BaseInit
=
1612 InitSeq
.Perform(*this, BaseEntity
, Kind
,
1613 MultiExprArg(*this, Args
, NumArgs
), 0);
1614 if (BaseInit
.isInvalid())
1617 CheckImplicitConversions(BaseInit
.get(), LParenLoc
);
1619 // C++0x [class.base.init]p7:
1620 // The initialization of each base and member constitutes a
1622 BaseInit
= MaybeCreateExprWithCleanups(BaseInit
);
1623 if (BaseInit
.isInvalid())
1626 // If we are in a dependent context, template instantiation will
1627 // perform this type-checking again. Just save the arguments that we
1628 // received in a ParenListExpr.
1629 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1630 // of the information that we have about the base
1631 // initializer. However, deconstructing the ASTs is a dicey process,
1632 // and this approach is far more likely to get the corner cases right.
1633 if (CurContext
->isDependentContext()) {
1635 = Owned(new (Context
) ParenListExpr(Context
, LParenLoc
, Args
, NumArgs
,
1637 return new (Context
) CXXCtorInitializer(Context
, BaseTInfo
,
1638 BaseSpec
->isVirtual(),
1640 Init
.takeAs
<Expr
>(),
1645 return new (Context
) CXXCtorInitializer(Context
, BaseTInfo
,
1646 BaseSpec
->isVirtual(),
1648 BaseInit
.takeAs
<Expr
>(),
1653 /// ImplicitInitializerKind - How an implicit base or member initializer should
1654 /// initialize its base or member.
1655 enum ImplicitInitializerKind
{
1662 BuildImplicitBaseInitializer(Sema
&SemaRef
, CXXConstructorDecl
*Constructor
,
1663 ImplicitInitializerKind ImplicitInitKind
,
1664 CXXBaseSpecifier
*BaseSpec
,
1665 bool IsInheritedVirtualBase
,
1666 CXXCtorInitializer
*&CXXBaseInit
) {
1667 InitializedEntity InitEntity
1668 = InitializedEntity::InitializeBase(SemaRef
.Context
, BaseSpec
,
1669 IsInheritedVirtualBase
);
1671 ExprResult BaseInit
;
1673 switch (ImplicitInitKind
) {
1675 InitializationKind InitKind
1676 = InitializationKind::CreateDefault(Constructor
->getLocation());
1677 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
, 0, 0);
1678 BaseInit
= InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
,
1679 MultiExprArg(SemaRef
, 0, 0));
1684 ParmVarDecl
*Param
= Constructor
->getParamDecl(0);
1685 QualType ParamType
= Param
->getType().getNonReferenceType();
1688 DeclRefExpr::Create(SemaRef
.Context
, 0, SourceRange(), Param
,
1689 Constructor
->getLocation(), ParamType
,
1692 // Cast to the base class to avoid ambiguities.
1694 SemaRef
.Context
.getQualifiedType(BaseSpec
->getType().getUnqualifiedType(),
1695 ParamType
.getQualifiers());
1697 CXXCastPath BasePath
;
1698 BasePath
.push_back(BaseSpec
);
1699 SemaRef
.ImpCastExprToType(CopyCtorArg
, ArgTy
,
1700 CK_UncheckedDerivedToBase
,
1701 VK_LValue
, &BasePath
);
1703 InitializationKind InitKind
1704 = InitializationKind::CreateDirect(Constructor
->getLocation(),
1705 SourceLocation(), SourceLocation());
1706 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
,
1708 BaseInit
= InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
,
1709 MultiExprArg(&CopyCtorArg
, 1));
1714 assert(false && "Unhandled initializer kind!");
1717 BaseInit
= SemaRef
.MaybeCreateExprWithCleanups(BaseInit
);
1718 if (BaseInit
.isInvalid())
1722 new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
,
1723 SemaRef
.Context
.getTrivialTypeSourceInfo(BaseSpec
->getType(),
1725 BaseSpec
->isVirtual(),
1727 BaseInit
.takeAs
<Expr
>(),
1735 BuildImplicitMemberInitializer(Sema
&SemaRef
, CXXConstructorDecl
*Constructor
,
1736 ImplicitInitializerKind ImplicitInitKind
,
1738 CXXCtorInitializer
*&CXXMemberInit
) {
1739 if (Field
->isInvalidDecl())
1742 SourceLocation Loc
= Constructor
->getLocation();
1744 if (ImplicitInitKind
== IIK_Copy
) {
1745 ParmVarDecl
*Param
= Constructor
->getParamDecl(0);
1746 QualType ParamType
= Param
->getType().getNonReferenceType();
1748 Expr
*MemberExprBase
=
1749 DeclRefExpr::Create(SemaRef
.Context
, 0, SourceRange(), Param
,
1750 Loc
, ParamType
, VK_LValue
, 0);
1752 // Build a reference to this field within the parameter.
1754 LookupResult
MemberLookup(SemaRef
, Field
->getDeclName(), Loc
,
1755 Sema::LookupMemberName
);
1756 MemberLookup
.addDecl(Field
, AS_public
);
1757 MemberLookup
.resolveKind();
1758 ExprResult CopyCtorArg
1759 = SemaRef
.BuildMemberReferenceExpr(MemberExprBase
,
1763 /*FirstQualifierInScope=*/0,
1765 /*TemplateArgs=*/0);
1766 if (CopyCtorArg
.isInvalid())
1769 // When the field we are copying is an array, create index variables for
1770 // each dimension of the array. We use these index variables to subscript
1771 // the source array, and other clients (e.g., CodeGen) will perform the
1772 // necessary iteration with these index variables.
1773 llvm::SmallVector
<VarDecl
*, 4> IndexVariables
;
1774 QualType BaseType
= Field
->getType();
1775 QualType SizeType
= SemaRef
.Context
.getSizeType();
1776 while (const ConstantArrayType
*Array
1777 = SemaRef
.Context
.getAsConstantArrayType(BaseType
)) {
1778 // Create the iteration variable for this array index.
1779 IdentifierInfo
*IterationVarName
= 0;
1781 llvm::SmallString
<8> Str
;
1782 llvm::raw_svector_ostream
OS(Str
);
1783 OS
<< "__i" << IndexVariables
.size();
1784 IterationVarName
= &SemaRef
.Context
.Idents
.get(OS
.str());
1786 VarDecl
*IterationVar
1787 = VarDecl::Create(SemaRef
.Context
, SemaRef
.CurContext
, Loc
,
1788 IterationVarName
, SizeType
,
1789 SemaRef
.Context
.getTrivialTypeSourceInfo(SizeType
, Loc
),
1791 IndexVariables
.push_back(IterationVar
);
1793 // Create a reference to the iteration variable.
1794 ExprResult IterationVarRef
1795 = SemaRef
.BuildDeclRefExpr(IterationVar
, SizeType
, VK_RValue
, Loc
);
1796 assert(!IterationVarRef
.isInvalid() &&
1797 "Reference to invented variable cannot fail!");
1799 // Subscript the array with this iteration variable.
1800 CopyCtorArg
= SemaRef
.CreateBuiltinArraySubscriptExpr(CopyCtorArg
.take(),
1802 IterationVarRef
.take(),
1804 if (CopyCtorArg
.isInvalid())
1807 BaseType
= Array
->getElementType();
1810 // Construct the entity that we will be initializing. For an array, this
1811 // will be first element in the array, which may require several levels
1812 // of array-subscript entities.
1813 llvm::SmallVector
<InitializedEntity
, 4> Entities
;
1814 Entities
.reserve(1 + IndexVariables
.size());
1815 Entities
.push_back(InitializedEntity::InitializeMember(Field
));
1816 for (unsigned I
= 0, N
= IndexVariables
.size(); I
!= N
; ++I
)
1817 Entities
.push_back(InitializedEntity::InitializeElement(SemaRef
.Context
,
1821 // Direct-initialize to use the copy constructor.
1822 InitializationKind InitKind
=
1823 InitializationKind::CreateDirect(Loc
, SourceLocation(), SourceLocation());
1825 Expr
*CopyCtorArgE
= CopyCtorArg
.takeAs
<Expr
>();
1826 InitializationSequence
InitSeq(SemaRef
, Entities
.back(), InitKind
,
1829 ExprResult MemberInit
1830 = InitSeq
.Perform(SemaRef
, Entities
.back(), InitKind
,
1831 MultiExprArg(&CopyCtorArgE
, 1));
1832 MemberInit
= SemaRef
.MaybeCreateExprWithCleanups(MemberInit
);
1833 if (MemberInit
.isInvalid())
1837 = CXXCtorInitializer::Create(SemaRef
.Context
, Field
, Loc
, Loc
,
1838 MemberInit
.takeAs
<Expr
>(), Loc
,
1839 IndexVariables
.data(),
1840 IndexVariables
.size());
1844 assert(ImplicitInitKind
== IIK_Default
&& "Unhandled implicit init kind!");
1846 QualType FieldBaseElementType
=
1847 SemaRef
.Context
.getBaseElementType(Field
->getType());
1849 if (FieldBaseElementType
->isRecordType()) {
1850 InitializedEntity InitEntity
= InitializedEntity::InitializeMember(Field
);
1851 InitializationKind InitKind
=
1852 InitializationKind::CreateDefault(Loc
);
1854 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
, 0, 0);
1855 ExprResult MemberInit
=
1856 InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
, MultiExprArg());
1858 MemberInit
= SemaRef
.MaybeCreateExprWithCleanups(MemberInit
);
1859 if (MemberInit
.isInvalid())
1863 new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
,
1870 if (FieldBaseElementType
->isReferenceType()) {
1871 SemaRef
.Diag(Constructor
->getLocation(),
1872 diag::err_uninitialized_member_in_ctor
)
1873 << (int)Constructor
->isImplicit()
1874 << SemaRef
.Context
.getTagDeclType(Constructor
->getParent())
1875 << 0 << Field
->getDeclName();
1876 SemaRef
.Diag(Field
->getLocation(), diag::note_declared_at
);
1880 if (FieldBaseElementType
.isConstQualified()) {
1881 SemaRef
.Diag(Constructor
->getLocation(),
1882 diag::err_uninitialized_member_in_ctor
)
1883 << (int)Constructor
->isImplicit()
1884 << SemaRef
.Context
.getTagDeclType(Constructor
->getParent())
1885 << 1 << Field
->getDeclName();
1886 SemaRef
.Diag(Field
->getLocation(), diag::note_declared_at
);
1890 // Nothing to initialize.
1896 struct BaseAndFieldInfo
{
1898 CXXConstructorDecl
*Ctor
;
1899 bool AnyErrorsInInits
;
1900 ImplicitInitializerKind IIK
;
1901 llvm::DenseMap
<const void *, CXXCtorInitializer
*> AllBaseFields
;
1902 llvm::SmallVector
<CXXCtorInitializer
*, 8> AllToInit
;
1904 BaseAndFieldInfo(Sema
&S
, CXXConstructorDecl
*Ctor
, bool ErrorsInInits
)
1905 : S(S
), Ctor(Ctor
), AnyErrorsInInits(ErrorsInInits
) {
1906 // FIXME: Handle implicit move constructors.
1907 if (Ctor
->isImplicit() && Ctor
->isCopyConstructor())
1915 static bool CollectFieldInitializer(BaseAndFieldInfo
&Info
,
1916 FieldDecl
*Top
, FieldDecl
*Field
) {
1918 // Overwhelmingly common case: we have a direct initializer for this field.
1919 if (CXXCtorInitializer
*Init
= Info
.AllBaseFields
.lookup(Field
)) {
1920 Info
.AllToInit
.push_back(Init
);
1924 if (Info
.IIK
== IIK_Default
&& Field
->isAnonymousStructOrUnion()) {
1925 const RecordType
*FieldClassType
= Field
->getType()->getAs
<RecordType
>();
1926 assert(FieldClassType
&& "anonymous struct/union without record type");
1927 CXXRecordDecl
*FieldClassDecl
1928 = cast
<CXXRecordDecl
>(FieldClassType
->getDecl());
1930 // Even though union members never have non-trivial default
1931 // constructions in C++03, we still build member initializers for aggregate
1932 // record types which can be union members, and C++0x allows non-trivial
1933 // default constructors for union members, so we ensure that only one
1934 // member is initialized for these.
1935 if (FieldClassDecl
->isUnion()) {
1936 // First check for an explicit initializer for one field.
1937 for (RecordDecl::field_iterator FA
= FieldClassDecl
->field_begin(),
1938 EA
= FieldClassDecl
->field_end(); FA
!= EA
; FA
++) {
1939 if (CXXCtorInitializer
*Init
= Info
.AllBaseFields
.lookup(*FA
)) {
1940 Info
.AllToInit
.push_back(Init
);
1942 // Once we've initialized a field of an anonymous union, the union
1943 // field in the class is also initialized, so exit immediately.
1945 } else if ((*FA
)->isAnonymousStructOrUnion()) {
1946 if (CollectFieldInitializer(Info
, Top
, *FA
))
1951 // Fallthrough and construct a default initializer for the union as
1952 // a whole, which can call its default constructor if such a thing exists
1953 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1954 // behavior going forward with C++0x, when anonymous unions there are
1955 // finalized, we should revisit this.
1957 // For structs, we simply descend through to initialize all members where
1959 for (RecordDecl::field_iterator FA
= FieldClassDecl
->field_begin(),
1960 EA
= FieldClassDecl
->field_end(); FA
!= EA
; FA
++) {
1961 if (CollectFieldInitializer(Info
, Top
, *FA
))
1967 // Don't try to build an implicit initializer if there were semantic
1968 // errors in any of the initializers (and therefore we might be
1969 // missing some that the user actually wrote).
1970 if (Info
.AnyErrorsInInits
)
1973 CXXCtorInitializer
*Init
= 0;
1974 if (BuildImplicitMemberInitializer(Info
.S
, Info
.Ctor
, Info
.IIK
, Field
, Init
))
1978 Info
.AllToInit
.push_back(Init
);
1984 Sema::SetCtorInitializers(CXXConstructorDecl
*Constructor
,
1985 CXXCtorInitializer
**Initializers
,
1986 unsigned NumInitializers
,
1988 if (Constructor
->getDeclContext()->isDependentContext()) {
1989 // Just store the initializers as written, they will be checked during
1991 if (NumInitializers
> 0) {
1992 Constructor
->setNumCtorInitializers(NumInitializers
);
1993 CXXCtorInitializer
**baseOrMemberInitializers
=
1994 new (Context
) CXXCtorInitializer
*[NumInitializers
];
1995 memcpy(baseOrMemberInitializers
, Initializers
,
1996 NumInitializers
* sizeof(CXXCtorInitializer
*));
1997 Constructor
->setCtorInitializers(baseOrMemberInitializers
);
2003 BaseAndFieldInfo
Info(*this, Constructor
, AnyErrors
);
2005 // We need to build the initializer AST according to order of construction
2006 // and not what user specified in the Initializers list.
2007 CXXRecordDecl
*ClassDecl
= Constructor
->getParent()->getDefinition();
2011 bool HadError
= false;
2013 for (unsigned i
= 0; i
< NumInitializers
; i
++) {
2014 CXXCtorInitializer
*Member
= Initializers
[i
];
2016 if (Member
->isBaseInitializer())
2017 Info
.AllBaseFields
[Member
->getBaseClass()->getAs
<RecordType
>()] = Member
;
2019 Info
.AllBaseFields
[Member
->getAnyMember()] = Member
;
2022 // Keep track of the direct virtual bases.
2023 llvm::SmallPtrSet
<CXXBaseSpecifier
*, 16> DirectVBases
;
2024 for (CXXRecordDecl::base_class_iterator I
= ClassDecl
->bases_begin(),
2025 E
= ClassDecl
->bases_end(); I
!= E
; ++I
) {
2027 DirectVBases
.insert(I
);
2030 // Push virtual bases before others.
2031 for (CXXRecordDecl::base_class_iterator VBase
= ClassDecl
->vbases_begin(),
2032 E
= ClassDecl
->vbases_end(); VBase
!= E
; ++VBase
) {
2034 if (CXXCtorInitializer
*Value
2035 = Info
.AllBaseFields
.lookup(VBase
->getType()->getAs
<RecordType
>())) {
2036 Info
.AllToInit
.push_back(Value
);
2037 } else if (!AnyErrors
) {
2038 bool IsInheritedVirtualBase
= !DirectVBases
.count(VBase
);
2039 CXXCtorInitializer
*CXXBaseInit
;
2040 if (BuildImplicitBaseInitializer(*this, Constructor
, Info
.IIK
,
2041 VBase
, IsInheritedVirtualBase
,
2047 Info
.AllToInit
.push_back(CXXBaseInit
);
2051 // Non-virtual bases.
2052 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
2053 E
= ClassDecl
->bases_end(); Base
!= E
; ++Base
) {
2054 // Virtuals are in the virtual base list and already constructed.
2055 if (Base
->isVirtual())
2058 if (CXXCtorInitializer
*Value
2059 = Info
.AllBaseFields
.lookup(Base
->getType()->getAs
<RecordType
>())) {
2060 Info
.AllToInit
.push_back(Value
);
2061 } else if (!AnyErrors
) {
2062 CXXCtorInitializer
*CXXBaseInit
;
2063 if (BuildImplicitBaseInitializer(*this, Constructor
, Info
.IIK
,
2064 Base
, /*IsInheritedVirtualBase=*/false,
2070 Info
.AllToInit
.push_back(CXXBaseInit
);
2075 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
2076 E
= ClassDecl
->field_end(); Field
!= E
; ++Field
) {
2077 if ((*Field
)->getType()->isIncompleteArrayType()) {
2078 assert(ClassDecl
->hasFlexibleArrayMember() &&
2079 "Incomplete array type is not valid");
2082 if (CollectFieldInitializer(Info
, *Field
, *Field
))
2086 NumInitializers
= Info
.AllToInit
.size();
2087 if (NumInitializers
> 0) {
2088 Constructor
->setNumCtorInitializers(NumInitializers
);
2089 CXXCtorInitializer
**baseOrMemberInitializers
=
2090 new (Context
) CXXCtorInitializer
*[NumInitializers
];
2091 memcpy(baseOrMemberInitializers
, Info
.AllToInit
.data(),
2092 NumInitializers
* sizeof(CXXCtorInitializer
*));
2093 Constructor
->setCtorInitializers(baseOrMemberInitializers
);
2095 // Constructors implicitly reference the base and member
2097 MarkBaseAndMemberDestructorsReferenced(Constructor
->getLocation(),
2098 Constructor
->getParent());
2104 static void *GetKeyForTopLevelField(FieldDecl
*Field
) {
2105 // For anonymous unions, use the class declaration as the key.
2106 if (const RecordType
*RT
= Field
->getType()->getAs
<RecordType
>()) {
2107 if (RT
->getDecl()->isAnonymousStructOrUnion())
2108 return static_cast<void *>(RT
->getDecl());
2110 return static_cast<void *>(Field
);
2113 static void *GetKeyForBase(ASTContext
&Context
, QualType BaseType
) {
2114 return const_cast<Type
*>(Context
.getCanonicalType(BaseType
).getTypePtr());
2117 static void *GetKeyForMember(ASTContext
&Context
,
2118 CXXCtorInitializer
*Member
) {
2119 if (!Member
->isAnyMemberInitializer())
2120 return GetKeyForBase(Context
, QualType(Member
->getBaseClass(), 0));
2122 // For fields injected into the class via declaration of an anonymous union,
2123 // use its anonymous union class declaration as the unique key.
2124 FieldDecl
*Field
= Member
->getAnyMember();
2126 // If the field is a member of an anonymous struct or union, our key
2127 // is the anonymous record decl that's a direct child of the class.
2128 RecordDecl
*RD
= Field
->getParent();
2129 if (RD
->isAnonymousStructOrUnion()) {
2131 RecordDecl
*Parent
= cast
<RecordDecl
>(RD
->getDeclContext());
2132 if (Parent
->isAnonymousStructOrUnion())
2138 return static_cast<void *>(RD
);
2141 return static_cast<void *>(Field
);
2145 DiagnoseBaseOrMemInitializerOrder(Sema
&SemaRef
,
2146 const CXXConstructorDecl
*Constructor
,
2147 CXXCtorInitializer
**Inits
,
2148 unsigned NumInits
) {
2149 if (Constructor
->getDeclContext()->isDependentContext())
2152 // Don't check initializers order unless the warning is enabled at the
2153 // location of at least one initializer.
2154 bool ShouldCheckOrder
= false;
2155 for (unsigned InitIndex
= 0; InitIndex
!= NumInits
; ++InitIndex
) {
2156 CXXCtorInitializer
*Init
= Inits
[InitIndex
];
2157 if (SemaRef
.Diags
.getDiagnosticLevel(diag::warn_initializer_out_of_order
,
2158 Init
->getSourceLocation())
2159 != Diagnostic::Ignored
) {
2160 ShouldCheckOrder
= true;
2164 if (!ShouldCheckOrder
)
2167 // Build the list of bases and members in the order that they'll
2168 // actually be initialized. The explicit initializers should be in
2169 // this same order but may be missing things.
2170 llvm::SmallVector
<const void*, 32> IdealInitKeys
;
2172 const CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
2174 // 1. Virtual bases.
2175 for (CXXRecordDecl::base_class_const_iterator VBase
=
2176 ClassDecl
->vbases_begin(),
2177 E
= ClassDecl
->vbases_end(); VBase
!= E
; ++VBase
)
2178 IdealInitKeys
.push_back(GetKeyForBase(SemaRef
.Context
, VBase
->getType()));
2180 // 2. Non-virtual bases.
2181 for (CXXRecordDecl::base_class_const_iterator Base
= ClassDecl
->bases_begin(),
2182 E
= ClassDecl
->bases_end(); Base
!= E
; ++Base
) {
2183 if (Base
->isVirtual())
2185 IdealInitKeys
.push_back(GetKeyForBase(SemaRef
.Context
, Base
->getType()));
2188 // 3. Direct fields.
2189 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
2190 E
= ClassDecl
->field_end(); Field
!= E
; ++Field
)
2191 IdealInitKeys
.push_back(GetKeyForTopLevelField(*Field
));
2193 unsigned NumIdealInits
= IdealInitKeys
.size();
2194 unsigned IdealIndex
= 0;
2196 CXXCtorInitializer
*PrevInit
= 0;
2197 for (unsigned InitIndex
= 0; InitIndex
!= NumInits
; ++InitIndex
) {
2198 CXXCtorInitializer
*Init
= Inits
[InitIndex
];
2199 void *InitKey
= GetKeyForMember(SemaRef
.Context
, Init
);
2201 // Scan forward to try to find this initializer in the idealized
2202 // initializers list.
2203 for (; IdealIndex
!= NumIdealInits
; ++IdealIndex
)
2204 if (InitKey
== IdealInitKeys
[IdealIndex
])
2207 // If we didn't find this initializer, it must be because we
2208 // scanned past it on a previous iteration. That can only
2209 // happen if we're out of order; emit a warning.
2210 if (IdealIndex
== NumIdealInits
&& PrevInit
) {
2211 Sema::SemaDiagnosticBuilder D
=
2212 SemaRef
.Diag(PrevInit
->getSourceLocation(),
2213 diag::warn_initializer_out_of_order
);
2215 if (PrevInit
->isAnyMemberInitializer())
2216 D
<< 0 << PrevInit
->getAnyMember()->getDeclName();
2218 D
<< 1 << PrevInit
->getBaseClassInfo()->getType();
2220 if (Init
->isAnyMemberInitializer())
2221 D
<< 0 << Init
->getAnyMember()->getDeclName();
2223 D
<< 1 << Init
->getBaseClassInfo()->getType();
2225 // Move back to the initializer's location in the ideal list.
2226 for (IdealIndex
= 0; IdealIndex
!= NumIdealInits
; ++IdealIndex
)
2227 if (InitKey
== IdealInitKeys
[IdealIndex
])
2230 assert(IdealIndex
!= NumIdealInits
&&
2231 "initializer not found in initializer list");
2239 bool CheckRedundantInit(Sema
&S
,
2240 CXXCtorInitializer
*Init
,
2241 CXXCtorInitializer
*&PrevInit
) {
2247 if (FieldDecl
*Field
= Init
->getMember())
2248 S
.Diag(Init
->getSourceLocation(),
2249 diag::err_multiple_mem_initialization
)
2250 << Field
->getDeclName()
2251 << Init
->getSourceRange();
2253 const Type
*BaseClass
= Init
->getBaseClass();
2254 assert(BaseClass
&& "neither field nor base");
2255 S
.Diag(Init
->getSourceLocation(),
2256 diag::err_multiple_base_initialization
)
2257 << QualType(BaseClass
, 0)
2258 << Init
->getSourceRange();
2260 S
.Diag(PrevInit
->getSourceLocation(), diag::note_previous_initializer
)
2261 << 0 << PrevInit
->getSourceRange();
2266 typedef std::pair
<NamedDecl
*, CXXCtorInitializer
*> UnionEntry
;
2267 typedef llvm::DenseMap
<RecordDecl
*, UnionEntry
> RedundantUnionMap
;
2269 bool CheckRedundantUnionInit(Sema
&S
,
2270 CXXCtorInitializer
*Init
,
2271 RedundantUnionMap
&Unions
) {
2272 FieldDecl
*Field
= Init
->getAnyMember();
2273 RecordDecl
*Parent
= Field
->getParent();
2274 if (!Parent
->isAnonymousStructOrUnion())
2277 NamedDecl
*Child
= Field
;
2279 if (Parent
->isUnion()) {
2280 UnionEntry
&En
= Unions
[Parent
];
2281 if (En
.first
&& En
.first
!= Child
) {
2282 S
.Diag(Init
->getSourceLocation(),
2283 diag::err_multiple_mem_union_initialization
)
2284 << Field
->getDeclName()
2285 << Init
->getSourceRange();
2286 S
.Diag(En
.second
->getSourceLocation(), diag::note_previous_initializer
)
2287 << 0 << En
.second
->getSourceRange();
2289 } else if (!En
.first
) {
2296 Parent
= cast
<RecordDecl
>(Parent
->getDeclContext());
2297 } while (Parent
->isAnonymousStructOrUnion());
2303 /// ActOnMemInitializers - Handle the member initializers for a constructor.
2304 void Sema::ActOnMemInitializers(Decl
*ConstructorDecl
,
2305 SourceLocation ColonLoc
,
2306 MemInitTy
**meminits
, unsigned NumMemInits
,
2308 if (!ConstructorDecl
)
2311 AdjustDeclIfTemplate(ConstructorDecl
);
2313 CXXConstructorDecl
*Constructor
2314 = dyn_cast
<CXXConstructorDecl
>(ConstructorDecl
);
2317 Diag(ColonLoc
, diag::err_only_constructors_take_base_inits
);
2321 CXXCtorInitializer
**MemInits
=
2322 reinterpret_cast<CXXCtorInitializer
**>(meminits
);
2324 // Mapping for the duplicate initializers check.
2325 // For member initializers, this is keyed with a FieldDecl*.
2326 // For base initializers, this is keyed with a Type*.
2327 llvm::DenseMap
<void*, CXXCtorInitializer
*> Members
;
2329 // Mapping for the inconsistent anonymous-union initializers check.
2330 RedundantUnionMap MemberUnions
;
2332 bool HadError
= false;
2333 for (unsigned i
= 0; i
< NumMemInits
; i
++) {
2334 CXXCtorInitializer
*Init
= MemInits
[i
];
2336 // Set the source order index.
2337 Init
->setSourceOrder(i
);
2339 if (Init
->isAnyMemberInitializer()) {
2340 FieldDecl
*Field
= Init
->getAnyMember();
2341 if (CheckRedundantInit(*this, Init
, Members
[Field
]) ||
2342 CheckRedundantUnionInit(*this, Init
, MemberUnions
))
2345 void *Key
= GetKeyForBase(Context
, QualType(Init
->getBaseClass(), 0));
2346 if (CheckRedundantInit(*this, Init
, Members
[Key
]))
2354 DiagnoseBaseOrMemInitializerOrder(*this, Constructor
, MemInits
, NumMemInits
);
2356 SetCtorInitializers(Constructor
, MemInits
, NumMemInits
, AnyErrors
);
2360 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location
,
2361 CXXRecordDecl
*ClassDecl
) {
2362 // Ignore dependent contexts.
2363 if (ClassDecl
->isDependentContext())
2366 // FIXME: all the access-control diagnostics are positioned on the
2367 // field/base declaration. That's probably good; that said, the
2368 // user might reasonably want to know why the destructor is being
2369 // emitted, and we currently don't say.
2371 // Non-static data members.
2372 for (CXXRecordDecl::field_iterator I
= ClassDecl
->field_begin(),
2373 E
= ClassDecl
->field_end(); I
!= E
; ++I
) {
2374 FieldDecl
*Field
= *I
;
2375 if (Field
->isInvalidDecl())
2377 QualType FieldType
= Context
.getBaseElementType(Field
->getType());
2379 const RecordType
* RT
= FieldType
->getAs
<RecordType
>();
2383 CXXRecordDecl
*FieldClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
2384 if (FieldClassDecl
->hasTrivialDestructor())
2387 CXXDestructorDecl
*Dtor
= LookupDestructor(FieldClassDecl
);
2388 CheckDestructorAccess(Field
->getLocation(), Dtor
,
2389 PDiag(diag::err_access_dtor_field
)
2390 << Field
->getDeclName()
2393 MarkDeclarationReferenced(Location
, const_cast<CXXDestructorDecl
*>(Dtor
));
2396 llvm::SmallPtrSet
<const RecordType
*, 8> DirectVirtualBases
;
2399 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
2400 E
= ClassDecl
->bases_end(); Base
!= E
; ++Base
) {
2401 // Bases are always records in a well-formed non-dependent class.
2402 const RecordType
*RT
= Base
->getType()->getAs
<RecordType
>();
2404 // Remember direct virtual bases.
2405 if (Base
->isVirtual())
2406 DirectVirtualBases
.insert(RT
);
2408 // Ignore trivial destructors.
2409 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
2410 if (BaseClassDecl
->hasTrivialDestructor())
2413 CXXDestructorDecl
*Dtor
= LookupDestructor(BaseClassDecl
);
2415 // FIXME: caret should be on the start of the class name
2416 CheckDestructorAccess(Base
->getSourceRange().getBegin(), Dtor
,
2417 PDiag(diag::err_access_dtor_base
)
2419 << Base
->getSourceRange());
2421 MarkDeclarationReferenced(Location
, const_cast<CXXDestructorDecl
*>(Dtor
));
2425 for (CXXRecordDecl::base_class_iterator VBase
= ClassDecl
->vbases_begin(),
2426 E
= ClassDecl
->vbases_end(); VBase
!= E
; ++VBase
) {
2428 // Bases are always records in a well-formed non-dependent class.
2429 const RecordType
*RT
= VBase
->getType()->getAs
<RecordType
>();
2431 // Ignore direct virtual bases.
2432 if (DirectVirtualBases
.count(RT
))
2435 // Ignore trivial destructors.
2436 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
2437 if (BaseClassDecl
->hasTrivialDestructor())
2440 CXXDestructorDecl
*Dtor
= LookupDestructor(BaseClassDecl
);
2441 CheckDestructorAccess(ClassDecl
->getLocation(), Dtor
,
2442 PDiag(diag::err_access_dtor_vbase
)
2443 << VBase
->getType());
2445 MarkDeclarationReferenced(Location
, const_cast<CXXDestructorDecl
*>(Dtor
));
2449 void Sema::ActOnDefaultCtorInitializers(Decl
*CDtorDecl
) {
2453 if (CXXConstructorDecl
*Constructor
2454 = dyn_cast
<CXXConstructorDecl
>(CDtorDecl
))
2455 SetCtorInitializers(Constructor
, 0, 0, /*AnyErrors=*/false);
2458 bool Sema::RequireNonAbstractType(SourceLocation Loc
, QualType T
,
2459 unsigned DiagID
, AbstractDiagSelID SelID
) {
2461 return RequireNonAbstractType(Loc
, T
, PDiag(DiagID
));
2463 return RequireNonAbstractType(Loc
, T
, PDiag(DiagID
) << SelID
);
2466 bool Sema::RequireNonAbstractType(SourceLocation Loc
, QualType T
,
2467 const PartialDiagnostic
&PD
) {
2468 if (!getLangOptions().CPlusPlus
)
2471 if (const ArrayType
*AT
= Context
.getAsArrayType(T
))
2472 return RequireNonAbstractType(Loc
, AT
->getElementType(), PD
);
2474 if (const PointerType
*PT
= T
->getAs
<PointerType
>()) {
2475 // Find the innermost pointer type.
2476 while (const PointerType
*T
= PT
->getPointeeType()->getAs
<PointerType
>())
2479 if (const ArrayType
*AT
= Context
.getAsArrayType(PT
->getPointeeType()))
2480 return RequireNonAbstractType(Loc
, AT
->getElementType(), PD
);
2483 const RecordType
*RT
= T
->getAs
<RecordType
>();
2487 const CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RT
->getDecl());
2489 // We can't answer whether something is abstract until it has a
2490 // definition. If it's currently being defined, we'll walk back
2491 // over all the declarations when we have a full definition.
2492 const CXXRecordDecl
*Def
= RD
->getDefinition();
2493 if (!Def
|| Def
->isBeingDefined())
2496 if (!RD
->isAbstract())
2499 Diag(Loc
, PD
) << RD
->getDeclName();
2500 DiagnoseAbstractType(RD
);
2505 void Sema::DiagnoseAbstractType(const CXXRecordDecl
*RD
) {
2506 // Check if we've already emitted the list of pure virtual functions
2508 if (PureVirtualClassDiagSet
&& PureVirtualClassDiagSet
->count(RD
))
2511 CXXFinalOverriderMap FinalOverriders
;
2512 RD
->getFinalOverriders(FinalOverriders
);
2514 // Keep a set of seen pure methods so we won't diagnose the same method
2516 llvm::SmallPtrSet
<const CXXMethodDecl
*, 8> SeenPureMethods
;
2518 for (CXXFinalOverriderMap::iterator M
= FinalOverriders
.begin(),
2519 MEnd
= FinalOverriders
.end();
2522 for (OverridingMethods::iterator SO
= M
->second
.begin(),
2523 SOEnd
= M
->second
.end();
2524 SO
!= SOEnd
; ++SO
) {
2525 // C++ [class.abstract]p4:
2526 // A class is abstract if it contains or inherits at least one
2527 // pure virtual function for which the final overrider is pure
2531 if (SO
->second
.size() != 1)
2534 if (!SO
->second
.front().Method
->isPure())
2537 if (!SeenPureMethods
.insert(SO
->second
.front().Method
))
2540 Diag(SO
->second
.front().Method
->getLocation(),
2541 diag::note_pure_virtual_function
)
2542 << SO
->second
.front().Method
->getDeclName();
2546 if (!PureVirtualClassDiagSet
)
2547 PureVirtualClassDiagSet
.reset(new RecordDeclSetTy
);
2548 PureVirtualClassDiagSet
->insert(RD
);
2552 struct AbstractUsageInfo
{
2554 CXXRecordDecl
*Record
;
2555 CanQualType AbstractType
;
2558 AbstractUsageInfo(Sema
&S
, CXXRecordDecl
*Record
)
2559 : S(S
), Record(Record
),
2560 AbstractType(S
.Context
.getCanonicalType(
2561 S
.Context
.getTypeDeclType(Record
))),
2564 void DiagnoseAbstractType() {
2565 if (Invalid
) return;
2566 S
.DiagnoseAbstractType(Record
);
2570 void CheckType(const NamedDecl
*D
, TypeLoc TL
, Sema::AbstractDiagSelID Sel
);
2573 struct CheckAbstractUsage
{
2574 AbstractUsageInfo
&Info
;
2575 const NamedDecl
*Ctx
;
2577 CheckAbstractUsage(AbstractUsageInfo
&Info
, const NamedDecl
*Ctx
)
2578 : Info(Info
), Ctx(Ctx
) {}
2580 void Visit(TypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
2581 switch (TL
.getTypeLocClass()) {
2582 #define ABSTRACT_TYPELOC(CLASS, PARENT)
2583 #define TYPELOC(CLASS, PARENT) \
2584 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2585 #include "clang/AST/TypeLocNodes.def"
2589 void Check(FunctionProtoTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
2590 Visit(TL
.getResultLoc(), Sema::AbstractReturnType
);
2591 for (unsigned I
= 0, E
= TL
.getNumArgs(); I
!= E
; ++I
) {
2592 TypeSourceInfo
*TSI
= TL
.getArg(I
)->getTypeSourceInfo();
2593 if (TSI
) Visit(TSI
->getTypeLoc(), Sema::AbstractParamType
);
2597 void Check(ArrayTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
2598 Visit(TL
.getElementLoc(), Sema::AbstractArrayType
);
2601 void Check(TemplateSpecializationTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
2602 // Visit the type parameters from a permissive context.
2603 for (unsigned I
= 0, E
= TL
.getNumArgs(); I
!= E
; ++I
) {
2604 TemplateArgumentLoc TAL
= TL
.getArgLoc(I
);
2605 if (TAL
.getArgument().getKind() == TemplateArgument::Type
)
2606 if (TypeSourceInfo
*TSI
= TAL
.getTypeSourceInfo())
2607 Visit(TSI
->getTypeLoc(), Sema::AbstractNone
);
2608 // TODO: other template argument types?
2612 // Visit pointee types from a permissive context.
2613 #define CheckPolymorphic(Type) \
2614 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2615 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2617 CheckPolymorphic(PointerTypeLoc
)
2618 CheckPolymorphic(ReferenceTypeLoc
)
2619 CheckPolymorphic(MemberPointerTypeLoc
)
2620 CheckPolymorphic(BlockPointerTypeLoc
)
2622 /// Handle all the types we haven't given a more specific
2623 /// implementation for above.
2624 void Check(TypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
2625 // Every other kind of type that we haven't called out already
2626 // that has an inner type is either (1) sugar or (2) contains that
2627 // inner type in some way as a subobject.
2628 if (TypeLoc Next
= TL
.getNextTypeLoc())
2629 return Visit(Next
, Sel
);
2631 // If there's no inner type and we're in a permissive context,
2633 if (Sel
== Sema::AbstractNone
) return;
2635 // Check whether the type matches the abstract type.
2636 QualType T
= TL
.getType();
2637 if (T
->isArrayType()) {
2638 Sel
= Sema::AbstractArrayType
;
2639 T
= Info
.S
.Context
.getBaseElementType(T
);
2641 CanQualType CT
= T
->getCanonicalTypeUnqualified().getUnqualifiedType();
2642 if (CT
!= Info
.AbstractType
) return;
2644 // It matched; do some magic.
2645 if (Sel
== Sema::AbstractArrayType
) {
2646 Info
.S
.Diag(Ctx
->getLocation(), diag::err_array_of_abstract_type
)
2647 << T
<< TL
.getSourceRange();
2649 Info
.S
.Diag(Ctx
->getLocation(), diag::err_abstract_type_in_decl
)
2650 << Sel
<< T
<< TL
.getSourceRange();
2652 Info
.DiagnoseAbstractType();
2656 void AbstractUsageInfo::CheckType(const NamedDecl
*D
, TypeLoc TL
,
2657 Sema::AbstractDiagSelID Sel
) {
2658 CheckAbstractUsage(*this, D
).Visit(TL
, Sel
);
2663 /// Check for invalid uses of an abstract type in a method declaration.
2664 static void CheckAbstractClassUsage(AbstractUsageInfo
&Info
,
2665 CXXMethodDecl
*MD
) {
2666 // No need to do the check on definitions, which require that
2667 // the return/param types be complete.
2668 if (MD
->isThisDeclarationADefinition())
2671 // For safety's sake, just ignore it if we don't have type source
2672 // information. This should never happen for non-implicit methods,
2674 if (TypeSourceInfo
*TSI
= MD
->getTypeSourceInfo())
2675 Info
.CheckType(MD
, TSI
->getTypeLoc(), Sema::AbstractNone
);
2678 /// Check for invalid uses of an abstract type within a class definition.
2679 static void CheckAbstractClassUsage(AbstractUsageInfo
&Info
,
2680 CXXRecordDecl
*RD
) {
2681 for (CXXRecordDecl::decl_iterator
2682 I
= RD
->decls_begin(), E
= RD
->decls_end(); I
!= E
; ++I
) {
2684 if (D
->isImplicit()) continue;
2686 // Methods and method templates.
2687 if (isa
<CXXMethodDecl
>(D
)) {
2688 CheckAbstractClassUsage(Info
, cast
<CXXMethodDecl
>(D
));
2689 } else if (isa
<FunctionTemplateDecl
>(D
)) {
2690 FunctionDecl
*FD
= cast
<FunctionTemplateDecl
>(D
)->getTemplatedDecl();
2691 CheckAbstractClassUsage(Info
, cast
<CXXMethodDecl
>(FD
));
2693 // Fields and static variables.
2694 } else if (isa
<FieldDecl
>(D
)) {
2695 FieldDecl
*FD
= cast
<FieldDecl
>(D
);
2696 if (TypeSourceInfo
*TSI
= FD
->getTypeSourceInfo())
2697 Info
.CheckType(FD
, TSI
->getTypeLoc(), Sema::AbstractFieldType
);
2698 } else if (isa
<VarDecl
>(D
)) {
2699 VarDecl
*VD
= cast
<VarDecl
>(D
);
2700 if (TypeSourceInfo
*TSI
= VD
->getTypeSourceInfo())
2701 Info
.CheckType(VD
, TSI
->getTypeLoc(), Sema::AbstractVariableType
);
2703 // Nested classes and class templates.
2704 } else if (isa
<CXXRecordDecl
>(D
)) {
2705 CheckAbstractClassUsage(Info
, cast
<CXXRecordDecl
>(D
));
2706 } else if (isa
<ClassTemplateDecl
>(D
)) {
2707 CheckAbstractClassUsage(Info
,
2708 cast
<ClassTemplateDecl
>(D
)->getTemplatedDecl());
2713 /// \brief Perform semantic checks on a class definition that has been
2714 /// completing, introducing implicitly-declared members, checking for
2715 /// abstract types, etc.
2716 void Sema::CheckCompletedCXXClass(CXXRecordDecl
*Record
) {
2720 if (Record
->isAbstract() && !Record
->isInvalidDecl()) {
2721 AbstractUsageInfo
Info(*this, Record
);
2722 CheckAbstractClassUsage(Info
, Record
);
2725 // If this is not an aggregate type and has no user-declared constructor,
2726 // complain about any non-static data members of reference or const scalar
2727 // type, since they will never get initializers.
2728 if (!Record
->isInvalidDecl() && !Record
->isDependentType() &&
2729 !Record
->isAggregate() && !Record
->hasUserDeclaredConstructor()) {
2730 bool Complained
= false;
2731 for (RecordDecl::field_iterator F
= Record
->field_begin(),
2732 FEnd
= Record
->field_end();
2734 if (F
->getType()->isReferenceType() ||
2735 (F
->getType().isConstQualified() && F
->getType()->isScalarType())) {
2737 Diag(Record
->getLocation(), diag::warn_no_constructor_for_refconst
)
2738 << Record
->getTagKind() << Record
;
2742 Diag(F
->getLocation(), diag::note_refconst_member_not_initialized
)
2743 << F
->getType()->isReferenceType()
2744 << F
->getDeclName();
2749 if (Record
->isDynamicClass() && !Record
->isDependentType())
2750 DynamicClasses
.push_back(Record
);
2752 if (Record
->getIdentifier()) {
2753 // C++ [class.mem]p13:
2754 // If T is the name of a class, then each of the following shall have a
2755 // name different from T:
2756 // - every member of every anonymous union that is a member of class T.
2758 // C++ [class.mem]p14:
2759 // In addition, if class T has a user-declared constructor (12.1), every
2760 // non-static data member of class T shall have a name different from T.
2761 for (DeclContext::lookup_result R
= Record
->lookup(Record
->getDeclName());
2762 R
.first
!= R
.second
; ++R
.first
) {
2763 NamedDecl
*D
= *R
.first
;
2764 if ((isa
<FieldDecl
>(D
) && Record
->hasUserDeclaredConstructor()) ||
2765 isa
<IndirectFieldDecl
>(D
)) {
2766 Diag(D
->getLocation(), diag::err_member_name_of_class
)
2767 << D
->getDeclName();
2773 // Warn if the class has virtual methods but non-virtual public destructor.
2774 if (Record
->isDynamicClass()) {
2775 CXXDestructorDecl
*dtor
= Record
->getDestructor();
2776 if (!dtor
|| (!dtor
->isVirtual() && dtor
->getAccess() == AS_public
))
2777 Diag(dtor
? dtor
->getLocation() : Record
->getLocation(),
2778 diag::warn_non_virtual_dtor
) << Context
.getRecordType(Record
);
2782 void Sema::ActOnFinishCXXMemberSpecification(Scope
* S
, SourceLocation RLoc
,
2784 SourceLocation LBrac
,
2785 SourceLocation RBrac
,
2786 AttributeList
*AttrList
) {
2790 AdjustDeclIfTemplate(TagDecl
);
2792 ActOnFields(S
, RLoc
, TagDecl
,
2793 // strict aliasing violation!
2794 reinterpret_cast<Decl
**>(FieldCollector
->getCurFields()),
2795 FieldCollector
->getCurNumFields(), LBrac
, RBrac
, AttrList
);
2797 CheckCompletedCXXClass(
2798 dyn_cast_or_null
<CXXRecordDecl
>(TagDecl
));
2802 /// \brief Helper class that collects exception specifications for
2803 /// implicitly-declared special member functions.
2804 class ImplicitExceptionSpecification
{
2805 ASTContext
&Context
;
2806 bool AllowsAllExceptions
;
2807 llvm::SmallPtrSet
<CanQualType
, 4> ExceptionsSeen
;
2808 llvm::SmallVector
<QualType
, 4> Exceptions
;
2811 explicit ImplicitExceptionSpecification(ASTContext
&Context
)
2812 : Context(Context
), AllowsAllExceptions(false) { }
2814 /// \brief Whether the special member function should have any
2815 /// exception specification at all.
2816 bool hasExceptionSpecification() const {
2817 return !AllowsAllExceptions
;
2820 /// \brief Whether the special member function should have a
2821 /// throw(...) exception specification (a Microsoft extension).
2822 bool hasAnyExceptionSpecification() const {
2826 /// \brief The number of exceptions in the exception specification.
2827 unsigned size() const { return Exceptions
.size(); }
2829 /// \brief The set of exceptions in the exception specification.
2830 const QualType
*data() const { return Exceptions
.data(); }
2832 /// \brief Note that
2833 void CalledDecl(CXXMethodDecl
*Method
) {
2834 // If we already know that we allow all exceptions, do nothing.
2835 if (AllowsAllExceptions
|| !Method
)
2838 const FunctionProtoType
*Proto
2839 = Method
->getType()->getAs
<FunctionProtoType
>();
2841 // If this function can throw any exceptions, make a note of that.
2842 if (!Proto
->hasExceptionSpec() || Proto
->hasAnyExceptionSpec()) {
2843 AllowsAllExceptions
= true;
2844 ExceptionsSeen
.clear();
2849 // Record the exceptions in this function's exception specification.
2850 for (FunctionProtoType::exception_iterator E
= Proto
->exception_begin(),
2851 EEnd
= Proto
->exception_end();
2853 if (ExceptionsSeen
.insert(Context
.getCanonicalType(*E
)))
2854 Exceptions
.push_back(*E
);
2860 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2861 /// special functions, such as the default constructor, copy
2862 /// constructor, or destructor, to the given C++ class (C++
2863 /// [special]p1). This routine can only be executed just before the
2864 /// definition of the class is complete.
2865 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl
*ClassDecl
) {
2866 if (!ClassDecl
->hasUserDeclaredConstructor())
2867 ++ASTContext::NumImplicitDefaultConstructors
;
2869 if (!ClassDecl
->hasUserDeclaredCopyConstructor())
2870 ++ASTContext::NumImplicitCopyConstructors
;
2872 if (!ClassDecl
->hasUserDeclaredCopyAssignment()) {
2873 ++ASTContext::NumImplicitCopyAssignmentOperators
;
2875 // If we have a dynamic class, then the copy assignment operator may be
2876 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2877 // it shows up in the right place in the vtable and that we diagnose
2878 // problems with the implicit exception specification.
2879 if (ClassDecl
->isDynamicClass())
2880 DeclareImplicitCopyAssignment(ClassDecl
);
2883 if (!ClassDecl
->hasUserDeclaredDestructor()) {
2884 ++ASTContext::NumImplicitDestructors
;
2886 // If we have a dynamic class, then the destructor may be virtual, so we
2887 // have to declare the destructor immediately. This ensures that, e.g., it
2888 // shows up in the right place in the vtable and that we diagnose problems
2889 // with the implicit exception specification.
2890 if (ClassDecl
->isDynamicClass())
2891 DeclareImplicitDestructor(ClassDecl
);
2895 void Sema::ActOnReenterTemplateScope(Scope
*S
, Decl
*D
) {
2899 TemplateParameterList
*Params
= 0;
2900 if (TemplateDecl
*Template
= dyn_cast
<TemplateDecl
>(D
))
2901 Params
= Template
->getTemplateParameters();
2902 else if (ClassTemplatePartialSpecializationDecl
*PartialSpec
2903 = dyn_cast
<ClassTemplatePartialSpecializationDecl
>(D
))
2904 Params
= PartialSpec
->getTemplateParameters();
2908 for (TemplateParameterList::iterator Param
= Params
->begin(),
2909 ParamEnd
= Params
->end();
2910 Param
!= ParamEnd
; ++Param
) {
2911 NamedDecl
*Named
= cast
<NamedDecl
>(*Param
);
2912 if (Named
->getDeclName()) {
2914 IdResolver
.AddDecl(Named
);
2919 void Sema::ActOnStartDelayedMemberDeclarations(Scope
*S
, Decl
*RecordD
) {
2920 if (!RecordD
) return;
2921 AdjustDeclIfTemplate(RecordD
);
2922 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(RecordD
);
2923 PushDeclContext(S
, Record
);
2926 void Sema::ActOnFinishDelayedMemberDeclarations(Scope
*S
, Decl
*RecordD
) {
2927 if (!RecordD
) return;
2931 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
2932 /// parsing a top-level (non-nested) C++ class, and we are now
2933 /// parsing those parts of the given Method declaration that could
2934 /// not be parsed earlier (C++ [class.mem]p2), such as default
2935 /// arguments. This action should enter the scope of the given
2936 /// Method declaration as if we had just parsed the qualified method
2937 /// name. However, it should not bring the parameters into scope;
2938 /// that will be performed by ActOnDelayedCXXMethodParameter.
2939 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope
*S
, Decl
*MethodD
) {
2942 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
2943 /// C++ method declaration. We're (re-)introducing the given
2944 /// function parameter into scope for use in parsing later parts of
2945 /// the method declaration. For example, we could see an
2946 /// ActOnParamDefaultArgument event for this parameter.
2947 void Sema::ActOnDelayedCXXMethodParameter(Scope
*S
, Decl
*ParamD
) {
2951 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(ParamD
);
2953 // If this parameter has an unparsed default argument, clear it out
2954 // to make way for the parsed default argument.
2955 if (Param
->hasUnparsedDefaultArg())
2956 Param
->setDefaultArg(0);
2959 if (Param
->getDeclName())
2960 IdResolver
.AddDecl(Param
);
2963 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
2964 /// processing the delayed method declaration for Method. The method
2965 /// declaration is now considered finished. There may be a separate
2966 /// ActOnStartOfFunctionDef action later (not necessarily
2967 /// immediately!) for this method, if it was also defined inside the
2969 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope
*S
, Decl
*MethodD
) {
2973 AdjustDeclIfTemplate(MethodD
);
2975 FunctionDecl
*Method
= cast
<FunctionDecl
>(MethodD
);
2977 // Now that we have our default arguments, check the constructor
2978 // again. It could produce additional diagnostics or affect whether
2979 // the class has implicitly-declared destructors, among other
2981 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Method
))
2982 CheckConstructor(Constructor
);
2984 // Check the default arguments, which we may have added.
2985 if (!Method
->isInvalidDecl())
2986 CheckCXXDefaultArguments(Method
);
2989 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
2990 /// the well-formedness of the constructor declarator @p D with type @p
2991 /// R. If there are any errors in the declarator, this routine will
2992 /// emit diagnostics and set the invalid bit to true. In any case, the type
2993 /// will be updated to reflect a well-formed type for the constructor and
2995 QualType
Sema::CheckConstructorDeclarator(Declarator
&D
, QualType R
,
2997 bool isVirtual
= D
.getDeclSpec().isVirtualSpecified();
2999 // C++ [class.ctor]p3:
3000 // A constructor shall not be virtual (10.3) or static (9.4). A
3001 // constructor can be invoked for a const, volatile or const
3002 // volatile object. A constructor shall not be declared const,
3003 // volatile, or const volatile (9.3.2).
3005 if (!D
.isInvalidType())
3006 Diag(D
.getIdentifierLoc(), diag::err_constructor_cannot_be
)
3007 << "virtual" << SourceRange(D
.getDeclSpec().getVirtualSpecLoc())
3008 << SourceRange(D
.getIdentifierLoc());
3011 if (SC
== SC_Static
) {
3012 if (!D
.isInvalidType())
3013 Diag(D
.getIdentifierLoc(), diag::err_constructor_cannot_be
)
3014 << "static" << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
3015 << SourceRange(D
.getIdentifierLoc());
3020 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
3021 if (FTI
.TypeQuals
!= 0) {
3022 if (FTI
.TypeQuals
& Qualifiers::Const
)
3023 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_constructor
)
3024 << "const" << SourceRange(D
.getIdentifierLoc());
3025 if (FTI
.TypeQuals
& Qualifiers::Volatile
)
3026 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_constructor
)
3027 << "volatile" << SourceRange(D
.getIdentifierLoc());
3028 if (FTI
.TypeQuals
& Qualifiers::Restrict
)
3029 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_constructor
)
3030 << "restrict" << SourceRange(D
.getIdentifierLoc());
3034 // C++0x [class.ctor]p4:
3035 // A constructor shall not be declared with a ref-qualifier.
3036 if (FTI
.hasRefQualifier()) {
3037 Diag(FTI
.getRefQualifierLoc(), diag::err_ref_qualifier_constructor
)
3038 << FTI
.RefQualifierIsLValueRef
3039 << FixItHint::CreateRemoval(FTI
.getRefQualifierLoc());
3043 // Rebuild the function type "R" without any type qualifiers (in
3044 // case any of the errors above fired) and with "void" as the
3045 // return type, since constructors don't have return types.
3046 const FunctionProtoType
*Proto
= R
->getAs
<FunctionProtoType
>();
3047 if (Proto
->getResultType() == Context
.VoidTy
&& !D
.isInvalidType())
3050 FunctionProtoType::ExtProtoInfo EPI
= Proto
->getExtProtoInfo();
3052 EPI
.RefQualifier
= RQ_None
;
3054 return Context
.getFunctionType(Context
.VoidTy
, Proto
->arg_type_begin(),
3055 Proto
->getNumArgs(), EPI
);
3058 /// CheckConstructor - Checks a fully-formed constructor for
3059 /// well-formedness, issuing any diagnostics required. Returns true if
3060 /// the constructor declarator is invalid.
3061 void Sema::CheckConstructor(CXXConstructorDecl
*Constructor
) {
3062 CXXRecordDecl
*ClassDecl
3063 = dyn_cast
<CXXRecordDecl
>(Constructor
->getDeclContext());
3065 return Constructor
->setInvalidDecl();
3067 // C++ [class.copy]p3:
3068 // A declaration of a constructor for a class X is ill-formed if
3069 // its first parameter is of type (optionally cv-qualified) X and
3070 // either there are no other parameters or else all other
3071 // parameters have default arguments.
3072 if (!Constructor
->isInvalidDecl() &&
3073 ((Constructor
->getNumParams() == 1) ||
3074 (Constructor
->getNumParams() > 1 &&
3075 Constructor
->getParamDecl(1)->hasDefaultArg())) &&
3076 Constructor
->getTemplateSpecializationKind()
3077 != TSK_ImplicitInstantiation
) {
3078 QualType ParamType
= Constructor
->getParamDecl(0)->getType();
3079 QualType ClassTy
= Context
.getTagDeclType(ClassDecl
);
3080 if (Context
.getCanonicalType(ParamType
).getUnqualifiedType() == ClassTy
) {
3081 SourceLocation ParamLoc
= Constructor
->getParamDecl(0)->getLocation();
3082 const char *ConstRef
3083 = Constructor
->getParamDecl(0)->getIdentifier() ? "const &"
3085 Diag(ParamLoc
, diag::err_constructor_byvalue_arg
)
3086 << FixItHint::CreateInsertion(ParamLoc
, ConstRef
);
3088 // FIXME: Rather that making the constructor invalid, we should endeavor
3090 Constructor
->setInvalidDecl();
3095 /// CheckDestructor - Checks a fully-formed destructor definition for
3096 /// well-formedness, issuing any diagnostics required. Returns true
3098 bool Sema::CheckDestructor(CXXDestructorDecl
*Destructor
) {
3099 CXXRecordDecl
*RD
= Destructor
->getParent();
3101 if (Destructor
->isVirtual()) {
3104 if (!Destructor
->isImplicit())
3105 Loc
= Destructor
->getLocation();
3107 Loc
= RD
->getLocation();
3109 // If we have a virtual destructor, look up the deallocation function
3110 FunctionDecl
*OperatorDelete
= 0;
3111 DeclarationName Name
=
3112 Context
.DeclarationNames
.getCXXOperatorName(OO_Delete
);
3113 if (FindDeallocationFunction(Loc
, RD
, Name
, OperatorDelete
))
3116 MarkDeclarationReferenced(Loc
, OperatorDelete
);
3118 Destructor
->setOperatorDelete(OperatorDelete
);
3125 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo
&FTI
) {
3126 return (FTI
.NumArgs
== 1 && !FTI
.isVariadic
&& FTI
.ArgInfo
[0].Ident
== 0 &&
3127 FTI
.ArgInfo
[0].Param
&&
3128 cast
<ParmVarDecl
>(FTI
.ArgInfo
[0].Param
)->getType()->isVoidType());
3131 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3132 /// the well-formednes of the destructor declarator @p D with type @p
3133 /// R. If there are any errors in the declarator, this routine will
3134 /// emit diagnostics and set the declarator to invalid. Even if this happens,
3135 /// will be updated to reflect a well-formed type for the destructor and
3137 QualType
Sema::CheckDestructorDeclarator(Declarator
&D
, QualType R
,
3139 // C++ [class.dtor]p1:
3140 // [...] A typedef-name that names a class is a class-name
3141 // (7.1.3); however, a typedef-name that names a class shall not
3142 // be used as the identifier in the declarator for a destructor
3144 QualType DeclaratorType
= GetTypeFromParser(D
.getName().DestructorName
);
3145 if (isa
<TypedefType
>(DeclaratorType
))
3146 Diag(D
.getIdentifierLoc(), diag::err_destructor_typedef_name
)
3149 // C++ [class.dtor]p2:
3150 // A destructor is used to destroy objects of its class type. A
3151 // destructor takes no parameters, and no return type can be
3152 // specified for it (not even void). The address of a destructor
3153 // shall not be taken. A destructor shall not be static. A
3154 // destructor can be invoked for a const, volatile or const
3155 // volatile object. A destructor shall not be declared const,
3156 // volatile or const volatile (9.3.2).
3157 if (SC
== SC_Static
) {
3158 if (!D
.isInvalidType())
3159 Diag(D
.getIdentifierLoc(), diag::err_destructor_cannot_be
)
3160 << "static" << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
3161 << SourceRange(D
.getIdentifierLoc())
3162 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
3166 if (D
.getDeclSpec().hasTypeSpecifier() && !D
.isInvalidType()) {
3167 // Destructors don't have return types, but the parser will
3168 // happily parse something like:
3174 // The return type will be eliminated later.
3175 Diag(D
.getIdentifierLoc(), diag::err_destructor_return_type
)
3176 << SourceRange(D
.getDeclSpec().getTypeSpecTypeLoc())
3177 << SourceRange(D
.getIdentifierLoc());
3180 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
3181 if (FTI
.TypeQuals
!= 0 && !D
.isInvalidType()) {
3182 if (FTI
.TypeQuals
& Qualifiers::Const
)
3183 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_destructor
)
3184 << "const" << SourceRange(D
.getIdentifierLoc());
3185 if (FTI
.TypeQuals
& Qualifiers::Volatile
)
3186 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_destructor
)
3187 << "volatile" << SourceRange(D
.getIdentifierLoc());
3188 if (FTI
.TypeQuals
& Qualifiers::Restrict
)
3189 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_destructor
)
3190 << "restrict" << SourceRange(D
.getIdentifierLoc());
3194 // C++0x [class.dtor]p2:
3195 // A destructor shall not be declared with a ref-qualifier.
3196 if (FTI
.hasRefQualifier()) {
3197 Diag(FTI
.getRefQualifierLoc(), diag::err_ref_qualifier_destructor
)
3198 << FTI
.RefQualifierIsLValueRef
3199 << FixItHint::CreateRemoval(FTI
.getRefQualifierLoc());
3203 // Make sure we don't have any parameters.
3204 if (FTI
.NumArgs
> 0 && !FTIHasSingleVoidArgument(FTI
)) {
3205 Diag(D
.getIdentifierLoc(), diag::err_destructor_with_params
);
3207 // Delete the parameters.
3212 // Make sure the destructor isn't variadic.
3213 if (FTI
.isVariadic
) {
3214 Diag(D
.getIdentifierLoc(), diag::err_destructor_variadic
);
3218 // Rebuild the function type "R" without any type qualifiers or
3219 // parameters (in case any of the errors above fired) and with
3220 // "void" as the return type, since destructors don't have return
3222 if (!D
.isInvalidType())
3225 const FunctionProtoType
*Proto
= R
->getAs
<FunctionProtoType
>();
3226 FunctionProtoType::ExtProtoInfo EPI
= Proto
->getExtProtoInfo();
3227 EPI
.Variadic
= false;
3229 EPI
.RefQualifier
= RQ_None
;
3230 return Context
.getFunctionType(Context
.VoidTy
, 0, 0, EPI
);
3233 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3234 /// well-formednes of the conversion function declarator @p D with
3235 /// type @p R. If there are any errors in the declarator, this routine
3236 /// will emit diagnostics and return true. Otherwise, it will return
3237 /// false. Either way, the type @p R will be updated to reflect a
3238 /// well-formed type for the conversion operator.
3239 void Sema::CheckConversionDeclarator(Declarator
&D
, QualType
&R
,
3241 // C++ [class.conv.fct]p1:
3242 // Neither parameter types nor return type can be specified. The
3243 // type of a conversion function (8.3.5) is "function taking no
3244 // parameter returning conversion-type-id."
3245 if (SC
== SC_Static
) {
3246 if (!D
.isInvalidType())
3247 Diag(D
.getIdentifierLoc(), diag::err_conv_function_not_member
)
3248 << "static" << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
3249 << SourceRange(D
.getIdentifierLoc());
3254 QualType ConvType
= GetTypeFromParser(D
.getName().ConversionFunctionId
);
3256 if (D
.getDeclSpec().hasTypeSpecifier() && !D
.isInvalidType()) {
3257 // Conversion functions don't have return types, but the parser will
3258 // happily parse something like:
3261 // float operator bool();
3264 // The return type will be changed later anyway.
3265 Diag(D
.getIdentifierLoc(), diag::err_conv_function_return_type
)
3266 << SourceRange(D
.getDeclSpec().getTypeSpecTypeLoc())
3267 << SourceRange(D
.getIdentifierLoc());
3271 const FunctionProtoType
*Proto
= R
->getAs
<FunctionProtoType
>();
3273 // Make sure we don't have any parameters.
3274 if (Proto
->getNumArgs() > 0) {
3275 Diag(D
.getIdentifierLoc(), diag::err_conv_function_with_params
);
3277 // Delete the parameters.
3278 D
.getFunctionTypeInfo().freeArgs();
3280 } else if (Proto
->isVariadic()) {
3281 Diag(D
.getIdentifierLoc(), diag::err_conv_function_variadic
);
3285 // Diagnose "&operator bool()" and other such nonsense. This
3286 // is actually a gcc extension which we don't support.
3287 if (Proto
->getResultType() != ConvType
) {
3288 Diag(D
.getIdentifierLoc(), diag::err_conv_function_with_complex_decl
)
3289 << Proto
->getResultType();
3291 ConvType
= Proto
->getResultType();
3294 // C++ [class.conv.fct]p4:
3295 // The conversion-type-id shall not represent a function type nor
3297 if (ConvType
->isArrayType()) {
3298 Diag(D
.getIdentifierLoc(), diag::err_conv_function_to_array
);
3299 ConvType
= Context
.getPointerType(ConvType
);
3301 } else if (ConvType
->isFunctionType()) {
3302 Diag(D
.getIdentifierLoc(), diag::err_conv_function_to_function
);
3303 ConvType
= Context
.getPointerType(ConvType
);
3307 // Rebuild the function type "R" without any parameters (in case any
3308 // of the errors above fired) and with the conversion type as the
3310 if (D
.isInvalidType())
3311 R
= Context
.getFunctionType(ConvType
, 0, 0, Proto
->getExtProtoInfo());
3313 // C++0x explicit conversion operators.
3314 if (D
.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x
)
3315 Diag(D
.getDeclSpec().getExplicitSpecLoc(),
3316 diag::warn_explicit_conversion_functions
)
3317 << SourceRange(D
.getDeclSpec().getExplicitSpecLoc());
3320 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3321 /// the declaration of the given C++ conversion function. This routine
3322 /// is responsible for recording the conversion function in the C++
3323 /// class, if possible.
3324 Decl
*Sema::ActOnConversionDeclarator(CXXConversionDecl
*Conversion
) {
3325 assert(Conversion
&& "Expected to receive a conversion function declaration");
3327 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(Conversion
->getDeclContext());
3329 // Make sure we aren't redeclaring the conversion function.
3330 QualType ConvType
= Context
.getCanonicalType(Conversion
->getConversionType());
3332 // C++ [class.conv.fct]p1:
3333 // [...] A conversion function is never used to convert a
3334 // (possibly cv-qualified) object to the (possibly cv-qualified)
3335 // same object type (or a reference to it), to a (possibly
3336 // cv-qualified) base class of that type (or a reference to it),
3337 // or to (possibly cv-qualified) void.
3338 // FIXME: Suppress this warning if the conversion function ends up being a
3339 // virtual function that overrides a virtual function in a base class.
3341 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
3342 if (const ReferenceType
*ConvTypeRef
= ConvType
->getAs
<ReferenceType
>())
3343 ConvType
= ConvTypeRef
->getPointeeType();
3344 if (Conversion
->getTemplateSpecializationKind() != TSK_Undeclared
&&
3345 Conversion
->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
)
3346 /* Suppress diagnostics for instantiations. */;
3347 else if (ConvType
->isRecordType()) {
3348 ConvType
= Context
.getCanonicalType(ConvType
).getUnqualifiedType();
3349 if (ConvType
== ClassType
)
3350 Diag(Conversion
->getLocation(), diag::warn_conv_to_self_not_used
)
3352 else if (IsDerivedFrom(ClassType
, ConvType
))
3353 Diag(Conversion
->getLocation(), diag::warn_conv_to_base_not_used
)
3354 << ClassType
<< ConvType
;
3355 } else if (ConvType
->isVoidType()) {
3356 Diag(Conversion
->getLocation(), diag::warn_conv_to_void_not_used
)
3357 << ClassType
<< ConvType
;
3360 if (FunctionTemplateDecl
*ConversionTemplate
3361 = Conversion
->getDescribedFunctionTemplate())
3362 return ConversionTemplate
;
3367 //===----------------------------------------------------------------------===//
3368 // Namespace Handling
3369 //===----------------------------------------------------------------------===//
3373 /// ActOnStartNamespaceDef - This is called at the start of a namespace
3375 Decl
*Sema::ActOnStartNamespaceDef(Scope
*NamespcScope
,
3376 SourceLocation InlineLoc
,
3377 SourceLocation IdentLoc
,
3379 SourceLocation LBrace
,
3380 AttributeList
*AttrList
) {
3381 // anonymous namespace starts at its left brace
3382 NamespaceDecl
*Namespc
= NamespaceDecl::Create(Context
, CurContext
,
3383 (II
? IdentLoc
: LBrace
) , II
);
3384 Namespc
->setLBracLoc(LBrace
);
3385 Namespc
->setInline(InlineLoc
.isValid());
3387 Scope
*DeclRegionScope
= NamespcScope
->getParent();
3389 ProcessDeclAttributeList(DeclRegionScope
, Namespc
, AttrList
);
3391 if (const VisibilityAttr
*Attr
= Namespc
->getAttr
<VisibilityAttr
>())
3392 PushNamespaceVisibilityAttr(Attr
);
3395 // C++ [namespace.def]p2:
3396 // The identifier in an original-namespace-definition shall not
3397 // have been previously defined in the declarative region in
3398 // which the original-namespace-definition appears. The
3399 // identifier in an original-namespace-definition is the name of
3400 // the namespace. Subsequently in that declarative region, it is
3401 // treated as an original-namespace-name.
3403 // Since namespace names are unique in their scope, and we don't
3404 // look through using directives, just
3405 DeclContext::lookup_result R
= CurContext
->getRedeclContext()->lookup(II
);
3406 NamedDecl
*PrevDecl
= R
.first
== R
.second
? 0 : *R
.first
;
3408 if (NamespaceDecl
*OrigNS
= dyn_cast_or_null
<NamespaceDecl
>(PrevDecl
)) {
3409 // This is an extended namespace definition.
3410 if (Namespc
->isInline() != OrigNS
->isInline()) {
3411 // inline-ness must match
3412 Diag(Namespc
->getLocation(), diag::err_inline_namespace_mismatch
)
3413 << Namespc
->isInline();
3414 Diag(OrigNS
->getLocation(), diag::note_previous_definition
);
3415 Namespc
->setInvalidDecl();
3416 // Recover by ignoring the new namespace's inline status.
3417 Namespc
->setInline(OrigNS
->isInline());
3420 // Attach this namespace decl to the chain of extended namespace
3422 OrigNS
->setNextNamespace(Namespc
);
3423 Namespc
->setOriginalNamespace(OrigNS
->getOriginalNamespace());
3425 // Remove the previous declaration from the scope.
3426 if (DeclRegionScope
->isDeclScope(OrigNS
)) {
3427 IdResolver
.RemoveDecl(OrigNS
);
3428 DeclRegionScope
->RemoveDecl(OrigNS
);
3430 } else if (PrevDecl
) {
3431 // This is an invalid name redefinition.
3432 Diag(Namespc
->getLocation(), diag::err_redefinition_different_kind
)
3433 << Namespc
->getDeclName();
3434 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
3435 Namespc
->setInvalidDecl();
3436 // Continue on to push Namespc as current DeclContext and return it.
3437 } else if (II
->isStr("std") &&
3438 CurContext
->getRedeclContext()->isTranslationUnit()) {
3439 // This is the first "real" definition of the namespace "std", so update
3440 // our cache of the "std" namespace to point at this definition.
3441 if (NamespaceDecl
*StdNS
= getStdNamespace()) {
3442 // We had already defined a dummy namespace "std". Link this new
3443 // namespace definition to the dummy namespace "std".
3444 StdNS
->setNextNamespace(Namespc
);
3445 StdNS
->setLocation(IdentLoc
);
3446 Namespc
->setOriginalNamespace(StdNS
->getOriginalNamespace());
3449 // Make our StdNamespace cache point at the first real definition of the
3451 StdNamespace
= Namespc
;
3454 PushOnScopeChains(Namespc
, DeclRegionScope
);
3456 // Anonymous namespaces.
3457 assert(Namespc
->isAnonymousNamespace());
3459 // Link the anonymous namespace into its parent.
3460 NamespaceDecl
*PrevDecl
;
3461 DeclContext
*Parent
= CurContext
->getRedeclContext();
3462 if (TranslationUnitDecl
*TU
= dyn_cast
<TranslationUnitDecl
>(Parent
)) {
3463 PrevDecl
= TU
->getAnonymousNamespace();
3464 TU
->setAnonymousNamespace(Namespc
);
3466 NamespaceDecl
*ND
= cast
<NamespaceDecl
>(Parent
);
3467 PrevDecl
= ND
->getAnonymousNamespace();
3468 ND
->setAnonymousNamespace(Namespc
);
3471 // Link the anonymous namespace with its previous declaration.
3473 assert(PrevDecl
->isAnonymousNamespace());
3474 assert(!PrevDecl
->getNextNamespace());
3475 Namespc
->setOriginalNamespace(PrevDecl
->getOriginalNamespace());
3476 PrevDecl
->setNextNamespace(Namespc
);
3478 if (Namespc
->isInline() != PrevDecl
->isInline()) {
3479 // inline-ness must match
3480 Diag(Namespc
->getLocation(), diag::err_inline_namespace_mismatch
)
3481 << Namespc
->isInline();
3482 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
3483 Namespc
->setInvalidDecl();
3484 // Recover by ignoring the new namespace's inline status.
3485 Namespc
->setInline(PrevDecl
->isInline());
3489 CurContext
->addDecl(Namespc
);
3491 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3492 // behaves as if it were replaced by
3493 // namespace unique { /* empty body */ }
3494 // using namespace unique;
3495 // namespace unique { namespace-body }
3496 // where all occurrences of 'unique' in a translation unit are
3497 // replaced by the same identifier and this identifier differs
3498 // from all other identifiers in the entire program.
3500 // We just create the namespace with an empty name and then add an
3501 // implicit using declaration, just like the standard suggests.
3503 // CodeGen enforces the "universally unique" aspect by giving all
3504 // declarations semantically contained within an anonymous
3505 // namespace internal linkage.
3508 UsingDirectiveDecl
* UD
3509 = UsingDirectiveDecl::Create(Context
, CurContext
,
3510 /* 'using' */ LBrace
,
3511 /* 'namespace' */ SourceLocation(),
3512 /* qualifier */ SourceRange(),
3514 /* identifier */ SourceLocation(),
3516 /* Ancestor */ CurContext
);
3518 CurContext
->addDecl(UD
);
3522 // Although we could have an invalid decl (i.e. the namespace name is a
3523 // redefinition), push it as current DeclContext and try to continue parsing.
3524 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3525 // for the namespace has the declarations that showed up in that particular
3526 // namespace definition.
3527 PushDeclContext(NamespcScope
, Namespc
);
3531 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3532 /// is a namespace alias, returns the namespace it points to.
3533 static inline NamespaceDecl
*getNamespaceDecl(NamedDecl
*D
) {
3534 if (NamespaceAliasDecl
*AD
= dyn_cast_or_null
<NamespaceAliasDecl
>(D
))
3535 return AD
->getNamespace();
3536 return dyn_cast_or_null
<NamespaceDecl
>(D
);
3539 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
3540 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
3541 void Sema::ActOnFinishNamespaceDef(Decl
*Dcl
, SourceLocation RBrace
) {
3542 NamespaceDecl
*Namespc
= dyn_cast_or_null
<NamespaceDecl
>(Dcl
);
3543 assert(Namespc
&& "Invalid parameter, expected NamespaceDecl");
3544 Namespc
->setRBracLoc(RBrace
);
3546 if (Namespc
->hasAttr
<VisibilityAttr
>())
3547 PopPragmaVisibility();
3550 CXXRecordDecl
*Sema::getStdBadAlloc() const {
3551 return cast_or_null
<CXXRecordDecl
>(
3552 StdBadAlloc
.get(Context
.getExternalSource()));
3555 NamespaceDecl
*Sema::getStdNamespace() const {
3556 return cast_or_null
<NamespaceDecl
>(
3557 StdNamespace
.get(Context
.getExternalSource()));
3560 /// \brief Retrieve the special "std" namespace, which may require us to
3561 /// implicitly define the namespace.
3562 NamespaceDecl
*Sema::getOrCreateStdNamespace() {
3563 if (!StdNamespace
) {
3564 // The "std" namespace has not yet been defined, so build one implicitly.
3565 StdNamespace
= NamespaceDecl::Create(Context
,
3566 Context
.getTranslationUnitDecl(),
3568 &PP
.getIdentifierTable().get("std"));
3569 getStdNamespace()->setImplicit(true);
3572 return getStdNamespace();
3575 Decl
*Sema::ActOnUsingDirective(Scope
*S
,
3576 SourceLocation UsingLoc
,
3577 SourceLocation NamespcLoc
,
3579 SourceLocation IdentLoc
,
3580 IdentifierInfo
*NamespcName
,
3581 AttributeList
*AttrList
) {
3582 assert(!SS
.isInvalid() && "Invalid CXXScopeSpec.");
3583 assert(NamespcName
&& "Invalid NamespcName.");
3584 assert(IdentLoc
.isValid() && "Invalid NamespceName location.");
3586 // This can only happen along a recovery path.
3587 while (S
->getFlags() & Scope::TemplateParamScope
)
3589 assert(S
->getFlags() & Scope::DeclScope
&& "Invalid Scope.");
3591 UsingDirectiveDecl
*UDir
= 0;
3592 NestedNameSpecifier
*Qualifier
= 0;
3594 Qualifier
= static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
3596 // Lookup namespace name.
3597 LookupResult
R(*this, NamespcName
, IdentLoc
, LookupNamespaceName
);
3598 LookupParsedName(R
, S
, &SS
);
3599 if (R
.isAmbiguous())
3603 // Allow "using namespace std;" or "using namespace ::std;" even if
3604 // "std" hasn't been defined yet, for GCC compatibility.
3605 if ((!Qualifier
|| Qualifier
->getKind() == NestedNameSpecifier::Global
) &&
3606 NamespcName
->isStr("std")) {
3607 Diag(IdentLoc
, diag::ext_using_undefined_std
);
3608 R
.addDecl(getOrCreateStdNamespace());
3611 // Otherwise, attempt typo correction.
3612 else if (DeclarationName Corrected
= CorrectTypo(R
, S
, &SS
, 0, false,
3613 CTC_NoKeywords
, 0)) {
3614 if (R
.getAsSingle
<NamespaceDecl
>() ||
3615 R
.getAsSingle
<NamespaceAliasDecl
>()) {
3616 if (DeclContext
*DC
= computeDeclContext(SS
, false))
3617 Diag(IdentLoc
, diag::err_using_directive_member_suggest
)
3618 << NamespcName
<< DC
<< Corrected
<< SS
.getRange()
3619 << FixItHint::CreateReplacement(IdentLoc
, Corrected
.getAsString());
3621 Diag(IdentLoc
, diag::err_using_directive_suggest
)
3622 << NamespcName
<< Corrected
3623 << FixItHint::CreateReplacement(IdentLoc
, Corrected
.getAsString());
3624 Diag(R
.getFoundDecl()->getLocation(), diag::note_namespace_defined_here
)
3627 NamespcName
= Corrected
.getAsIdentifierInfo();
3630 R
.setLookupName(NamespcName
);
3636 NamedDecl
*Named
= R
.getFoundDecl();
3637 assert((isa
<NamespaceDecl
>(Named
) || isa
<NamespaceAliasDecl
>(Named
))
3638 && "expected namespace decl");
3639 // C++ [namespace.udir]p1:
3640 // A using-directive specifies that the names in the nominated
3641 // namespace can be used in the scope in which the
3642 // using-directive appears after the using-directive. During
3643 // unqualified name lookup (3.4.1), the names appear as if they
3644 // were declared in the nearest enclosing namespace which
3645 // contains both the using-directive and the nominated
3646 // namespace. [Note: in this context, "contains" means "contains
3647 // directly or indirectly". ]
3649 // Find enclosing context containing both using-directive and
3650 // nominated namespace.
3651 NamespaceDecl
*NS
= getNamespaceDecl(Named
);
3652 DeclContext
*CommonAncestor
= cast
<DeclContext
>(NS
);
3653 while (CommonAncestor
&& !CommonAncestor
->Encloses(CurContext
))
3654 CommonAncestor
= CommonAncestor
->getParent();
3656 UDir
= UsingDirectiveDecl::Create(Context
, CurContext
, UsingLoc
, NamespcLoc
,
3658 (NestedNameSpecifier
*)SS
.getScopeRep(),
3659 IdentLoc
, Named
, CommonAncestor
);
3660 PushUsingDirective(S
, UDir
);
3662 Diag(IdentLoc
, diag::err_expected_namespace_name
) << SS
.getRange();
3665 // FIXME: We ignore attributes for now.
3669 void Sema::PushUsingDirective(Scope
*S
, UsingDirectiveDecl
*UDir
) {
3670 // If scope has associated entity, then using directive is at namespace
3671 // or translation unit scope. We add UsingDirectiveDecls, into
3672 // it's lookup structure.
3673 if (DeclContext
*Ctx
= static_cast<DeclContext
*>(S
->getEntity()))
3676 // Otherwise it is block-sope. using-directives will affect lookup
3677 // only to the end of scope.
3678 S
->PushUsingDirective(UDir
);
3682 Decl
*Sema::ActOnUsingDeclaration(Scope
*S
,
3684 bool HasUsingKeyword
,
3685 SourceLocation UsingLoc
,
3687 UnqualifiedId
&Name
,
3688 AttributeList
*AttrList
,
3690 SourceLocation TypenameLoc
) {
3691 assert(S
->getFlags() & Scope::DeclScope
&& "Invalid Scope.");
3693 switch (Name
.getKind()) {
3694 case UnqualifiedId::IK_Identifier
:
3695 case UnqualifiedId::IK_OperatorFunctionId
:
3696 case UnqualifiedId::IK_LiteralOperatorId
:
3697 case UnqualifiedId::IK_ConversionFunctionId
:
3700 case UnqualifiedId::IK_ConstructorName
:
3701 case UnqualifiedId::IK_ConstructorTemplateId
:
3702 // C++0x inherited constructors.
3703 if (getLangOptions().CPlusPlus0x
) break;
3705 Diag(Name
.getSourceRange().getBegin(), diag::err_using_decl_constructor
)
3709 case UnqualifiedId::IK_DestructorName
:
3710 Diag(Name
.getSourceRange().getBegin(), diag::err_using_decl_destructor
)
3714 case UnqualifiedId::IK_TemplateId
:
3715 Diag(Name
.getSourceRange().getBegin(), diag::err_using_decl_template_id
)
3716 << SourceRange(Name
.TemplateId
->LAngleLoc
, Name
.TemplateId
->RAngleLoc
);
3720 DeclarationNameInfo TargetNameInfo
= GetNameFromUnqualifiedId(Name
);
3721 DeclarationName TargetName
= TargetNameInfo
.getName();
3725 // Warn about using declarations.
3726 // TODO: store that the declaration was written without 'using' and
3727 // talk about access decls instead of using decls in the
3729 if (!HasUsingKeyword
) {
3730 UsingLoc
= Name
.getSourceRange().getBegin();
3732 Diag(UsingLoc
, diag::warn_access_decl_deprecated
)
3733 << FixItHint::CreateInsertion(SS
.getRange().getBegin(), "using ");
3736 if (DiagnoseUnexpandedParameterPack(SS
, UPPC_UsingDeclaration
) ||
3737 DiagnoseUnexpandedParameterPack(TargetNameInfo
, UPPC_UsingDeclaration
))
3740 NamedDecl
*UD
= BuildUsingDeclaration(S
, AS
, UsingLoc
, SS
,
3741 TargetNameInfo
, AttrList
,
3742 /* IsInstantiation */ false,
3743 IsTypeName
, TypenameLoc
);
3745 PushOnScopeChains(UD
, S
, /*AddToContext*/ false);
3750 /// \brief Determine whether a using declaration considers the given
3751 /// declarations as "equivalent", e.g., if they are redeclarations of
3752 /// the same entity or are both typedefs of the same type.
3754 IsEquivalentForUsingDecl(ASTContext
&Context
, NamedDecl
*D1
, NamedDecl
*D2
,
3755 bool &SuppressRedeclaration
) {
3756 if (D1
->getCanonicalDecl() == D2
->getCanonicalDecl()) {
3757 SuppressRedeclaration
= false;
3761 if (TypedefDecl
*TD1
= dyn_cast
<TypedefDecl
>(D1
))
3762 if (TypedefDecl
*TD2
= dyn_cast
<TypedefDecl
>(D2
)) {
3763 SuppressRedeclaration
= true;
3764 return Context
.hasSameType(TD1
->getUnderlyingType(),
3765 TD2
->getUnderlyingType());
3772 /// Determines whether to create a using shadow decl for a particular
3773 /// decl, given the set of decls existing prior to this using lookup.
3774 bool Sema::CheckUsingShadowDecl(UsingDecl
*Using
, NamedDecl
*Orig
,
3775 const LookupResult
&Previous
) {
3776 // Diagnose finding a decl which is not from a base class of the
3777 // current class. We do this now because there are cases where this
3778 // function will silently decide not to build a shadow decl, which
3779 // will pre-empt further diagnostics.
3781 // We don't need to do this in C++0x because we do the check once on
3784 // FIXME: diagnose the following if we care enough:
3785 // struct A { int foo; };
3786 // struct B : A { using A::foo; };
3787 // template <class T> struct C : A {};
3788 // template <class T> struct D : C<T> { using B::foo; } // <---
3789 // This is invalid (during instantiation) in C++03 because B::foo
3790 // resolves to the using decl in B, which is not a base class of D<T>.
3791 // We can't diagnose it immediately because C<T> is an unknown
3792 // specialization. The UsingShadowDecl in D<T> then points directly
3793 // to A::foo, which will look well-formed when we instantiate.
3794 // The right solution is to not collapse the shadow-decl chain.
3795 if (!getLangOptions().CPlusPlus0x
&& CurContext
->isRecord()) {
3796 DeclContext
*OrigDC
= Orig
->getDeclContext();
3798 // Handle enums and anonymous structs.
3799 if (isa
<EnumDecl
>(OrigDC
)) OrigDC
= OrigDC
->getParent();
3800 CXXRecordDecl
*OrigRec
= cast
<CXXRecordDecl
>(OrigDC
);
3801 while (OrigRec
->isAnonymousStructOrUnion())
3802 OrigRec
= cast
<CXXRecordDecl
>(OrigRec
->getDeclContext());
3804 if (cast
<CXXRecordDecl
>(CurContext
)->isProvablyNotDerivedFrom(OrigRec
)) {
3805 if (OrigDC
== CurContext
) {
3806 Diag(Using
->getLocation(),
3807 diag::err_using_decl_nested_name_specifier_is_current_class
)
3808 << Using
->getNestedNameRange();
3809 Diag(Orig
->getLocation(), diag::note_using_decl_target
);
3813 Diag(Using
->getNestedNameRange().getBegin(),
3814 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
3815 << Using
->getTargetNestedNameDecl()
3816 << cast
<CXXRecordDecl
>(CurContext
)
3817 << Using
->getNestedNameRange();
3818 Diag(Orig
->getLocation(), diag::note_using_decl_target
);
3823 if (Previous
.empty()) return false;
3825 NamedDecl
*Target
= Orig
;
3826 if (isa
<UsingShadowDecl
>(Target
))
3827 Target
= cast
<UsingShadowDecl
>(Target
)->getTargetDecl();
3829 // If the target happens to be one of the previous declarations, we
3830 // don't have a conflict.
3832 // FIXME: but we might be increasing its access, in which case we
3833 // should redeclare it.
3834 NamedDecl
*NonTag
= 0, *Tag
= 0;
3835 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
3837 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
3839 if (IsEquivalentForUsingDecl(Context
, D
, Target
, Result
))
3842 (isa
<TagDecl
>(D
) ? Tag
: NonTag
) = D
;
3845 if (Target
->isFunctionOrFunctionTemplate()) {
3847 if (isa
<FunctionTemplateDecl
>(Target
))
3848 FD
= cast
<FunctionTemplateDecl
>(Target
)->getTemplatedDecl();
3850 FD
= cast
<FunctionDecl
>(Target
);
3852 NamedDecl
*OldDecl
= 0;
3853 switch (CheckOverload(0, FD
, Previous
, OldDecl
, /*IsForUsingDecl*/ true)) {
3857 case Ovl_NonFunction
:
3858 Diag(Using
->getLocation(), diag::err_using_decl_conflict
);
3861 // We found a decl with the exact signature.
3863 // If we're in a record, we want to hide the target, so we
3864 // return true (without a diagnostic) to tell the caller not to
3865 // build a shadow decl.
3866 if (CurContext
->isRecord())
3869 // If we're not in a record, this is an error.
3870 Diag(Using
->getLocation(), diag::err_using_decl_conflict
);
3874 Diag(Target
->getLocation(), diag::note_using_decl_target
);
3875 Diag(OldDecl
->getLocation(), diag::note_using_decl_conflict
);
3879 // Target is not a function.
3881 if (isa
<TagDecl
>(Target
)) {
3882 // No conflict between a tag and a non-tag.
3883 if (!Tag
) return false;
3885 Diag(Using
->getLocation(), diag::err_using_decl_conflict
);
3886 Diag(Target
->getLocation(), diag::note_using_decl_target
);
3887 Diag(Tag
->getLocation(), diag::note_using_decl_conflict
);
3891 // No conflict between a tag and a non-tag.
3892 if (!NonTag
) return false;
3894 Diag(Using
->getLocation(), diag::err_using_decl_conflict
);
3895 Diag(Target
->getLocation(), diag::note_using_decl_target
);
3896 Diag(NonTag
->getLocation(), diag::note_using_decl_conflict
);
3900 /// Builds a shadow declaration corresponding to a 'using' declaration.
3901 UsingShadowDecl
*Sema::BuildUsingShadowDecl(Scope
*S
,
3905 // If we resolved to another shadow declaration, just coalesce them.
3906 NamedDecl
*Target
= Orig
;
3907 if (isa
<UsingShadowDecl
>(Target
)) {
3908 Target
= cast
<UsingShadowDecl
>(Target
)->getTargetDecl();
3909 assert(!isa
<UsingShadowDecl
>(Target
) && "nested shadow declaration");
3912 UsingShadowDecl
*Shadow
3913 = UsingShadowDecl::Create(Context
, CurContext
,
3914 UD
->getLocation(), UD
, Target
);
3915 UD
->addShadowDecl(Shadow
);
3917 Shadow
->setAccess(UD
->getAccess());
3918 if (Orig
->isInvalidDecl() || UD
->isInvalidDecl())
3919 Shadow
->setInvalidDecl();
3922 PushOnScopeChains(Shadow
, S
);
3924 CurContext
->addDecl(Shadow
);
3930 /// Hides a using shadow declaration. This is required by the current
3931 /// using-decl implementation when a resolvable using declaration in a
3932 /// class is followed by a declaration which would hide or override
3933 /// one or more of the using decl's targets; for example:
3935 /// struct Base { void foo(int); };
3936 /// struct Derived : Base {
3937 /// using Base::foo;
3941 /// The governing language is C++03 [namespace.udecl]p12:
3943 /// When a using-declaration brings names from a base class into a
3944 /// derived class scope, member functions in the derived class
3945 /// override and/or hide member functions with the same name and
3946 /// parameter types in a base class (rather than conflicting).
3948 /// There are two ways to implement this:
3949 /// (1) optimistically create shadow decls when they're not hidden
3950 /// by existing declarations, or
3951 /// (2) don't create any shadow decls (or at least don't make them
3952 /// visible) until we've fully parsed/instantiated the class.
3953 /// The problem with (1) is that we might have to retroactively remove
3954 /// a shadow decl, which requires several O(n) operations because the
3955 /// decl structures are (very reasonably) not designed for removal.
3956 /// (2) avoids this but is very fiddly and phase-dependent.
3957 void Sema::HideUsingShadowDecl(Scope
*S
, UsingShadowDecl
*Shadow
) {
3958 if (Shadow
->getDeclName().getNameKind() ==
3959 DeclarationName::CXXConversionFunctionName
)
3960 cast
<CXXRecordDecl
>(Shadow
->getDeclContext())->removeConversion(Shadow
);
3962 // Remove it from the DeclContext...
3963 Shadow
->getDeclContext()->removeDecl(Shadow
);
3965 // ...and the scope, if applicable...
3967 S
->RemoveDecl(Shadow
);
3968 IdResolver
.RemoveDecl(Shadow
);
3971 // ...and the using decl.
3972 Shadow
->getUsingDecl()->removeShadowDecl(Shadow
);
3974 // TODO: complain somehow if Shadow was used. It shouldn't
3975 // be possible for this to happen, because...?
3978 /// Builds a using declaration.
3980 /// \param IsInstantiation - Whether this call arises from an
3981 /// instantiation of an unresolved using declaration. We treat
3982 /// the lookup differently for these declarations.
3983 NamedDecl
*Sema::BuildUsingDeclaration(Scope
*S
, AccessSpecifier AS
,
3984 SourceLocation UsingLoc
,
3986 const DeclarationNameInfo
&NameInfo
,
3987 AttributeList
*AttrList
,
3988 bool IsInstantiation
,
3990 SourceLocation TypenameLoc
) {
3991 assert(!SS
.isInvalid() && "Invalid CXXScopeSpec.");
3992 SourceLocation IdentLoc
= NameInfo
.getLoc();
3993 assert(IdentLoc
.isValid() && "Invalid TargetName location.");
3995 // FIXME: We ignore attributes for now.
3998 Diag(IdentLoc
, diag::err_using_requires_qualname
);
4002 // Do the redeclaration lookup in the current scope.
4003 LookupResult
Previous(*this, NameInfo
, LookupUsingDeclName
,
4005 Previous
.setHideTags(false);
4007 LookupName(Previous
, S
);
4009 // It is really dumb that we have to do this.
4010 LookupResult::Filter F
= Previous
.makeFilter();
4011 while (F
.hasNext()) {
4012 NamedDecl
*D
= F
.next();
4013 if (!isDeclInScope(D
, CurContext
, S
))
4018 assert(IsInstantiation
&& "no scope in non-instantiation");
4019 assert(CurContext
->isRecord() && "scope not record in instantiation");
4020 LookupQualifiedName(Previous
, CurContext
);
4023 NestedNameSpecifier
*NNS
=
4024 static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
4026 // Check for invalid redeclarations.
4027 if (CheckUsingDeclRedeclaration(UsingLoc
, IsTypeName
, SS
, IdentLoc
, Previous
))
4030 // Check for bad qualifiers.
4031 if (CheckUsingDeclQualifier(UsingLoc
, SS
, IdentLoc
))
4034 DeclContext
*LookupContext
= computeDeclContext(SS
);
4036 if (!LookupContext
) {
4038 // FIXME: not all declaration name kinds are legal here
4039 D
= UnresolvedUsingTypenameDecl::Create(Context
, CurContext
,
4040 UsingLoc
, TypenameLoc
,
4042 IdentLoc
, NameInfo
.getName());
4044 D
= UnresolvedUsingValueDecl::Create(Context
, CurContext
,
4045 UsingLoc
, SS
.getRange(),
4049 D
= UsingDecl::Create(Context
, CurContext
,
4050 SS
.getRange(), UsingLoc
, NNS
, NameInfo
,
4054 CurContext
->addDecl(D
);
4056 if (!LookupContext
) return D
;
4057 UsingDecl
*UD
= cast
<UsingDecl
>(D
);
4059 if (RequireCompleteDeclContext(SS
, LookupContext
)) {
4060 UD
->setInvalidDecl();
4064 // Look up the target name.
4066 LookupResult
R(*this, NameInfo
, LookupOrdinaryName
);
4068 // Unlike most lookups, we don't always want to hide tag
4069 // declarations: tag names are visible through the using declaration
4070 // even if hidden by ordinary names, *except* in a dependent context
4071 // where it's important for the sanity of two-phase lookup.
4072 if (!IsInstantiation
)
4073 R
.setHideTags(false);
4075 LookupQualifiedName(R
, LookupContext
);
4078 Diag(IdentLoc
, diag::err_no_member
)
4079 << NameInfo
.getName() << LookupContext
<< SS
.getRange();
4080 UD
->setInvalidDecl();
4084 if (R
.isAmbiguous()) {
4085 UD
->setInvalidDecl();
4090 // If we asked for a typename and got a non-type decl, error out.
4091 if (!R
.getAsSingle
<TypeDecl
>()) {
4092 Diag(IdentLoc
, diag::err_using_typename_non_type
);
4093 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
)
4094 Diag((*I
)->getUnderlyingDecl()->getLocation(),
4095 diag::note_using_decl_target
);
4096 UD
->setInvalidDecl();
4100 // If we asked for a non-typename and we got a type, error out,
4101 // but only if this is an instantiation of an unresolved using
4102 // decl. Otherwise just silently find the type name.
4103 if (IsInstantiation
&& R
.getAsSingle
<TypeDecl
>()) {
4104 Diag(IdentLoc
, diag::err_using_dependent_value_is_type
);
4105 Diag(R
.getFoundDecl()->getLocation(), diag::note_using_decl_target
);
4106 UD
->setInvalidDecl();
4111 // C++0x N2914 [namespace.udecl]p6:
4112 // A using-declaration shall not name a namespace.
4113 if (R
.getAsSingle
<NamespaceDecl
>()) {
4114 Diag(IdentLoc
, diag::err_using_decl_can_not_refer_to_namespace
)
4116 UD
->setInvalidDecl();
4120 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
) {
4121 if (!CheckUsingShadowDecl(UD
, *I
, Previous
))
4122 BuildUsingShadowDecl(S
, UD
, *I
);
4128 /// Checks that the given using declaration is not an invalid
4129 /// redeclaration. Note that this is checking only for the using decl
4130 /// itself, not for any ill-formedness among the UsingShadowDecls.
4131 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc
,
4133 const CXXScopeSpec
&SS
,
4134 SourceLocation NameLoc
,
4135 const LookupResult
&Prev
) {
4136 // C++03 [namespace.udecl]p8:
4137 // C++0x [namespace.udecl]p10:
4138 // A using-declaration is a declaration and can therefore be used
4139 // repeatedly where (and only where) multiple declarations are
4142 // That's in non-member contexts.
4143 if (!CurContext
->getRedeclContext()->isRecord())
4146 NestedNameSpecifier
*Qual
4147 = static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
4149 for (LookupResult::iterator I
= Prev
.begin(), E
= Prev
.end(); I
!= E
; ++I
) {
4153 NestedNameSpecifier
*DQual
;
4154 if (UsingDecl
*UD
= dyn_cast
<UsingDecl
>(D
)) {
4155 DTypename
= UD
->isTypeName();
4156 DQual
= UD
->getTargetNestedNameDecl();
4157 } else if (UnresolvedUsingValueDecl
*UD
4158 = dyn_cast
<UnresolvedUsingValueDecl
>(D
)) {
4160 DQual
= UD
->getTargetNestedNameSpecifier();
4161 } else if (UnresolvedUsingTypenameDecl
*UD
4162 = dyn_cast
<UnresolvedUsingTypenameDecl
>(D
)) {
4164 DQual
= UD
->getTargetNestedNameSpecifier();
4167 // using decls differ if one says 'typename' and the other doesn't.
4168 // FIXME: non-dependent using decls?
4169 if (isTypeName
!= DTypename
) continue;
4171 // using decls differ if they name different scopes (but note that
4172 // template instantiation can cause this check to trigger when it
4173 // didn't before instantiation).
4174 if (Context
.getCanonicalNestedNameSpecifier(Qual
) !=
4175 Context
.getCanonicalNestedNameSpecifier(DQual
))
4178 Diag(NameLoc
, diag::err_using_decl_redeclaration
) << SS
.getRange();
4179 Diag(D
->getLocation(), diag::note_using_decl
) << 1;
4187 /// Checks that the given nested-name qualifier used in a using decl
4188 /// in the current context is appropriately related to the current
4189 /// scope. If an error is found, diagnoses it and returns true.
4190 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc
,
4191 const CXXScopeSpec
&SS
,
4192 SourceLocation NameLoc
) {
4193 DeclContext
*NamedContext
= computeDeclContext(SS
);
4195 if (!CurContext
->isRecord()) {
4196 // C++03 [namespace.udecl]p3:
4197 // C++0x [namespace.udecl]p8:
4198 // A using-declaration for a class member shall be a member-declaration.
4200 // If we weren't able to compute a valid scope, it must be a
4201 // dependent class scope.
4202 if (!NamedContext
|| NamedContext
->isRecord()) {
4203 Diag(NameLoc
, diag::err_using_decl_can_not_refer_to_class_member
)
4208 // Otherwise, everything is known to be fine.
4212 // The current scope is a record.
4214 // If the named context is dependent, we can't decide much.
4215 if (!NamedContext
) {
4216 // FIXME: in C++0x, we can diagnose if we can prove that the
4217 // nested-name-specifier does not refer to a base class, which is
4218 // still possible in some cases.
4220 // Otherwise we have to conservatively report that things might be
4225 if (!NamedContext
->isRecord()) {
4226 // Ideally this would point at the last name in the specifier,
4227 // but we don't have that level of source info.
4228 Diag(SS
.getRange().getBegin(),
4229 diag::err_using_decl_nested_name_specifier_is_not_class
)
4230 << (NestedNameSpecifier
*) SS
.getScopeRep() << SS
.getRange();
4234 if (!NamedContext
->isDependentContext() &&
4235 RequireCompleteDeclContext(const_cast<CXXScopeSpec
&>(SS
), NamedContext
))
4238 if (getLangOptions().CPlusPlus0x
) {
4239 // C++0x [namespace.udecl]p3:
4240 // In a using-declaration used as a member-declaration, the
4241 // nested-name-specifier shall name a base class of the class
4244 if (cast
<CXXRecordDecl
>(CurContext
)->isProvablyNotDerivedFrom(
4245 cast
<CXXRecordDecl
>(NamedContext
))) {
4246 if (CurContext
== NamedContext
) {
4248 diag::err_using_decl_nested_name_specifier_is_current_class
)
4253 Diag(SS
.getRange().getBegin(),
4254 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
4255 << (NestedNameSpecifier
*) SS
.getScopeRep()
4256 << cast
<CXXRecordDecl
>(CurContext
)
4264 // C++03 [namespace.udecl]p4:
4265 // A using-declaration used as a member-declaration shall refer
4266 // to a member of a base class of the class being defined [etc.].
4268 // Salient point: SS doesn't have to name a base class as long as
4269 // lookup only finds members from base classes. Therefore we can
4270 // diagnose here only if we can prove that that can't happen,
4271 // i.e. if the class hierarchies provably don't intersect.
4273 // TODO: it would be nice if "definitely valid" results were cached
4274 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4275 // need to be repeated.
4278 llvm::DenseSet
<const CXXRecordDecl
*> Bases
;
4280 static bool collect(const CXXRecordDecl
*Base
, void *OpaqueData
) {
4281 UserData
*Data
= reinterpret_cast<UserData
*>(OpaqueData
);
4282 Data
->Bases
.insert(Base
);
4286 bool hasDependentBases(const CXXRecordDecl
*Class
) {
4287 return !Class
->forallBases(collect
, this);
4290 /// Returns true if the base is dependent or is one of the
4291 /// accumulated base classes.
4292 static bool doesNotContain(const CXXRecordDecl
*Base
, void *OpaqueData
) {
4293 UserData
*Data
= reinterpret_cast<UserData
*>(OpaqueData
);
4294 return !Data
->Bases
.count(Base
);
4297 bool mightShareBases(const CXXRecordDecl
*Class
) {
4298 return Bases
.count(Class
) || !Class
->forallBases(doesNotContain
, this);
4304 // Returns false if we find a dependent base.
4305 if (Data
.hasDependentBases(cast
<CXXRecordDecl
>(CurContext
)))
4308 // Returns false if the class has a dependent base or if it or one
4309 // of its bases is present in the base set of the current context.
4310 if (Data
.mightShareBases(cast
<CXXRecordDecl
>(NamedContext
)))
4313 Diag(SS
.getRange().getBegin(),
4314 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
4315 << (NestedNameSpecifier
*) SS
.getScopeRep()
4316 << cast
<CXXRecordDecl
>(CurContext
)
4322 Decl
*Sema::ActOnNamespaceAliasDef(Scope
*S
,
4323 SourceLocation NamespaceLoc
,
4324 SourceLocation AliasLoc
,
4325 IdentifierInfo
*Alias
,
4327 SourceLocation IdentLoc
,
4328 IdentifierInfo
*Ident
) {
4330 // Lookup the namespace name.
4331 LookupResult
R(*this, Ident
, IdentLoc
, LookupNamespaceName
);
4332 LookupParsedName(R
, S
, &SS
);
4334 // Check if we have a previous declaration with the same name.
4336 = LookupSingleName(S
, Alias
, AliasLoc
, LookupOrdinaryName
,
4338 if (PrevDecl
&& !isDeclInScope(PrevDecl
, CurContext
, S
))
4342 if (NamespaceAliasDecl
*AD
= dyn_cast
<NamespaceAliasDecl
>(PrevDecl
)) {
4343 // We already have an alias with the same name that points to the same
4344 // namespace, so don't create a new one.
4345 // FIXME: At some point, we'll want to create the (redundant)
4346 // declaration to maintain better source information.
4347 if (!R
.isAmbiguous() && !R
.empty() &&
4348 AD
->getNamespace()->Equals(getNamespaceDecl(R
.getFoundDecl())))
4352 unsigned DiagID
= isa
<NamespaceDecl
>(PrevDecl
) ? diag::err_redefinition
:
4353 diag::err_redefinition_different_kind
;
4354 Diag(AliasLoc
, DiagID
) << Alias
;
4355 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
4359 if (R
.isAmbiguous())
4363 if (DeclarationName Corrected
= CorrectTypo(R
, S
, &SS
, 0, false,
4364 CTC_NoKeywords
, 0)) {
4365 if (R
.getAsSingle
<NamespaceDecl
>() ||
4366 R
.getAsSingle
<NamespaceAliasDecl
>()) {
4367 if (DeclContext
*DC
= computeDeclContext(SS
, false))
4368 Diag(IdentLoc
, diag::err_using_directive_member_suggest
)
4369 << Ident
<< DC
<< Corrected
<< SS
.getRange()
4370 << FixItHint::CreateReplacement(IdentLoc
, Corrected
.getAsString());
4372 Diag(IdentLoc
, diag::err_using_directive_suggest
)
4373 << Ident
<< Corrected
4374 << FixItHint::CreateReplacement(IdentLoc
, Corrected
.getAsString());
4376 Diag(R
.getFoundDecl()->getLocation(), diag::note_namespace_defined_here
)
4379 Ident
= Corrected
.getAsIdentifierInfo();
4382 R
.setLookupName(Ident
);
4387 Diag(NamespaceLoc
, diag::err_expected_namespace_name
) << SS
.getRange();
4392 NamespaceAliasDecl
*AliasDecl
=
4393 NamespaceAliasDecl::Create(Context
, CurContext
, NamespaceLoc
, AliasLoc
,
4394 Alias
, SS
.getRange(),
4395 (NestedNameSpecifier
*)SS
.getScopeRep(),
4396 IdentLoc
, R
.getFoundDecl());
4398 PushOnScopeChains(AliasDecl
, S
);
4403 /// \brief Scoped object used to handle the state changes required in Sema
4404 /// to implicitly define the body of a C++ member function;
4405 class ImplicitlyDefinedFunctionScope
{
4407 DeclContext
*PreviousContext
;
4410 ImplicitlyDefinedFunctionScope(Sema
&S
, CXXMethodDecl
*Method
)
4411 : S(S
), PreviousContext(S
.CurContext
)
4413 S
.CurContext
= Method
;
4414 S
.PushFunctionScope();
4415 S
.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated
);
4418 ~ImplicitlyDefinedFunctionScope() {
4419 S
.PopExpressionEvaluationContext();
4420 S
.PopFunctionOrBlockScope();
4421 S
.CurContext
= PreviousContext
;
4426 static CXXConstructorDecl
*getDefaultConstructorUnsafe(Sema
&Self
,
4428 ASTContext
&Context
= Self
.Context
;
4429 QualType ClassType
= Context
.getTypeDeclType(D
);
4430 DeclarationName ConstructorName
4431 = Context
.DeclarationNames
.getCXXConstructorName(
4432 Context
.getCanonicalType(ClassType
.getUnqualifiedType()));
4434 DeclContext::lookup_const_iterator Con
, ConEnd
;
4435 for (llvm::tie(Con
, ConEnd
) = D
->lookup(ConstructorName
);
4436 Con
!= ConEnd
; ++Con
) {
4437 // FIXME: In C++0x, a constructor template can be a default constructor.
4438 if (isa
<FunctionTemplateDecl
>(*Con
))
4441 CXXConstructorDecl
*Constructor
= cast
<CXXConstructorDecl
>(*Con
);
4442 if (Constructor
->isDefaultConstructor())
4448 CXXConstructorDecl
*Sema::DeclareImplicitDefaultConstructor(
4449 CXXRecordDecl
*ClassDecl
) {
4450 // C++ [class.ctor]p5:
4451 // A default constructor for a class X is a constructor of class X
4452 // that can be called without an argument. If there is no
4453 // user-declared constructor for class X, a default constructor is
4454 // implicitly declared. An implicitly-declared default constructor
4455 // is an inline public member of its class.
4456 assert(!ClassDecl
->hasUserDeclaredConstructor() &&
4457 "Should not build implicit default constructor!");
4459 // C++ [except.spec]p14:
4460 // An implicitly declared special member function (Clause 12) shall have an
4461 // exception-specification. [...]
4462 ImplicitExceptionSpecification
ExceptSpec(Context
);
4464 // Direct base-class destructors.
4465 for (CXXRecordDecl::base_class_iterator B
= ClassDecl
->bases_begin(),
4466 BEnd
= ClassDecl
->bases_end();
4468 if (B
->isVirtual()) // Handled below.
4471 if (const RecordType
*BaseType
= B
->getType()->getAs
<RecordType
>()) {
4472 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(BaseType
->getDecl());
4473 if (!BaseClassDecl
->hasDeclaredDefaultConstructor())
4474 ExceptSpec
.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl
));
4475 else if (CXXConstructorDecl
*Constructor
4476 = getDefaultConstructorUnsafe(*this, BaseClassDecl
))
4477 ExceptSpec
.CalledDecl(Constructor
);
4481 // Virtual base-class destructors.
4482 for (CXXRecordDecl::base_class_iterator B
= ClassDecl
->vbases_begin(),
4483 BEnd
= ClassDecl
->vbases_end();
4485 if (const RecordType
*BaseType
= B
->getType()->getAs
<RecordType
>()) {
4486 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(BaseType
->getDecl());
4487 if (!BaseClassDecl
->hasDeclaredDefaultConstructor())
4488 ExceptSpec
.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl
));
4489 else if (CXXConstructorDecl
*Constructor
4490 = getDefaultConstructorUnsafe(*this, BaseClassDecl
))
4491 ExceptSpec
.CalledDecl(Constructor
);
4495 // Field destructors.
4496 for (RecordDecl::field_iterator F
= ClassDecl
->field_begin(),
4497 FEnd
= ClassDecl
->field_end();
4499 if (const RecordType
*RecordTy
4500 = Context
.getBaseElementType(F
->getType())->getAs
<RecordType
>()) {
4501 CXXRecordDecl
*FieldClassDecl
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
4502 if (!FieldClassDecl
->hasDeclaredDefaultConstructor())
4503 ExceptSpec
.CalledDecl(
4504 DeclareImplicitDefaultConstructor(FieldClassDecl
));
4505 else if (CXXConstructorDecl
*Constructor
4506 = getDefaultConstructorUnsafe(*this, FieldClassDecl
))
4507 ExceptSpec
.CalledDecl(Constructor
);
4511 FunctionProtoType::ExtProtoInfo EPI
;
4512 EPI
.HasExceptionSpec
= ExceptSpec
.hasExceptionSpecification();
4513 EPI
.HasAnyExceptionSpec
= ExceptSpec
.hasAnyExceptionSpecification();
4514 EPI
.NumExceptions
= ExceptSpec
.size();
4515 EPI
.Exceptions
= ExceptSpec
.data();
4517 // Create the actual constructor declaration.
4518 CanQualType ClassType
4519 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
4520 DeclarationName Name
4521 = Context
.DeclarationNames
.getCXXConstructorName(ClassType
);
4522 DeclarationNameInfo
NameInfo(Name
, ClassDecl
->getLocation());
4523 CXXConstructorDecl
*DefaultCon
4524 = CXXConstructorDecl::Create(Context
, ClassDecl
, NameInfo
,
4525 Context
.getFunctionType(Context
.VoidTy
,
4528 /*isExplicit=*/false,
4530 /*isImplicitlyDeclared=*/true);
4531 DefaultCon
->setAccess(AS_public
);
4532 DefaultCon
->setImplicit();
4533 DefaultCon
->setTrivial(ClassDecl
->hasTrivialConstructor());
4535 // Note that we have declared this constructor.
4536 ++ASTContext::NumImplicitDefaultConstructorsDeclared
;
4538 if (Scope
*S
= getScopeForContext(ClassDecl
))
4539 PushOnScopeChains(DefaultCon
, S
, false);
4540 ClassDecl
->addDecl(DefaultCon
);
4545 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation
,
4546 CXXConstructorDecl
*Constructor
) {
4547 assert((Constructor
->isImplicit() && Constructor
->isDefaultConstructor() &&
4548 !Constructor
->isUsed(false)) &&
4549 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
4551 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
4552 assert(ClassDecl
&& "DefineImplicitDefaultConstructor - invalid constructor");
4554 ImplicitlyDefinedFunctionScope
Scope(*this, Constructor
);
4555 DiagnosticErrorTrap
Trap(Diags
);
4556 if (SetCtorInitializers(Constructor
, 0, 0, /*AnyErrors=*/false) ||
4557 Trap
.hasErrorOccurred()) {
4558 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
4559 << CXXConstructor
<< Context
.getTagDeclType(ClassDecl
);
4560 Constructor
->setInvalidDecl();
4564 SourceLocation Loc
= Constructor
->getLocation();
4565 Constructor
->setBody(new (Context
) CompoundStmt(Context
, 0, 0, Loc
, Loc
));
4567 Constructor
->setUsed();
4568 MarkVTableUsed(CurrentLocation
, ClassDecl
);
4571 CXXDestructorDecl
*Sema::DeclareImplicitDestructor(CXXRecordDecl
*ClassDecl
) {
4572 // C++ [class.dtor]p2:
4573 // If a class has no user-declared destructor, a destructor is
4574 // declared implicitly. An implicitly-declared destructor is an
4575 // inline public member of its class.
4577 // C++ [except.spec]p14:
4578 // An implicitly declared special member function (Clause 12) shall have
4579 // an exception-specification.
4580 ImplicitExceptionSpecification
ExceptSpec(Context
);
4582 // Direct base-class destructors.
4583 for (CXXRecordDecl::base_class_iterator B
= ClassDecl
->bases_begin(),
4584 BEnd
= ClassDecl
->bases_end();
4586 if (B
->isVirtual()) // Handled below.
4589 if (const RecordType
*BaseType
= B
->getType()->getAs
<RecordType
>())
4590 ExceptSpec
.CalledDecl(
4591 LookupDestructor(cast
<CXXRecordDecl
>(BaseType
->getDecl())));
4594 // Virtual base-class destructors.
4595 for (CXXRecordDecl::base_class_iterator B
= ClassDecl
->vbases_begin(),
4596 BEnd
= ClassDecl
->vbases_end();
4598 if (const RecordType
*BaseType
= B
->getType()->getAs
<RecordType
>())
4599 ExceptSpec
.CalledDecl(
4600 LookupDestructor(cast
<CXXRecordDecl
>(BaseType
->getDecl())));
4603 // Field destructors.
4604 for (RecordDecl::field_iterator F
= ClassDecl
->field_begin(),
4605 FEnd
= ClassDecl
->field_end();
4607 if (const RecordType
*RecordTy
4608 = Context
.getBaseElementType(F
->getType())->getAs
<RecordType
>())
4609 ExceptSpec
.CalledDecl(
4610 LookupDestructor(cast
<CXXRecordDecl
>(RecordTy
->getDecl())));
4613 // Create the actual destructor declaration.
4614 FunctionProtoType::ExtProtoInfo EPI
;
4615 EPI
.HasExceptionSpec
= ExceptSpec
.hasExceptionSpecification();
4616 EPI
.HasAnyExceptionSpec
= ExceptSpec
.hasAnyExceptionSpecification();
4617 EPI
.NumExceptions
= ExceptSpec
.size();
4618 EPI
.Exceptions
= ExceptSpec
.data();
4619 QualType Ty
= Context
.getFunctionType(Context
.VoidTy
, 0, 0, EPI
);
4621 CanQualType ClassType
4622 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
4623 DeclarationName Name
4624 = Context
.DeclarationNames
.getCXXDestructorName(ClassType
);
4625 DeclarationNameInfo
NameInfo(Name
, ClassDecl
->getLocation());
4626 CXXDestructorDecl
*Destructor
4627 = CXXDestructorDecl::Create(Context
, ClassDecl
, NameInfo
, Ty
, 0,
4629 /*isImplicitlyDeclared=*/true);
4630 Destructor
->setAccess(AS_public
);
4631 Destructor
->setImplicit();
4632 Destructor
->setTrivial(ClassDecl
->hasTrivialDestructor());
4634 // Note that we have declared this destructor.
4635 ++ASTContext::NumImplicitDestructorsDeclared
;
4637 // Introduce this destructor into its scope.
4638 if (Scope
*S
= getScopeForContext(ClassDecl
))
4639 PushOnScopeChains(Destructor
, S
, false);
4640 ClassDecl
->addDecl(Destructor
);
4642 // This could be uniqued if it ever proves significant.
4643 Destructor
->setTypeSourceInfo(Context
.getTrivialTypeSourceInfo(Ty
));
4645 AddOverriddenMethods(ClassDecl
, Destructor
);
4650 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation
,
4651 CXXDestructorDecl
*Destructor
) {
4652 assert((Destructor
->isImplicit() && !Destructor
->isUsed(false)) &&
4653 "DefineImplicitDestructor - call it for implicit default dtor");
4654 CXXRecordDecl
*ClassDecl
= Destructor
->getParent();
4655 assert(ClassDecl
&& "DefineImplicitDestructor - invalid destructor");
4657 if (Destructor
->isInvalidDecl())
4660 ImplicitlyDefinedFunctionScope
Scope(*this, Destructor
);
4662 DiagnosticErrorTrap
Trap(Diags
);
4663 MarkBaseAndMemberDestructorsReferenced(Destructor
->getLocation(),
4664 Destructor
->getParent());
4666 if (CheckDestructor(Destructor
) || Trap
.hasErrorOccurred()) {
4667 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
4668 << CXXDestructor
<< Context
.getTagDeclType(ClassDecl
);
4670 Destructor
->setInvalidDecl();
4674 SourceLocation Loc
= Destructor
->getLocation();
4675 Destructor
->setBody(new (Context
) CompoundStmt(Context
, 0, 0, Loc
, Loc
));
4677 Destructor
->setUsed();
4678 MarkVTableUsed(CurrentLocation
, ClassDecl
);
4681 /// \brief Builds a statement that copies the given entity from \p From to
4684 /// This routine is used to copy the members of a class with an
4685 /// implicitly-declared copy assignment operator. When the entities being
4686 /// copied are arrays, this routine builds for loops to copy them.
4688 /// \param S The Sema object used for type-checking.
4690 /// \param Loc The location where the implicit copy is being generated.
4692 /// \param T The type of the expressions being copied. Both expressions must
4695 /// \param To The expression we are copying to.
4697 /// \param From The expression we are copying from.
4699 /// \param CopyingBaseSubobject Whether we're copying a base subobject.
4700 /// Otherwise, it's a non-static member subobject.
4702 /// \param Depth Internal parameter recording the depth of the recursion.
4704 /// \returns A statement or a loop that copies the expressions.
4706 BuildSingleCopyAssign(Sema
&S
, SourceLocation Loc
, QualType T
,
4707 Expr
*To
, Expr
*From
,
4708 bool CopyingBaseSubobject
, unsigned Depth
= 0) {
4709 // C++0x [class.copy]p30:
4710 // Each subobject is assigned in the manner appropriate to its type:
4712 // - if the subobject is of class type, the copy assignment operator
4713 // for the class is used (as if by explicit qualification; that is,
4714 // ignoring any possible virtual overriding functions in more derived
4716 if (const RecordType
*RecordTy
= T
->getAs
<RecordType
>()) {
4717 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
4719 // Look for operator=.
4720 DeclarationName Name
4721 = S
.Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
4722 LookupResult
OpLookup(S
, Name
, Loc
, Sema::LookupOrdinaryName
);
4723 S
.LookupQualifiedName(OpLookup
, ClassDecl
, false);
4725 // Filter out any result that isn't a copy-assignment operator.
4726 LookupResult::Filter F
= OpLookup
.makeFilter();
4727 while (F
.hasNext()) {
4728 NamedDecl
*D
= F
.next();
4729 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
))
4730 if (Method
->isCopyAssignmentOperator())
4737 // Suppress the protected check (C++ [class.protected]) for each of the
4738 // assignment operators we found. This strange dance is required when
4739 // we're assigning via a base classes's copy-assignment operator. To
4740 // ensure that we're getting the right base class subobject (without
4741 // ambiguities), we need to cast "this" to that subobject type; to
4742 // ensure that we don't go through the virtual call mechanism, we need
4743 // to qualify the operator= name with the base class (see below). However,
4744 // this means that if the base class has a protected copy assignment
4745 // operator, the protected member access check will fail. So, we
4746 // rewrite "protected" access to "public" access in this case, since we
4747 // know by construction that we're calling from a derived class.
4748 if (CopyingBaseSubobject
) {
4749 for (LookupResult::iterator L
= OpLookup
.begin(), LEnd
= OpLookup
.end();
4751 if (L
.getAccess() == AS_protected
)
4752 L
.setAccess(AS_public
);
4756 // Create the nested-name-specifier that will be used to qualify the
4757 // reference to operator=; this is required to suppress the virtual
4761 SS
.setScopeRep(NestedNameSpecifier::Create(S
.Context
, 0, false,
4764 // Create the reference to operator=.
4765 ExprResult OpEqualRef
4766 = S
.BuildMemberReferenceExpr(To
, T
, Loc
, /*isArrow=*/false, SS
,
4767 /*FirstQualifierInScope=*/0, OpLookup
,
4769 /*SuppressQualifierCheck=*/true);
4770 if (OpEqualRef
.isInvalid())
4773 // Build the call to the assignment operator.
4775 ExprResult Call
= S
.BuildCallToMemberFunction(/*Scope=*/0,
4776 OpEqualRef
.takeAs
<Expr
>(),
4777 Loc
, &From
, 1, Loc
);
4778 if (Call
.isInvalid())
4781 return S
.Owned(Call
.takeAs
<Stmt
>());
4784 // - if the subobject is of scalar type, the built-in assignment
4785 // operator is used.
4786 const ConstantArrayType
*ArrayTy
= S
.Context
.getAsConstantArrayType(T
);
4788 ExprResult Assignment
= S
.CreateBuiltinBinOp(Loc
, BO_Assign
, To
, From
);
4789 if (Assignment
.isInvalid())
4792 return S
.Owned(Assignment
.takeAs
<Stmt
>());
4795 // - if the subobject is an array, each element is assigned, in the
4796 // manner appropriate to the element type;
4798 // Construct a loop over the array bounds, e.g.,
4800 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
4802 // that will copy each of the array elements.
4803 QualType SizeType
= S
.Context
.getSizeType();
4805 // Create the iteration variable.
4806 IdentifierInfo
*IterationVarName
= 0;
4808 llvm::SmallString
<8> Str
;
4809 llvm::raw_svector_ostream
OS(Str
);
4810 OS
<< "__i" << Depth
;
4811 IterationVarName
= &S
.Context
.Idents
.get(OS
.str());
4813 VarDecl
*IterationVar
= VarDecl::Create(S
.Context
, S
.CurContext
, Loc
,
4814 IterationVarName
, SizeType
,
4815 S
.Context
.getTrivialTypeSourceInfo(SizeType
, Loc
),
4818 // Initialize the iteration variable to zero.
4819 llvm::APInt
Zero(S
.Context
.getTypeSize(SizeType
), 0);
4820 IterationVar
->setInit(IntegerLiteral::Create(S
.Context
, Zero
, SizeType
, Loc
));
4822 // Create a reference to the iteration variable; we'll use this several
4823 // times throughout.
4824 Expr
*IterationVarRef
4825 = S
.BuildDeclRefExpr(IterationVar
, SizeType
, VK_RValue
, Loc
).take();
4826 assert(IterationVarRef
&& "Reference to invented variable cannot fail!");
4828 // Create the DeclStmt that holds the iteration variable.
4829 Stmt
*InitStmt
= new (S
.Context
) DeclStmt(DeclGroupRef(IterationVar
),Loc
,Loc
);
4831 // Create the comparison against the array bound.
4833 = ArrayTy
->getSize().zextOrTrunc(S
.Context
.getTypeSize(SizeType
));
4835 = new (S
.Context
) BinaryOperator(IterationVarRef
,
4836 IntegerLiteral::Create(S
.Context
, Upper
, SizeType
, Loc
),
4837 BO_NE
, S
.Context
.BoolTy
,
4838 VK_RValue
, OK_Ordinary
, Loc
);
4840 // Create the pre-increment of the iteration variable.
4842 = new (S
.Context
) UnaryOperator(IterationVarRef
, UO_PreInc
, SizeType
,
4843 VK_LValue
, OK_Ordinary
, Loc
);
4845 // Subscript the "from" and "to" expressions with the iteration variable.
4846 From
= AssertSuccess(S
.CreateBuiltinArraySubscriptExpr(From
, Loc
,
4847 IterationVarRef
, Loc
));
4848 To
= AssertSuccess(S
.CreateBuiltinArraySubscriptExpr(To
, Loc
,
4849 IterationVarRef
, Loc
));
4851 // Build the copy for an individual element of the array.
4852 StmtResult Copy
= BuildSingleCopyAssign(S
, Loc
, ArrayTy
->getElementType(),
4853 To
, From
, CopyingBaseSubobject
,
4855 if (Copy
.isInvalid())
4858 // Construct the loop that copies all elements of this array.
4859 return S
.ActOnForStmt(Loc
, Loc
, InitStmt
,
4860 S
.MakeFullExpr(Comparison
),
4861 0, S
.MakeFullExpr(Increment
),
4865 /// \brief Determine whether the given class has a copy assignment operator
4866 /// that accepts a const-qualified argument.
4867 static bool hasConstCopyAssignment(Sema
&S
, const CXXRecordDecl
*CClass
) {
4868 CXXRecordDecl
*Class
= const_cast<CXXRecordDecl
*>(CClass
);
4870 if (!Class
->hasDeclaredCopyAssignment())
4871 S
.DeclareImplicitCopyAssignment(Class
);
4873 QualType ClassType
= S
.Context
.getCanonicalType(S
.Context
.getTypeDeclType(Class
));
4874 DeclarationName OpName
4875 = S
.Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
4877 DeclContext::lookup_const_iterator Op
, OpEnd
;
4878 for (llvm::tie(Op
, OpEnd
) = Class
->lookup(OpName
); Op
!= OpEnd
; ++Op
) {
4879 // C++ [class.copy]p9:
4880 // A user-declared copy assignment operator is a non-static non-template
4881 // member function of class X with exactly one parameter of type X, X&,
4882 // const X&, volatile X& or const volatile X&.
4883 const CXXMethodDecl
* Method
= dyn_cast
<CXXMethodDecl
>(*Op
);
4887 if (Method
->isStatic())
4889 if (Method
->getPrimaryTemplate())
4891 const FunctionProtoType
*FnType
=
4892 Method
->getType()->getAs
<FunctionProtoType
>();
4893 assert(FnType
&& "Overloaded operator has no prototype.");
4894 // Don't assert on this; an invalid decl might have been left in the AST.
4895 if (FnType
->getNumArgs() != 1 || FnType
->isVariadic())
4897 bool AcceptsConst
= true;
4898 QualType ArgType
= FnType
->getArgType(0);
4899 if (const LValueReferenceType
*Ref
= ArgType
->getAs
<LValueReferenceType
>()){
4900 ArgType
= Ref
->getPointeeType();
4901 // Is it a non-const lvalue reference?
4902 if (!ArgType
.isConstQualified())
4903 AcceptsConst
= false;
4905 if (!S
.Context
.hasSameUnqualifiedType(ArgType
, ClassType
))
4908 // We have a single argument of type cv X or cv X&, i.e. we've found the
4909 // copy assignment operator. Return whether it accepts const arguments.
4910 return AcceptsConst
;
4912 assert(Class
->isInvalidDecl() &&
4913 "No copy assignment operator declared in valid code.");
4917 CXXMethodDecl
*Sema::DeclareImplicitCopyAssignment(CXXRecordDecl
*ClassDecl
) {
4918 // Note: The following rules are largely analoguous to the copy
4919 // constructor rules. Note that virtual bases are not taken into account
4920 // for determining the argument type of the operator. Note also that
4921 // operators taking an object instead of a reference are allowed.
4924 // C++ [class.copy]p10:
4925 // If the class definition does not explicitly declare a copy
4926 // assignment operator, one is declared implicitly.
4927 // The implicitly-defined copy assignment operator for a class X
4928 // will have the form
4930 // X& X::operator=(const X&)
4933 bool HasConstCopyAssignment
= true;
4935 // -- each direct base class B of X has a copy assignment operator
4936 // whose parameter is of type const B&, const volatile B& or B,
4938 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
4939 BaseEnd
= ClassDecl
->bases_end();
4940 HasConstCopyAssignment
&& Base
!= BaseEnd
; ++Base
) {
4941 assert(!Base
->getType()->isDependentType() &&
4942 "Cannot generate implicit members for class with dependent bases.");
4943 const CXXRecordDecl
*BaseClassDecl
4944 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
4945 HasConstCopyAssignment
= hasConstCopyAssignment(*this, BaseClassDecl
);
4948 // -- for all the nonstatic data members of X that are of a class
4949 // type M (or array thereof), each such class type has a copy
4950 // assignment operator whose parameter is of type const M&,
4951 // const volatile M& or M.
4952 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
4953 FieldEnd
= ClassDecl
->field_end();
4954 HasConstCopyAssignment
&& Field
!= FieldEnd
;
4956 QualType FieldType
= Context
.getBaseElementType((*Field
)->getType());
4957 if (const RecordType
*FieldClassType
= FieldType
->getAs
<RecordType
>()) {
4958 const CXXRecordDecl
*FieldClassDecl
4959 = cast
<CXXRecordDecl
>(FieldClassType
->getDecl());
4960 HasConstCopyAssignment
= hasConstCopyAssignment(*this, FieldClassDecl
);
4964 // Otherwise, the implicitly declared copy assignment operator will
4967 // X& X::operator=(X&)
4968 QualType ArgType
= Context
.getTypeDeclType(ClassDecl
);
4969 QualType RetType
= Context
.getLValueReferenceType(ArgType
);
4970 if (HasConstCopyAssignment
)
4971 ArgType
= ArgType
.withConst();
4972 ArgType
= Context
.getLValueReferenceType(ArgType
);
4974 // C++ [except.spec]p14:
4975 // An implicitly declared special member function (Clause 12) shall have an
4976 // exception-specification. [...]
4977 ImplicitExceptionSpecification
ExceptSpec(Context
);
4978 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
4979 BaseEnd
= ClassDecl
->bases_end();
4980 Base
!= BaseEnd
; ++Base
) {
4981 CXXRecordDecl
*BaseClassDecl
4982 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
4984 if (!BaseClassDecl
->hasDeclaredCopyAssignment())
4985 DeclareImplicitCopyAssignment(BaseClassDecl
);
4987 if (CXXMethodDecl
*CopyAssign
4988 = BaseClassDecl
->getCopyAssignmentOperator(HasConstCopyAssignment
))
4989 ExceptSpec
.CalledDecl(CopyAssign
);
4991 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
4992 FieldEnd
= ClassDecl
->field_end();
4995 QualType FieldType
= Context
.getBaseElementType((*Field
)->getType());
4996 if (const RecordType
*FieldClassType
= FieldType
->getAs
<RecordType
>()) {
4997 CXXRecordDecl
*FieldClassDecl
4998 = cast
<CXXRecordDecl
>(FieldClassType
->getDecl());
5000 if (!FieldClassDecl
->hasDeclaredCopyAssignment())
5001 DeclareImplicitCopyAssignment(FieldClassDecl
);
5003 if (CXXMethodDecl
*CopyAssign
5004 = FieldClassDecl
->getCopyAssignmentOperator(HasConstCopyAssignment
))
5005 ExceptSpec
.CalledDecl(CopyAssign
);
5009 // An implicitly-declared copy assignment operator is an inline public
5010 // member of its class.
5011 FunctionProtoType::ExtProtoInfo EPI
;
5012 EPI
.HasExceptionSpec
= ExceptSpec
.hasExceptionSpecification();
5013 EPI
.HasAnyExceptionSpec
= ExceptSpec
.hasAnyExceptionSpecification();
5014 EPI
.NumExceptions
= ExceptSpec
.size();
5015 EPI
.Exceptions
= ExceptSpec
.data();
5016 DeclarationName Name
= Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
5017 DeclarationNameInfo
NameInfo(Name
, ClassDecl
->getLocation());
5018 CXXMethodDecl
*CopyAssignment
5019 = CXXMethodDecl::Create(Context
, ClassDecl
, NameInfo
,
5020 Context
.getFunctionType(RetType
, &ArgType
, 1, EPI
),
5021 /*TInfo=*/0, /*isStatic=*/false,
5022 /*StorageClassAsWritten=*/SC_None
,
5024 CopyAssignment
->setAccess(AS_public
);
5025 CopyAssignment
->setImplicit();
5026 CopyAssignment
->setTrivial(ClassDecl
->hasTrivialCopyAssignment());
5028 // Add the parameter to the operator.
5029 ParmVarDecl
*FromParam
= ParmVarDecl::Create(Context
, CopyAssignment
,
5030 ClassDecl
->getLocation(),
5032 ArgType
, /*TInfo=*/0,
5035 CopyAssignment
->setParams(&FromParam
, 1);
5037 // Note that we have added this copy-assignment operator.
5038 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared
;
5040 if (Scope
*S
= getScopeForContext(ClassDecl
))
5041 PushOnScopeChains(CopyAssignment
, S
, false);
5042 ClassDecl
->addDecl(CopyAssignment
);
5044 AddOverriddenMethods(ClassDecl
, CopyAssignment
);
5045 return CopyAssignment
;
5048 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation
,
5049 CXXMethodDecl
*CopyAssignOperator
) {
5050 assert((CopyAssignOperator
->isImplicit() &&
5051 CopyAssignOperator
->isOverloadedOperator() &&
5052 CopyAssignOperator
->getOverloadedOperator() == OO_Equal
&&
5053 !CopyAssignOperator
->isUsed(false)) &&
5054 "DefineImplicitCopyAssignment called for wrong function");
5056 CXXRecordDecl
*ClassDecl
= CopyAssignOperator
->getParent();
5058 if (ClassDecl
->isInvalidDecl() || CopyAssignOperator
->isInvalidDecl()) {
5059 CopyAssignOperator
->setInvalidDecl();
5063 CopyAssignOperator
->setUsed();
5065 ImplicitlyDefinedFunctionScope
Scope(*this, CopyAssignOperator
);
5066 DiagnosticErrorTrap
Trap(Diags
);
5068 // C++0x [class.copy]p30:
5069 // The implicitly-defined or explicitly-defaulted copy assignment operator
5070 // for a non-union class X performs memberwise copy assignment of its
5071 // subobjects. The direct base classes of X are assigned first, in the
5072 // order of their declaration in the base-specifier-list, and then the
5073 // immediate non-static data members of X are assigned, in the order in
5074 // which they were declared in the class definition.
5076 // The statements that form the synthesized function body.
5077 ASTOwningVector
<Stmt
*> Statements(*this);
5079 // The parameter for the "other" object, which we are copying from.
5080 ParmVarDecl
*Other
= CopyAssignOperator
->getParamDecl(0);
5081 Qualifiers OtherQuals
= Other
->getType().getQualifiers();
5082 QualType OtherRefType
= Other
->getType();
5083 if (const LValueReferenceType
*OtherRef
5084 = OtherRefType
->getAs
<LValueReferenceType
>()) {
5085 OtherRefType
= OtherRef
->getPointeeType();
5086 OtherQuals
= OtherRefType
.getQualifiers();
5089 // Our location for everything implicitly-generated.
5090 SourceLocation Loc
= CopyAssignOperator
->getLocation();
5092 // Construct a reference to the "other" object. We'll be using this
5093 // throughout the generated ASTs.
5094 Expr
*OtherRef
= BuildDeclRefExpr(Other
, OtherRefType
, VK_LValue
, Loc
).take();
5095 assert(OtherRef
&& "Reference to parameter cannot fail!");
5097 // Construct the "this" pointer. We'll be using this throughout the generated
5099 Expr
*This
= ActOnCXXThis(Loc
).takeAs
<Expr
>();
5100 assert(This
&& "Reference to this cannot fail!");
5102 // Assign base classes.
5103 bool Invalid
= false;
5104 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
5105 E
= ClassDecl
->bases_end(); Base
!= E
; ++Base
) {
5106 // Form the assignment:
5107 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5108 QualType BaseType
= Base
->getType().getUnqualifiedType();
5109 if (!BaseType
->isRecordType()) {
5114 CXXCastPath BasePath
;
5115 BasePath
.push_back(Base
);
5117 // Construct the "from" expression, which is an implicit cast to the
5118 // appropriately-qualified base type.
5119 Expr
*From
= OtherRef
;
5120 ImpCastExprToType(From
, Context
.getQualifiedType(BaseType
, OtherQuals
),
5121 CK_UncheckedDerivedToBase
,
5122 VK_LValue
, &BasePath
);
5124 // Dereference "this".
5125 ExprResult To
= CreateBuiltinUnaryOp(Loc
, UO_Deref
, This
);
5127 // Implicitly cast "this" to the appropriately-qualified base type.
5128 Expr
*ToE
= To
.takeAs
<Expr
>();
5129 ImpCastExprToType(ToE
,
5130 Context
.getCVRQualifiedType(BaseType
,
5131 CopyAssignOperator
->getTypeQualifiers()),
5132 CK_UncheckedDerivedToBase
,
5133 VK_LValue
, &BasePath
);
5137 StmtResult Copy
= BuildSingleCopyAssign(*this, Loc
, BaseType
,
5139 /*CopyingBaseSubobject=*/true);
5140 if (Copy
.isInvalid()) {
5141 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5142 << CXXCopyAssignment
<< Context
.getTagDeclType(ClassDecl
);
5143 CopyAssignOperator
->setInvalidDecl();
5147 // Success! Record the copy.
5148 Statements
.push_back(Copy
.takeAs
<Expr
>());
5151 // \brief Reference to the __builtin_memcpy function.
5152 Expr
*BuiltinMemCpyRef
= 0;
5153 // \brief Reference to the __builtin_objc_memmove_collectable function.
5154 Expr
*CollectableMemCpyRef
= 0;
5156 // Assign non-static members.
5157 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
5158 FieldEnd
= ClassDecl
->field_end();
5159 Field
!= FieldEnd
; ++Field
) {
5160 // Check for members of reference type; we can't copy those.
5161 if (Field
->getType()->isReferenceType()) {
5162 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
5163 << Context
.getTagDeclType(ClassDecl
) << 0 << Field
->getDeclName();
5164 Diag(Field
->getLocation(), diag::note_declared_at
);
5165 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5166 << CXXCopyAssignment
<< Context
.getTagDeclType(ClassDecl
);
5171 // Check for members of const-qualified, non-class type.
5172 QualType BaseType
= Context
.getBaseElementType(Field
->getType());
5173 if (!BaseType
->getAs
<RecordType
>() && BaseType
.isConstQualified()) {
5174 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
5175 << Context
.getTagDeclType(ClassDecl
) << 1 << Field
->getDeclName();
5176 Diag(Field
->getLocation(), diag::note_declared_at
);
5177 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5178 << CXXCopyAssignment
<< Context
.getTagDeclType(ClassDecl
);
5183 QualType FieldType
= Field
->getType().getNonReferenceType();
5184 if (FieldType
->isIncompleteArrayType()) {
5185 assert(ClassDecl
->hasFlexibleArrayMember() &&
5186 "Incomplete array type is not valid");
5190 // Build references to the field in the object we're copying from and to.
5191 CXXScopeSpec SS
; // Intentionally empty
5192 LookupResult
MemberLookup(*this, Field
->getDeclName(), Loc
,
5194 MemberLookup
.addDecl(*Field
);
5195 MemberLookup
.resolveKind();
5196 ExprResult From
= BuildMemberReferenceExpr(OtherRef
, OtherRefType
,
5197 Loc
, /*IsArrow=*/false,
5198 SS
, 0, MemberLookup
, 0);
5199 ExprResult To
= BuildMemberReferenceExpr(This
, This
->getType(),
5200 Loc
, /*IsArrow=*/true,
5201 SS
, 0, MemberLookup
, 0);
5202 assert(!From
.isInvalid() && "Implicit field reference cannot fail");
5203 assert(!To
.isInvalid() && "Implicit field reference cannot fail");
5205 // If the field should be copied with __builtin_memcpy rather than via
5206 // explicit assignments, do so. This optimization only applies for arrays
5207 // of scalars and arrays of class type with trivial copy-assignment
5209 if (FieldType
->isArrayType() &&
5210 (!BaseType
->isRecordType() ||
5211 cast
<CXXRecordDecl
>(BaseType
->getAs
<RecordType
>()->getDecl())
5212 ->hasTrivialCopyAssignment())) {
5213 // Compute the size of the memory buffer to be copied.
5214 QualType SizeType
= Context
.getSizeType();
5215 llvm::APInt
Size(Context
.getTypeSize(SizeType
),
5216 Context
.getTypeSizeInChars(BaseType
).getQuantity());
5217 for (const ConstantArrayType
*Array
5218 = Context
.getAsConstantArrayType(FieldType
);
5220 Array
= Context
.getAsConstantArrayType(Array
->getElementType())) {
5221 llvm::APInt ArraySize
5222 = Array
->getSize().zextOrTrunc(Size
.getBitWidth());
5226 // Take the address of the field references for "from" and "to".
5227 From
= CreateBuiltinUnaryOp(Loc
, UO_AddrOf
, From
.get());
5228 To
= CreateBuiltinUnaryOp(Loc
, UO_AddrOf
, To
.get());
5230 bool NeedsCollectableMemCpy
=
5231 (BaseType
->isRecordType() &&
5232 BaseType
->getAs
<RecordType
>()->getDecl()->hasObjectMember());
5234 if (NeedsCollectableMemCpy
) {
5235 if (!CollectableMemCpyRef
) {
5236 // Create a reference to the __builtin_objc_memmove_collectable function.
5237 LookupResult
R(*this,
5238 &Context
.Idents
.get("__builtin_objc_memmove_collectable"),
5239 Loc
, LookupOrdinaryName
);
5240 LookupName(R
, TUScope
, true);
5242 FunctionDecl
*CollectableMemCpy
= R
.getAsSingle
<FunctionDecl
>();
5243 if (!CollectableMemCpy
) {
5244 // Something went horribly wrong earlier, and we will have
5245 // complained about it.
5250 CollectableMemCpyRef
= BuildDeclRefExpr(CollectableMemCpy
,
5251 CollectableMemCpy
->getType(),
5252 VK_LValue
, Loc
, 0).take();
5253 assert(CollectableMemCpyRef
&& "Builtin reference cannot fail");
5256 // Create a reference to the __builtin_memcpy builtin function.
5257 else if (!BuiltinMemCpyRef
) {
5258 LookupResult
R(*this, &Context
.Idents
.get("__builtin_memcpy"), Loc
,
5259 LookupOrdinaryName
);
5260 LookupName(R
, TUScope
, true);
5262 FunctionDecl
*BuiltinMemCpy
= R
.getAsSingle
<FunctionDecl
>();
5263 if (!BuiltinMemCpy
) {
5264 // Something went horribly wrong earlier, and we will have complained
5270 BuiltinMemCpyRef
= BuildDeclRefExpr(BuiltinMemCpy
,
5271 BuiltinMemCpy
->getType(),
5272 VK_LValue
, Loc
, 0).take();
5273 assert(BuiltinMemCpyRef
&& "Builtin reference cannot fail");
5276 ASTOwningVector
<Expr
*> CallArgs(*this);
5277 CallArgs
.push_back(To
.takeAs
<Expr
>());
5278 CallArgs
.push_back(From
.takeAs
<Expr
>());
5279 CallArgs
.push_back(IntegerLiteral::Create(Context
, Size
, SizeType
, Loc
));
5280 ExprResult Call
= ExprError();
5281 if (NeedsCollectableMemCpy
)
5282 Call
= ActOnCallExpr(/*Scope=*/0,
5283 CollectableMemCpyRef
,
5284 Loc
, move_arg(CallArgs
),
5287 Call
= ActOnCallExpr(/*Scope=*/0,
5289 Loc
, move_arg(CallArgs
),
5292 assert(!Call
.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5293 Statements
.push_back(Call
.takeAs
<Expr
>());
5297 // Build the copy of this field.
5298 StmtResult Copy
= BuildSingleCopyAssign(*this, Loc
, FieldType
,
5299 To
.get(), From
.get(),
5300 /*CopyingBaseSubobject=*/false);
5301 if (Copy
.isInvalid()) {
5302 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5303 << CXXCopyAssignment
<< Context
.getTagDeclType(ClassDecl
);
5304 CopyAssignOperator
->setInvalidDecl();
5308 // Success! Record the copy.
5309 Statements
.push_back(Copy
.takeAs
<Stmt
>());
5313 // Add a "return *this;"
5314 ExprResult ThisObj
= CreateBuiltinUnaryOp(Loc
, UO_Deref
, This
);
5316 StmtResult Return
= ActOnReturnStmt(Loc
, ThisObj
.get());
5317 if (Return
.isInvalid())
5320 Statements
.push_back(Return
.takeAs
<Stmt
>());
5322 if (Trap
.hasErrorOccurred()) {
5323 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5324 << CXXCopyAssignment
<< Context
.getTagDeclType(ClassDecl
);
5331 CopyAssignOperator
->setInvalidDecl();
5335 StmtResult Body
= ActOnCompoundStmt(Loc
, Loc
, move_arg(Statements
),
5336 /*isStmtExpr=*/false);
5337 assert(!Body
.isInvalid() && "Compound statement creation cannot fail");
5338 CopyAssignOperator
->setBody(Body
.takeAs
<Stmt
>());
5341 CXXConstructorDecl
*Sema::DeclareImplicitCopyConstructor(
5342 CXXRecordDecl
*ClassDecl
) {
5343 // C++ [class.copy]p4:
5344 // If the class definition does not explicitly declare a copy
5345 // constructor, one is declared implicitly.
5347 // C++ [class.copy]p5:
5348 // The implicitly-declared copy constructor for a class X will
5354 bool HasConstCopyConstructor
= true;
5356 // -- each direct or virtual base class B of X has a copy
5357 // constructor whose first parameter is of type const B& or
5358 // const volatile B&, and
5359 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
5360 BaseEnd
= ClassDecl
->bases_end();
5361 HasConstCopyConstructor
&& Base
!= BaseEnd
;
5363 // Virtual bases are handled below.
5364 if (Base
->isVirtual())
5367 CXXRecordDecl
*BaseClassDecl
5368 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
5369 if (!BaseClassDecl
->hasDeclaredCopyConstructor())
5370 DeclareImplicitCopyConstructor(BaseClassDecl
);
5372 HasConstCopyConstructor
5373 = BaseClassDecl
->hasConstCopyConstructor(Context
);
5376 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->vbases_begin(),
5377 BaseEnd
= ClassDecl
->vbases_end();
5378 HasConstCopyConstructor
&& Base
!= BaseEnd
;
5380 CXXRecordDecl
*BaseClassDecl
5381 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
5382 if (!BaseClassDecl
->hasDeclaredCopyConstructor())
5383 DeclareImplicitCopyConstructor(BaseClassDecl
);
5385 HasConstCopyConstructor
5386 = BaseClassDecl
->hasConstCopyConstructor(Context
);
5389 // -- for all the nonstatic data members of X that are of a
5390 // class type M (or array thereof), each such class type
5391 // has a copy constructor whose first parameter is of type
5392 // const M& or const volatile M&.
5393 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
5394 FieldEnd
= ClassDecl
->field_end();
5395 HasConstCopyConstructor
&& Field
!= FieldEnd
;
5397 QualType FieldType
= Context
.getBaseElementType((*Field
)->getType());
5398 if (const RecordType
*FieldClassType
= FieldType
->getAs
<RecordType
>()) {
5399 CXXRecordDecl
*FieldClassDecl
5400 = cast
<CXXRecordDecl
>(FieldClassType
->getDecl());
5401 if (!FieldClassDecl
->hasDeclaredCopyConstructor())
5402 DeclareImplicitCopyConstructor(FieldClassDecl
);
5404 HasConstCopyConstructor
5405 = FieldClassDecl
->hasConstCopyConstructor(Context
);
5409 // Otherwise, the implicitly declared copy constructor will have
5413 QualType ClassType
= Context
.getTypeDeclType(ClassDecl
);
5414 QualType ArgType
= ClassType
;
5415 if (HasConstCopyConstructor
)
5416 ArgType
= ArgType
.withConst();
5417 ArgType
= Context
.getLValueReferenceType(ArgType
);
5419 // C++ [except.spec]p14:
5420 // An implicitly declared special member function (Clause 12) shall have an
5421 // exception-specification. [...]
5422 ImplicitExceptionSpecification
ExceptSpec(Context
);
5423 unsigned Quals
= HasConstCopyConstructor
? Qualifiers::Const
: 0;
5424 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
5425 BaseEnd
= ClassDecl
->bases_end();
5428 // Virtual bases are handled below.
5429 if (Base
->isVirtual())
5432 CXXRecordDecl
*BaseClassDecl
5433 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
5434 if (!BaseClassDecl
->hasDeclaredCopyConstructor())
5435 DeclareImplicitCopyConstructor(BaseClassDecl
);
5437 if (CXXConstructorDecl
*CopyConstructor
5438 = BaseClassDecl
->getCopyConstructor(Context
, Quals
))
5439 ExceptSpec
.CalledDecl(CopyConstructor
);
5441 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->vbases_begin(),
5442 BaseEnd
= ClassDecl
->vbases_end();
5445 CXXRecordDecl
*BaseClassDecl
5446 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
5447 if (!BaseClassDecl
->hasDeclaredCopyConstructor())
5448 DeclareImplicitCopyConstructor(BaseClassDecl
);
5450 if (CXXConstructorDecl
*CopyConstructor
5451 = BaseClassDecl
->getCopyConstructor(Context
, Quals
))
5452 ExceptSpec
.CalledDecl(CopyConstructor
);
5454 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
5455 FieldEnd
= ClassDecl
->field_end();
5458 QualType FieldType
= Context
.getBaseElementType((*Field
)->getType());
5459 if (const RecordType
*FieldClassType
= FieldType
->getAs
<RecordType
>()) {
5460 CXXRecordDecl
*FieldClassDecl
5461 = cast
<CXXRecordDecl
>(FieldClassType
->getDecl());
5462 if (!FieldClassDecl
->hasDeclaredCopyConstructor())
5463 DeclareImplicitCopyConstructor(FieldClassDecl
);
5465 if (CXXConstructorDecl
*CopyConstructor
5466 = FieldClassDecl
->getCopyConstructor(Context
, Quals
))
5467 ExceptSpec
.CalledDecl(CopyConstructor
);
5471 // An implicitly-declared copy constructor is an inline public
5472 // member of its class.
5473 FunctionProtoType::ExtProtoInfo EPI
;
5474 EPI
.HasExceptionSpec
= ExceptSpec
.hasExceptionSpecification();
5475 EPI
.HasAnyExceptionSpec
= ExceptSpec
.hasAnyExceptionSpecification();
5476 EPI
.NumExceptions
= ExceptSpec
.size();
5477 EPI
.Exceptions
= ExceptSpec
.data();
5478 DeclarationName Name
5479 = Context
.DeclarationNames
.getCXXConstructorName(
5480 Context
.getCanonicalType(ClassType
));
5481 DeclarationNameInfo
NameInfo(Name
, ClassDecl
->getLocation());
5482 CXXConstructorDecl
*CopyConstructor
5483 = CXXConstructorDecl::Create(Context
, ClassDecl
, NameInfo
,
5484 Context
.getFunctionType(Context
.VoidTy
,
5487 /*isExplicit=*/false,
5489 /*isImplicitlyDeclared=*/true);
5490 CopyConstructor
->setAccess(AS_public
);
5491 CopyConstructor
->setImplicit();
5492 CopyConstructor
->setTrivial(ClassDecl
->hasTrivialCopyConstructor());
5494 // Note that we have declared this constructor.
5495 ++ASTContext::NumImplicitCopyConstructorsDeclared
;
5497 // Add the parameter to the constructor.
5498 ParmVarDecl
*FromParam
= ParmVarDecl::Create(Context
, CopyConstructor
,
5499 ClassDecl
->getLocation(),
5500 /*IdentifierInfo=*/0,
5501 ArgType
, /*TInfo=*/0,
5504 CopyConstructor
->setParams(&FromParam
, 1);
5505 if (Scope
*S
= getScopeForContext(ClassDecl
))
5506 PushOnScopeChains(CopyConstructor
, S
, false);
5507 ClassDecl
->addDecl(CopyConstructor
);
5509 return CopyConstructor
;
5512 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation
,
5513 CXXConstructorDecl
*CopyConstructor
,
5514 unsigned TypeQuals
) {
5515 assert((CopyConstructor
->isImplicit() &&
5516 CopyConstructor
->isCopyConstructor(TypeQuals
) &&
5517 !CopyConstructor
->isUsed(false)) &&
5518 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
5520 CXXRecordDecl
*ClassDecl
= CopyConstructor
->getParent();
5521 assert(ClassDecl
&& "DefineImplicitCopyConstructor - invalid constructor");
5523 ImplicitlyDefinedFunctionScope
Scope(*this, CopyConstructor
);
5524 DiagnosticErrorTrap
Trap(Diags
);
5526 if (SetCtorInitializers(CopyConstructor
, 0, 0, /*AnyErrors=*/false) ||
5527 Trap
.hasErrorOccurred()) {
5528 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5529 << CXXCopyConstructor
<< Context
.getTagDeclType(ClassDecl
);
5530 CopyConstructor
->setInvalidDecl();
5532 CopyConstructor
->setBody(ActOnCompoundStmt(CopyConstructor
->getLocation(),
5533 CopyConstructor
->getLocation(),
5534 MultiStmtArg(*this, 0, 0),
5535 /*isStmtExpr=*/false)
5539 CopyConstructor
->setUsed();
5543 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc
, QualType DeclInitType
,
5544 CXXConstructorDecl
*Constructor
,
5545 MultiExprArg ExprArgs
,
5546 bool RequiresZeroInit
,
5547 unsigned ConstructKind
,
5548 SourceRange ParenRange
) {
5549 bool Elidable
= false;
5551 // C++0x [class.copy]p34:
5552 // When certain criteria are met, an implementation is allowed to
5553 // omit the copy/move construction of a class object, even if the
5554 // copy/move constructor and/or destructor for the object have
5555 // side effects. [...]
5556 // - when a temporary class object that has not been bound to a
5557 // reference (12.2) would be copied/moved to a class object
5558 // with the same cv-unqualified type, the copy/move operation
5559 // can be omitted by constructing the temporary object
5560 // directly into the target of the omitted copy/move
5561 if (ConstructKind
== CXXConstructExpr::CK_Complete
&&
5562 Constructor
->isCopyOrMoveConstructor() && ExprArgs
.size() >= 1) {
5563 Expr
*SubExpr
= ((Expr
**)ExprArgs
.get())[0];
5564 Elidable
= SubExpr
->isTemporaryObject(Context
, Constructor
->getParent());
5567 return BuildCXXConstructExpr(ConstructLoc
, DeclInitType
, Constructor
,
5568 Elidable
, move(ExprArgs
), RequiresZeroInit
,
5569 ConstructKind
, ParenRange
);
5572 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5573 /// including handling of its default argument expressions.
5575 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc
, QualType DeclInitType
,
5576 CXXConstructorDecl
*Constructor
, bool Elidable
,
5577 MultiExprArg ExprArgs
,
5578 bool RequiresZeroInit
,
5579 unsigned ConstructKind
,
5580 SourceRange ParenRange
) {
5581 unsigned NumExprs
= ExprArgs
.size();
5582 Expr
**Exprs
= (Expr
**)ExprArgs
.release();
5584 MarkDeclarationReferenced(ConstructLoc
, Constructor
);
5585 return Owned(CXXConstructExpr::Create(Context
, DeclInitType
, ConstructLoc
,
5586 Constructor
, Elidable
, Exprs
, NumExprs
,
5588 static_cast<CXXConstructExpr::ConstructionKind
>(ConstructKind
),
5592 bool Sema::InitializeVarWithConstructor(VarDecl
*VD
,
5593 CXXConstructorDecl
*Constructor
,
5594 MultiExprArg Exprs
) {
5595 // FIXME: Provide the correct paren SourceRange when available.
5596 ExprResult TempResult
=
5597 BuildCXXConstructExpr(VD
->getLocation(), VD
->getType(), Constructor
,
5598 move(Exprs
), false, CXXConstructExpr::CK_Complete
,
5600 if (TempResult
.isInvalid())
5603 Expr
*Temp
= TempResult
.takeAs
<Expr
>();
5604 CheckImplicitConversions(Temp
, VD
->getLocation());
5605 MarkDeclarationReferenced(VD
->getLocation(), Constructor
);
5606 Temp
= MaybeCreateExprWithCleanups(Temp
);
5612 void Sema::FinalizeVarWithDestructor(VarDecl
*VD
, const RecordType
*Record
) {
5613 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(Record
->getDecl());
5614 if (!ClassDecl
->isInvalidDecl() && !VD
->isInvalidDecl() &&
5615 !ClassDecl
->hasTrivialDestructor() && !ClassDecl
->isDependentContext()) {
5616 CXXDestructorDecl
*Destructor
= LookupDestructor(ClassDecl
);
5617 MarkDeclarationReferenced(VD
->getLocation(), Destructor
);
5618 CheckDestructorAccess(VD
->getLocation(), Destructor
,
5619 PDiag(diag::err_access_dtor_var
)
5620 << VD
->getDeclName()
5623 // TODO: this should be re-enabled for static locals by !CXAAtExit
5624 if (!VD
->isInvalidDecl() && VD
->hasGlobalStorage() && !VD
->isStaticLocal())
5625 Diag(VD
->getLocation(), diag::warn_global_destructor
);
5629 /// AddCXXDirectInitializerToDecl - This action is called immediately after
5630 /// ActOnDeclarator, when a C++ direct initializer is present.
5631 /// e.g: "int x(1);"
5632 void Sema::AddCXXDirectInitializerToDecl(Decl
*RealDecl
,
5633 SourceLocation LParenLoc
,
5635 SourceLocation RParenLoc
) {
5636 assert(Exprs
.size() != 0 && Exprs
.get() && "missing expressions");
5638 // If there is no declaration, there was an error parsing it. Just ignore
5643 VarDecl
*VDecl
= dyn_cast
<VarDecl
>(RealDecl
);
5645 Diag(RealDecl
->getLocation(), diag::err_illegal_initializer
);
5646 RealDecl
->setInvalidDecl();
5650 // We will represent direct-initialization similarly to copy-initialization:
5651 // int x(1); -as-> int x = 1;
5652 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5654 // Clients that want to distinguish between the two forms, can check for
5655 // direct initializer using VarDecl::hasCXXDirectInitializer().
5656 // A major benefit is that clients that don't particularly care about which
5657 // exactly form was it (like the CodeGen) can handle both cases without
5658 // special case code.
5661 // The form of initialization (using parentheses or '=') is generally
5662 // insignificant, but does matter when the entity being initialized has a
5665 if (!VDecl
->getType()->isDependentType() &&
5666 RequireCompleteType(VDecl
->getLocation(), VDecl
->getType(),
5667 diag::err_typecheck_decl_incomplete_type
)) {
5668 VDecl
->setInvalidDecl();
5672 // The variable can not have an abstract class type.
5673 if (RequireNonAbstractType(VDecl
->getLocation(), VDecl
->getType(),
5674 diag::err_abstract_type_in_decl
,
5675 AbstractVariableType
))
5676 VDecl
->setInvalidDecl();
5679 if ((Def
= VDecl
->getDefinition()) && Def
!= VDecl
) {
5680 Diag(VDecl
->getLocation(), diag::err_redefinition
)
5681 << VDecl
->getDeclName();
5682 Diag(Def
->getLocation(), diag::note_previous_definition
);
5683 VDecl
->setInvalidDecl();
5687 // C++ [class.static.data]p4
5688 // If a static data member is of const integral or const
5689 // enumeration type, its declaration in the class definition can
5690 // specify a constant-initializer which shall be an integral
5691 // constant expression (5.19). In that case, the member can appear
5692 // in integral constant expressions. The member shall still be
5693 // defined in a namespace scope if it is used in the program and the
5694 // namespace scope definition shall not contain an initializer.
5696 // We already performed a redefinition check above, but for static
5697 // data members we also need to check whether there was an in-class
5698 // declaration with an initializer.
5699 const VarDecl
* PrevInit
= 0;
5700 if (VDecl
->isStaticDataMember() && VDecl
->getAnyInitializer(PrevInit
)) {
5701 Diag(VDecl
->getLocation(), diag::err_redefinition
) << VDecl
->getDeclName();
5702 Diag(PrevInit
->getLocation(), diag::note_previous_definition
);
5706 bool IsDependent
= false;
5707 for (unsigned I
= 0, N
= Exprs
.size(); I
!= N
; ++I
) {
5708 if (DiagnoseUnexpandedParameterPack(Exprs
.get()[I
], UPPC_Expression
)) {
5709 VDecl
->setInvalidDecl();
5713 if (Exprs
.get()[I
]->isTypeDependent())
5717 // If either the declaration has a dependent type or if any of the
5718 // expressions is type-dependent, we represent the initialization
5719 // via a ParenListExpr for later use during template instantiation.
5720 if (VDecl
->getType()->isDependentType() || IsDependent
) {
5721 // Let clients know that initialization was done with a direct initializer.
5722 VDecl
->setCXXDirectInitializer(true);
5724 // Store the initialization expressions as a ParenListExpr.
5725 unsigned NumExprs
= Exprs
.size();
5726 VDecl
->setInit(new (Context
) ParenListExpr(Context
, LParenLoc
,
5727 (Expr
**)Exprs
.release(),
5728 NumExprs
, RParenLoc
));
5732 // Capture the variable that is being initialized and the style of
5734 InitializedEntity Entity
= InitializedEntity::InitializeVariable(VDecl
);
5736 // FIXME: Poor source location information.
5737 InitializationKind Kind
5738 = InitializationKind::CreateDirect(VDecl
->getLocation(),
5739 LParenLoc
, RParenLoc
);
5741 InitializationSequence
InitSeq(*this, Entity
, Kind
,
5742 Exprs
.get(), Exprs
.size());
5743 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, move(Exprs
));
5744 if (Result
.isInvalid()) {
5745 VDecl
->setInvalidDecl();
5749 CheckImplicitConversions(Result
.get(), LParenLoc
);
5751 Result
= MaybeCreateExprWithCleanups(Result
);
5752 VDecl
->setInit(Result
.takeAs
<Expr
>());
5753 VDecl
->setCXXDirectInitializer(true);
5755 CheckCompleteVariableDeclaration(VDecl
);
5758 /// \brief Given a constructor and the set of arguments provided for the
5759 /// constructor, convert the arguments and add any required default arguments
5760 /// to form a proper call to this constructor.
5762 /// \returns true if an error occurred, false otherwise.
5764 Sema::CompleteConstructorCall(CXXConstructorDecl
*Constructor
,
5765 MultiExprArg ArgsPtr
,
5767 ASTOwningVector
<Expr
*> &ConvertedArgs
) {
5768 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
5769 unsigned NumArgs
= ArgsPtr
.size();
5770 Expr
**Args
= (Expr
**)ArgsPtr
.get();
5772 const FunctionProtoType
*Proto
5773 = Constructor
->getType()->getAs
<FunctionProtoType
>();
5774 assert(Proto
&& "Constructor without a prototype?");
5775 unsigned NumArgsInProto
= Proto
->getNumArgs();
5777 // If too few arguments are available, we'll fill in the rest with defaults.
5778 if (NumArgs
< NumArgsInProto
)
5779 ConvertedArgs
.reserve(NumArgsInProto
);
5781 ConvertedArgs
.reserve(NumArgs
);
5783 VariadicCallType CallType
=
5784 Proto
->isVariadic() ? VariadicConstructor
: VariadicDoesNotApply
;
5785 llvm::SmallVector
<Expr
*, 8> AllArgs
;
5786 bool Invalid
= GatherArgumentsForCall(Loc
, Constructor
,
5787 Proto
, 0, Args
, NumArgs
, AllArgs
,
5789 for (unsigned i
=0, size
= AllArgs
.size(); i
< size
; i
++)
5790 ConvertedArgs
.push_back(AllArgs
[i
]);
5795 CheckOperatorNewDeleteDeclarationScope(Sema
&SemaRef
,
5796 const FunctionDecl
*FnDecl
) {
5797 const DeclContext
*DC
= FnDecl
->getDeclContext()->getRedeclContext();
5798 if (isa
<NamespaceDecl
>(DC
)) {
5799 return SemaRef
.Diag(FnDecl
->getLocation(),
5800 diag::err_operator_new_delete_declared_in_namespace
)
5801 << FnDecl
->getDeclName();
5804 if (isa
<TranslationUnitDecl
>(DC
) &&
5805 FnDecl
->getStorageClass() == SC_Static
) {
5806 return SemaRef
.Diag(FnDecl
->getLocation(),
5807 diag::err_operator_new_delete_declared_static
)
5808 << FnDecl
->getDeclName();
5815 CheckOperatorNewDeleteTypes(Sema
&SemaRef
, const FunctionDecl
*FnDecl
,
5816 CanQualType ExpectedResultType
,
5817 CanQualType ExpectedFirstParamType
,
5818 unsigned DependentParamTypeDiag
,
5819 unsigned InvalidParamTypeDiag
) {
5820 QualType ResultType
=
5821 FnDecl
->getType()->getAs
<FunctionType
>()->getResultType();
5823 // Check that the result type is not dependent.
5824 if (ResultType
->isDependentType())
5825 return SemaRef
.Diag(FnDecl
->getLocation(),
5826 diag::err_operator_new_delete_dependent_result_type
)
5827 << FnDecl
->getDeclName() << ExpectedResultType
;
5829 // Check that the result type is what we expect.
5830 if (SemaRef
.Context
.getCanonicalType(ResultType
) != ExpectedResultType
)
5831 return SemaRef
.Diag(FnDecl
->getLocation(),
5832 diag::err_operator_new_delete_invalid_result_type
)
5833 << FnDecl
->getDeclName() << ExpectedResultType
;
5835 // A function template must have at least 2 parameters.
5836 if (FnDecl
->getDescribedFunctionTemplate() && FnDecl
->getNumParams() < 2)
5837 return SemaRef
.Diag(FnDecl
->getLocation(),
5838 diag::err_operator_new_delete_template_too_few_parameters
)
5839 << FnDecl
->getDeclName();
5841 // The function decl must have at least 1 parameter.
5842 if (FnDecl
->getNumParams() == 0)
5843 return SemaRef
.Diag(FnDecl
->getLocation(),
5844 diag::err_operator_new_delete_too_few_parameters
)
5845 << FnDecl
->getDeclName();
5847 // Check the the first parameter type is not dependent.
5848 QualType FirstParamType
= FnDecl
->getParamDecl(0)->getType();
5849 if (FirstParamType
->isDependentType())
5850 return SemaRef
.Diag(FnDecl
->getLocation(), DependentParamTypeDiag
)
5851 << FnDecl
->getDeclName() << ExpectedFirstParamType
;
5853 // Check that the first parameter type is what we expect.
5854 if (SemaRef
.Context
.getCanonicalType(FirstParamType
).getUnqualifiedType() !=
5855 ExpectedFirstParamType
)
5856 return SemaRef
.Diag(FnDecl
->getLocation(), InvalidParamTypeDiag
)
5857 << FnDecl
->getDeclName() << ExpectedFirstParamType
;
5863 CheckOperatorNewDeclaration(Sema
&SemaRef
, const FunctionDecl
*FnDecl
) {
5864 // C++ [basic.stc.dynamic.allocation]p1:
5865 // A program is ill-formed if an allocation function is declared in a
5866 // namespace scope other than global scope or declared static in global
5868 if (CheckOperatorNewDeleteDeclarationScope(SemaRef
, FnDecl
))
5871 CanQualType SizeTy
=
5872 SemaRef
.Context
.getCanonicalType(SemaRef
.Context
.getSizeType());
5874 // C++ [basic.stc.dynamic.allocation]p1:
5875 // The return type shall be void*. The first parameter shall have type
5877 if (CheckOperatorNewDeleteTypes(SemaRef
, FnDecl
, SemaRef
.Context
.VoidPtrTy
,
5879 diag::err_operator_new_dependent_param_type
,
5880 diag::err_operator_new_param_type
))
5883 // C++ [basic.stc.dynamic.allocation]p1:
5884 // The first parameter shall not have an associated default argument.
5885 if (FnDecl
->getParamDecl(0)->hasDefaultArg())
5886 return SemaRef
.Diag(FnDecl
->getLocation(),
5887 diag::err_operator_new_default_arg
)
5888 << FnDecl
->getDeclName() << FnDecl
->getParamDecl(0)->getDefaultArgRange();
5894 CheckOperatorDeleteDeclaration(Sema
&SemaRef
, const FunctionDecl
*FnDecl
) {
5895 // C++ [basic.stc.dynamic.deallocation]p1:
5896 // A program is ill-formed if deallocation functions are declared in a
5897 // namespace scope other than global scope or declared static in global
5899 if (CheckOperatorNewDeleteDeclarationScope(SemaRef
, FnDecl
))
5902 // C++ [basic.stc.dynamic.deallocation]p2:
5903 // Each deallocation function shall return void and its first parameter
5905 if (CheckOperatorNewDeleteTypes(SemaRef
, FnDecl
, SemaRef
.Context
.VoidTy
,
5906 SemaRef
.Context
.VoidPtrTy
,
5907 diag::err_operator_delete_dependent_param_type
,
5908 diag::err_operator_delete_param_type
))
5914 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
5915 /// of this overloaded operator is well-formed. If so, returns false;
5916 /// otherwise, emits appropriate diagnostics and returns true.
5917 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl
*FnDecl
) {
5918 assert(FnDecl
&& FnDecl
->isOverloadedOperator() &&
5919 "Expected an overloaded operator declaration");
5921 OverloadedOperatorKind Op
= FnDecl
->getOverloadedOperator();
5923 // C++ [over.oper]p5:
5924 // The allocation and deallocation functions, operator new,
5925 // operator new[], operator delete and operator delete[], are
5926 // described completely in 3.7.3. The attributes and restrictions
5927 // found in the rest of this subclause do not apply to them unless
5928 // explicitly stated in 3.7.3.
5929 if (Op
== OO_Delete
|| Op
== OO_Array_Delete
)
5930 return CheckOperatorDeleteDeclaration(*this, FnDecl
);
5932 if (Op
== OO_New
|| Op
== OO_Array_New
)
5933 return CheckOperatorNewDeclaration(*this, FnDecl
);
5935 // C++ [over.oper]p6:
5936 // An operator function shall either be a non-static member
5937 // function or be a non-member function and have at least one
5938 // parameter whose type is a class, a reference to a class, an
5939 // enumeration, or a reference to an enumeration.
5940 if (CXXMethodDecl
*MethodDecl
= dyn_cast
<CXXMethodDecl
>(FnDecl
)) {
5941 if (MethodDecl
->isStatic())
5942 return Diag(FnDecl
->getLocation(),
5943 diag::err_operator_overload_static
) << FnDecl
->getDeclName();
5945 bool ClassOrEnumParam
= false;
5946 for (FunctionDecl::param_iterator Param
= FnDecl
->param_begin(),
5947 ParamEnd
= FnDecl
->param_end();
5948 Param
!= ParamEnd
; ++Param
) {
5949 QualType ParamType
= (*Param
)->getType().getNonReferenceType();
5950 if (ParamType
->isDependentType() || ParamType
->isRecordType() ||
5951 ParamType
->isEnumeralType()) {
5952 ClassOrEnumParam
= true;
5957 if (!ClassOrEnumParam
)
5958 return Diag(FnDecl
->getLocation(),
5959 diag::err_operator_overload_needs_class_or_enum
)
5960 << FnDecl
->getDeclName();
5963 // C++ [over.oper]p8:
5964 // An operator function cannot have default arguments (8.3.6),
5965 // except where explicitly stated below.
5967 // Only the function-call operator allows default arguments
5968 // (C++ [over.call]p1).
5969 if (Op
!= OO_Call
) {
5970 for (FunctionDecl::param_iterator Param
= FnDecl
->param_begin();
5971 Param
!= FnDecl
->param_end(); ++Param
) {
5972 if ((*Param
)->hasDefaultArg())
5973 return Diag((*Param
)->getLocation(),
5974 diag::err_operator_overload_default_arg
)
5975 << FnDecl
->getDeclName() << (*Param
)->getDefaultArgRange();
5979 static const bool OperatorUses
[NUM_OVERLOADED_OPERATORS
][3] = {
5980 { false, false, false }
5981 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
5982 , { Unary, Binary, MemberOnly }
5983 #include "clang/Basic/OperatorKinds.def"
5986 bool CanBeUnaryOperator
= OperatorUses
[Op
][0];
5987 bool CanBeBinaryOperator
= OperatorUses
[Op
][1];
5988 bool MustBeMemberOperator
= OperatorUses
[Op
][2];
5990 // C++ [over.oper]p8:
5991 // [...] Operator functions cannot have more or fewer parameters
5992 // than the number required for the corresponding operator, as
5993 // described in the rest of this subclause.
5994 unsigned NumParams
= FnDecl
->getNumParams()
5995 + (isa
<CXXMethodDecl
>(FnDecl
)? 1 : 0);
5996 if (Op
!= OO_Call
&&
5997 ((NumParams
== 1 && !CanBeUnaryOperator
) ||
5998 (NumParams
== 2 && !CanBeBinaryOperator
) ||
5999 (NumParams
< 1) || (NumParams
> 2))) {
6000 // We have the wrong number of parameters.
6002 if (CanBeUnaryOperator
&& CanBeBinaryOperator
) {
6003 ErrorKind
= 2; // 2 -> unary or binary.
6004 } else if (CanBeUnaryOperator
) {
6005 ErrorKind
= 0; // 0 -> unary
6007 assert(CanBeBinaryOperator
&&
6008 "All non-call overloaded operators are unary or binary!");
6009 ErrorKind
= 1; // 1 -> binary
6012 return Diag(FnDecl
->getLocation(), diag::err_operator_overload_must_be
)
6013 << FnDecl
->getDeclName() << NumParams
<< ErrorKind
;
6016 // Overloaded operators other than operator() cannot be variadic.
6017 if (Op
!= OO_Call
&&
6018 FnDecl
->getType()->getAs
<FunctionProtoType
>()->isVariadic()) {
6019 return Diag(FnDecl
->getLocation(), diag::err_operator_overload_variadic
)
6020 << FnDecl
->getDeclName();
6023 // Some operators must be non-static member functions.
6024 if (MustBeMemberOperator
&& !isa
<CXXMethodDecl
>(FnDecl
)) {
6025 return Diag(FnDecl
->getLocation(),
6026 diag::err_operator_overload_must_be_member
)
6027 << FnDecl
->getDeclName();
6030 // C++ [over.inc]p1:
6031 // The user-defined function called operator++ implements the
6032 // prefix and postfix ++ operator. If this function is a member
6033 // function with no parameters, or a non-member function with one
6034 // parameter of class or enumeration type, it defines the prefix
6035 // increment operator ++ for objects of that type. If the function
6036 // is a member function with one parameter (which shall be of type
6037 // int) or a non-member function with two parameters (the second
6038 // of which shall be of type int), it defines the postfix
6039 // increment operator ++ for objects of that type.
6040 if ((Op
== OO_PlusPlus
|| Op
== OO_MinusMinus
) && NumParams
== 2) {
6041 ParmVarDecl
*LastParam
= FnDecl
->getParamDecl(FnDecl
->getNumParams() - 1);
6042 bool ParamIsInt
= false;
6043 if (const BuiltinType
*BT
= LastParam
->getType()->getAs
<BuiltinType
>())
6044 ParamIsInt
= BT
->getKind() == BuiltinType::Int
;
6047 return Diag(LastParam
->getLocation(),
6048 diag::err_operator_overload_post_incdec_must_be_int
)
6049 << LastParam
->getType() << (Op
== OO_MinusMinus
);
6055 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6056 /// of this literal operator function is well-formed. If so, returns
6057 /// false; otherwise, emits appropriate diagnostics and returns true.
6058 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl
*FnDecl
) {
6059 DeclContext
*DC
= FnDecl
->getDeclContext();
6060 Decl::Kind Kind
= DC
->getDeclKind();
6061 if (Kind
!= Decl::TranslationUnit
&& Kind
!= Decl::Namespace
&&
6062 Kind
!= Decl::LinkageSpec
) {
6063 Diag(FnDecl
->getLocation(), diag::err_literal_operator_outside_namespace
)
6064 << FnDecl
->getDeclName();
6070 // template <char...> type operator "" name() is the only valid template
6071 // signature, and the only valid signature with no parameters.
6072 if (FnDecl
->param_size() == 0) {
6073 if (FunctionTemplateDecl
*TpDecl
= FnDecl
->getDescribedFunctionTemplate()) {
6074 // Must have only one template parameter
6075 TemplateParameterList
*Params
= TpDecl
->getTemplateParameters();
6076 if (Params
->size() == 1) {
6077 NonTypeTemplateParmDecl
*PmDecl
=
6078 cast
<NonTypeTemplateParmDecl
>(Params
->getParam(0));
6080 // The template parameter must be a char parameter pack.
6081 if (PmDecl
&& PmDecl
->isTemplateParameterPack() &&
6082 Context
.hasSameType(PmDecl
->getType(), Context
.CharTy
))
6087 // Check the first parameter
6088 FunctionDecl::param_iterator Param
= FnDecl
->param_begin();
6090 QualType T
= (*Param
)->getType();
6092 // unsigned long long int, long double, and any character type are allowed
6093 // as the only parameters.
6094 if (Context
.hasSameType(T
, Context
.UnsignedLongLongTy
) ||
6095 Context
.hasSameType(T
, Context
.LongDoubleTy
) ||
6096 Context
.hasSameType(T
, Context
.CharTy
) ||
6097 Context
.hasSameType(T
, Context
.WCharTy
) ||
6098 Context
.hasSameType(T
, Context
.Char16Ty
) ||
6099 Context
.hasSameType(T
, Context
.Char32Ty
)) {
6100 if (++Param
== FnDecl
->param_end())
6102 goto FinishedParams
;
6105 // Otherwise it must be a pointer to const; let's strip those qualifiers.
6106 const PointerType
*PT
= T
->getAs
<PointerType
>();
6108 goto FinishedParams
;
6109 T
= PT
->getPointeeType();
6110 if (!T
.isConstQualified())
6111 goto FinishedParams
;
6112 T
= T
.getUnqualifiedType();
6114 // Move on to the second parameter;
6117 // If there is no second parameter, the first must be a const char *
6118 if (Param
== FnDecl
->param_end()) {
6119 if (Context
.hasSameType(T
, Context
.CharTy
))
6121 goto FinishedParams
;
6124 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6125 // are allowed as the first parameter to a two-parameter function
6126 if (!(Context
.hasSameType(T
, Context
.CharTy
) ||
6127 Context
.hasSameType(T
, Context
.WCharTy
) ||
6128 Context
.hasSameType(T
, Context
.Char16Ty
) ||
6129 Context
.hasSameType(T
, Context
.Char32Ty
)))
6130 goto FinishedParams
;
6132 // The second and final parameter must be an std::size_t
6133 T
= (*Param
)->getType().getUnqualifiedType();
6134 if (Context
.hasSameType(T
, Context
.getSizeType()) &&
6135 ++Param
== FnDecl
->param_end())
6139 // FIXME: This diagnostic is absolutely terrible.
6142 Diag(FnDecl
->getLocation(), diag::err_literal_operator_params
)
6143 << FnDecl
->getDeclName();
6150 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6151 /// linkage specification, including the language and (if present)
6152 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6153 /// the location of the language string literal, which is provided
6154 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6155 /// the '{' brace. Otherwise, this linkage specification does not
6156 /// have any braces.
6157 Decl
*Sema::ActOnStartLinkageSpecification(Scope
*S
, SourceLocation ExternLoc
,
6158 SourceLocation LangLoc
,
6159 llvm::StringRef Lang
,
6160 SourceLocation LBraceLoc
) {
6161 LinkageSpecDecl::LanguageIDs Language
;
6162 if (Lang
== "\"C\"")
6163 Language
= LinkageSpecDecl::lang_c
;
6164 else if (Lang
== "\"C++\"")
6165 Language
= LinkageSpecDecl::lang_cxx
;
6167 Diag(LangLoc
, diag::err_bad_language
);
6171 // FIXME: Add all the various semantics of linkage specifications
6173 LinkageSpecDecl
*D
= LinkageSpecDecl::Create(Context
, CurContext
,
6175 LBraceLoc
.isValid());
6176 CurContext
->addDecl(D
);
6177 PushDeclContext(S
, D
);
6181 /// ActOnFinishLinkageSpecification - Complete the definition of
6182 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
6183 /// valid, it's the position of the closing '}' brace in a linkage
6184 /// specification that uses braces.
6185 Decl
*Sema::ActOnFinishLinkageSpecification(Scope
*S
,
6187 SourceLocation RBraceLoc
) {
6193 /// \brief Perform semantic analysis for the variable declaration that
6194 /// occurs within a C++ catch clause, returning the newly-created
6196 VarDecl
*Sema::BuildExceptionDeclaration(Scope
*S
,
6197 TypeSourceInfo
*TInfo
,
6198 IdentifierInfo
*Name
,
6199 SourceLocation Loc
) {
6200 bool Invalid
= false;
6201 QualType ExDeclType
= TInfo
->getType();
6203 // Arrays and functions decay.
6204 if (ExDeclType
->isArrayType())
6205 ExDeclType
= Context
.getArrayDecayedType(ExDeclType
);
6206 else if (ExDeclType
->isFunctionType())
6207 ExDeclType
= Context
.getPointerType(ExDeclType
);
6209 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6210 // The exception-declaration shall not denote a pointer or reference to an
6211 // incomplete type, other than [cv] void*.
6212 // N2844 forbids rvalue references.
6213 if (!ExDeclType
->isDependentType() && ExDeclType
->isRValueReferenceType()) {
6214 Diag(Loc
, diag::err_catch_rvalue_ref
);
6218 // GCC allows catching pointers and references to incomplete types
6219 // as an extension; so do we, but we warn by default.
6221 QualType BaseType
= ExDeclType
;
6222 int Mode
= 0; // 0 for direct type, 1 for pointer, 2 for reference
6223 unsigned DK
= diag::err_catch_incomplete
;
6224 bool IncompleteCatchIsInvalid
= true;
6225 if (const PointerType
*Ptr
= BaseType
->getAs
<PointerType
>()) {
6226 BaseType
= Ptr
->getPointeeType();
6228 DK
= diag::ext_catch_incomplete_ptr
;
6229 IncompleteCatchIsInvalid
= false;
6230 } else if (const ReferenceType
*Ref
= BaseType
->getAs
<ReferenceType
>()) {
6231 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
6232 BaseType
= Ref
->getPointeeType();
6234 DK
= diag::ext_catch_incomplete_ref
;
6235 IncompleteCatchIsInvalid
= false;
6237 if (!Invalid
&& (Mode
== 0 || !BaseType
->isVoidType()) &&
6238 !BaseType
->isDependentType() && RequireCompleteType(Loc
, BaseType
, DK
) &&
6239 IncompleteCatchIsInvalid
)
6242 if (!Invalid
&& !ExDeclType
->isDependentType() &&
6243 RequireNonAbstractType(Loc
, ExDeclType
,
6244 diag::err_abstract_type_in_decl
,
6245 AbstractVariableType
))
6248 // Only the non-fragile NeXT runtime currently supports C++ catches
6249 // of ObjC types, and no runtime supports catching ObjC types by value.
6250 if (!Invalid
&& getLangOptions().ObjC1
) {
6251 QualType T
= ExDeclType
;
6252 if (const ReferenceType
*RT
= T
->getAs
<ReferenceType
>())
6253 T
= RT
->getPointeeType();
6255 if (T
->isObjCObjectType()) {
6256 Diag(Loc
, diag::err_objc_object_catch
);
6258 } else if (T
->isObjCObjectPointerType()) {
6259 if (!getLangOptions().NeXTRuntime
) {
6260 Diag(Loc
, diag::err_objc_pointer_cxx_catch_gnu
);
6262 } else if (!getLangOptions().ObjCNonFragileABI
) {
6263 Diag(Loc
, diag::err_objc_pointer_cxx_catch_fragile
);
6269 VarDecl
*ExDecl
= VarDecl::Create(Context
, CurContext
, Loc
,
6270 Name
, ExDeclType
, TInfo
, SC_None
,
6272 ExDecl
->setExceptionVariable(true);
6275 if (const RecordType
*RecordTy
= ExDeclType
->getAs
<RecordType
>()) {
6276 // C++ [except.handle]p16:
6277 // The object declared in an exception-declaration or, if the
6278 // exception-declaration does not specify a name, a temporary (12.2) is
6279 // copy-initialized (8.5) from the exception object. [...]
6280 // The object is destroyed when the handler exits, after the destruction
6281 // of any automatic objects initialized within the handler.
6283 // We just pretend to initialize the object with itself, then make sure
6284 // it can be destroyed later.
6285 InitializedEntity Entity
= InitializedEntity::InitializeVariable(ExDecl
);
6286 Expr
*ExDeclRef
= DeclRefExpr::Create(Context
, 0, SourceRange(), ExDecl
,
6287 Loc
, ExDeclType
, VK_LValue
, 0);
6288 InitializationKind Kind
= InitializationKind::CreateCopy(Loc
,
6290 InitializationSequence
InitSeq(*this, Entity
, Kind
, &ExDeclRef
, 1);
6291 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
,
6292 MultiExprArg(*this, &ExDeclRef
, 1));
6293 if (Result
.isInvalid())
6296 FinalizeVarWithDestructor(ExDecl
, RecordTy
);
6301 ExDecl
->setInvalidDecl();
6306 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6308 Decl
*Sema::ActOnExceptionDeclarator(Scope
*S
, Declarator
&D
) {
6309 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
6310 bool Invalid
= D
.isInvalidType();
6312 // Check for unexpanded parameter packs.
6313 if (TInfo
&& DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
6314 UPPC_ExceptionType
)) {
6315 TInfo
= Context
.getTrivialTypeSourceInfo(Context
.IntTy
,
6316 D
.getIdentifierLoc());
6320 IdentifierInfo
*II
= D
.getIdentifier();
6321 if (NamedDecl
*PrevDecl
= LookupSingleName(S
, II
, D
.getIdentifierLoc(),
6323 ForRedeclaration
)) {
6324 // The scope should be freshly made just for us. There is just no way
6325 // it contains any previous declaration.
6326 assert(!S
->isDeclScope(PrevDecl
));
6327 if (PrevDecl
->isTemplateParameter()) {
6328 // Maybe we will complain about the shadowed template parameter.
6329 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
6333 if (D
.getCXXScopeSpec().isSet() && !Invalid
) {
6334 Diag(D
.getIdentifierLoc(), diag::err_qualified_catch_declarator
)
6335 << D
.getCXXScopeSpec().getRange();
6339 VarDecl
*ExDecl
= BuildExceptionDeclaration(S
, TInfo
,
6341 D
.getIdentifierLoc());
6344 ExDecl
->setInvalidDecl();
6346 // Add the exception declaration into this scope.
6348 PushOnScopeChains(ExDecl
, S
);
6350 CurContext
->addDecl(ExDecl
);
6352 ProcessDeclAttributes(S
, ExDecl
, D
);
6356 Decl
*Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc
,
6358 Expr
*AssertMessageExpr_
) {
6359 StringLiteral
*AssertMessage
= cast
<StringLiteral
>(AssertMessageExpr_
);
6361 if (!AssertExpr
->isTypeDependent() && !AssertExpr
->isValueDependent()) {
6362 llvm::APSInt
Value(32);
6363 if (!AssertExpr
->isIntegerConstantExpr(Value
, Context
)) {
6364 Diag(AssertLoc
, diag::err_static_assert_expression_is_not_constant
) <<
6365 AssertExpr
->getSourceRange();
6370 Diag(AssertLoc
, diag::err_static_assert_failed
)
6371 << AssertMessage
->getString() << AssertExpr
->getSourceRange();
6375 if (DiagnoseUnexpandedParameterPack(AssertExpr
, UPPC_StaticAssertExpression
))
6378 Decl
*Decl
= StaticAssertDecl::Create(Context
, CurContext
, AssertLoc
,
6379 AssertExpr
, AssertMessage
);
6381 CurContext
->addDecl(Decl
);
6385 /// \brief Perform semantic analysis of the given friend type declaration.
6387 /// \returns A friend declaration that.
6388 FriendDecl
*Sema::CheckFriendTypeDecl(SourceLocation FriendLoc
,
6389 TypeSourceInfo
*TSInfo
) {
6390 assert(TSInfo
&& "NULL TypeSourceInfo for friend type declaration");
6392 QualType T
= TSInfo
->getType();
6393 SourceRange TypeRange
= TSInfo
->getTypeLoc().getLocalSourceRange();
6395 if (!getLangOptions().CPlusPlus0x
) {
6396 // C++03 [class.friend]p2:
6397 // An elaborated-type-specifier shall be used in a friend declaration
6400 // * The class-key of the elaborated-type-specifier is required.
6401 if (!ActiveTemplateInstantiations
.empty()) {
6402 // Do not complain about the form of friend template types during
6403 // template instantiation; we will already have complained when the
6404 // template was declared.
6405 } else if (!T
->isElaboratedTypeSpecifier()) {
6406 // If we evaluated the type to a record type, suggest putting
6408 if (const RecordType
*RT
= T
->getAs
<RecordType
>()) {
6409 RecordDecl
*RD
= RT
->getDecl();
6411 std::string InsertionText
= std::string(" ") + RD
->getKindName();
6413 Diag(TypeRange
.getBegin(), diag::ext_unelaborated_friend_type
)
6414 << (unsigned) RD
->getTagKind()
6416 << FixItHint::CreateInsertion(PP
.getLocForEndOfToken(FriendLoc
),
6419 Diag(FriendLoc
, diag::ext_nonclass_type_friend
)
6421 << SourceRange(FriendLoc
, TypeRange
.getEnd());
6423 } else if (T
->getAs
<EnumType
>()) {
6424 Diag(FriendLoc
, diag::ext_enum_friend
)
6426 << SourceRange(FriendLoc
, TypeRange
.getEnd());
6430 // C++0x [class.friend]p3:
6431 // If the type specifier in a friend declaration designates a (possibly
6432 // cv-qualified) class type, that class is declared as a friend; otherwise,
6433 // the friend declaration is ignored.
6435 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6436 // in [class.friend]p3 that we do not implement.
6438 return FriendDecl::Create(Context
, CurContext
, FriendLoc
, TSInfo
, FriendLoc
);
6441 /// Handle a friend tag declaration where the scope specifier was
6443 Decl
*Sema::ActOnTemplatedFriendTag(Scope
*S
, SourceLocation FriendLoc
,
6444 unsigned TagSpec
, SourceLocation TagLoc
,
6446 IdentifierInfo
*Name
, SourceLocation NameLoc
,
6447 AttributeList
*Attr
,
6448 MultiTemplateParamsArg TempParamLists
) {
6449 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
6451 bool isExplicitSpecialization
= false;
6452 unsigned NumMatchedTemplateParamLists
= TempParamLists
.size();
6453 bool Invalid
= false;
6455 if (TemplateParameterList
*TemplateParams
6456 = MatchTemplateParametersToScopeSpecifier(TagLoc
, SS
,
6457 TempParamLists
.get(),
6458 TempParamLists
.size(),
6460 isExplicitSpecialization
,
6462 --NumMatchedTemplateParamLists
;
6464 if (TemplateParams
->size() > 0) {
6465 // This is a declaration of a class template.
6469 return CheckClassTemplate(S
, TagSpec
, TUK_Friend
, TagLoc
,
6470 SS
, Name
, NameLoc
, Attr
,
6471 TemplateParams
, AS_public
).take();
6473 // The "template<>" header is extraneous.
6474 Diag(TemplateParams
->getTemplateLoc(), diag::err_template_tag_noparams
)
6475 << TypeWithKeyword::getTagTypeKindName(Kind
) << Name
;
6476 isExplicitSpecialization
= true;
6480 if (Invalid
) return 0;
6482 assert(SS
.isNotEmpty() && "valid templated tag with no SS and no direct?");
6484 bool isAllExplicitSpecializations
= true;
6485 for (unsigned I
= 0; I
!= NumMatchedTemplateParamLists
; ++I
) {
6486 if (TempParamLists
.get()[I
]->size()) {
6487 isAllExplicitSpecializations
= false;
6492 // FIXME: don't ignore attributes.
6494 // If it's explicit specializations all the way down, just forget
6495 // about the template header and build an appropriate non-templated
6496 // friend. TODO: for source fidelity, remember the headers.
6497 if (isAllExplicitSpecializations
) {
6498 ElaboratedTypeKeyword Keyword
6499 = TypeWithKeyword::getKeywordForTagTypeKind(Kind
);
6500 QualType T
= CheckTypenameType(Keyword
, SS
.getScopeRep(), *Name
,
6501 TagLoc
, SS
.getRange(), NameLoc
);
6505 TypeSourceInfo
*TSI
= Context
.CreateTypeSourceInfo(T
);
6506 if (isa
<DependentNameType
>(T
)) {
6507 DependentNameTypeLoc TL
= cast
<DependentNameTypeLoc
>(TSI
->getTypeLoc());
6508 TL
.setKeywordLoc(TagLoc
);
6509 TL
.setQualifierRange(SS
.getRange());
6510 TL
.setNameLoc(NameLoc
);
6512 ElaboratedTypeLoc TL
= cast
<ElaboratedTypeLoc
>(TSI
->getTypeLoc());
6513 TL
.setKeywordLoc(TagLoc
);
6514 TL
.setQualifierRange(SS
.getRange());
6515 cast
<TypeSpecTypeLoc
>(TL
.getNamedTypeLoc()).setNameLoc(NameLoc
);
6518 FriendDecl
*Friend
= FriendDecl::Create(Context
, CurContext
, NameLoc
,
6520 Friend
->setAccess(AS_public
);
6521 CurContext
->addDecl(Friend
);
6525 // Handle the case of a templated-scope friend class. e.g.
6526 // template <class T> class A<T>::B;
6527 // FIXME: we don't support these right now.
6528 ElaboratedTypeKeyword ETK
= TypeWithKeyword::getKeywordForTagTypeKind(Kind
);
6529 QualType T
= Context
.getDependentNameType(ETK
, SS
.getScopeRep(), Name
);
6530 TypeSourceInfo
*TSI
= Context
.CreateTypeSourceInfo(T
);
6531 DependentNameTypeLoc TL
= cast
<DependentNameTypeLoc
>(TSI
->getTypeLoc());
6532 TL
.setKeywordLoc(TagLoc
);
6533 TL
.setQualifierRange(SS
.getRange());
6534 TL
.setNameLoc(NameLoc
);
6536 FriendDecl
*Friend
= FriendDecl::Create(Context
, CurContext
, NameLoc
,
6538 Friend
->setAccess(AS_public
);
6539 Friend
->setUnsupportedFriend(true);
6540 CurContext
->addDecl(Friend
);
6545 /// Handle a friend type declaration. This works in tandem with
6548 /// Notes on friend class templates:
6550 /// We generally treat friend class declarations as if they were
6551 /// declaring a class. So, for example, the elaborated type specifier
6552 /// in a friend declaration is required to obey the restrictions of a
6553 /// class-head (i.e. no typedefs in the scope chain), template
6554 /// parameters are required to match up with simple template-ids, &c.
6555 /// However, unlike when declaring a template specialization, it's
6556 /// okay to refer to a template specialization without an empty
6557 /// template parameter declaration, e.g.
6558 /// friend class A<T>::B<unsigned>;
6559 /// We permit this as a special case; if there are any template
6560 /// parameters present at all, require proper matching, i.e.
6561 /// template <> template <class T> friend class A<int>::B;
6562 Decl
*Sema::ActOnFriendTypeDecl(Scope
*S
, const DeclSpec
&DS
,
6563 MultiTemplateParamsArg TempParams
) {
6564 SourceLocation Loc
= DS
.getSourceRange().getBegin();
6566 assert(DS
.isFriendSpecified());
6567 assert(DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
);
6569 // Try to convert the decl specifier to a type. This works for
6570 // friend templates because ActOnTag never produces a ClassTemplateDecl
6571 // for a TUK_Friend.
6572 Declarator
TheDeclarator(DS
, Declarator::MemberContext
);
6573 TypeSourceInfo
*TSI
= GetTypeForDeclarator(TheDeclarator
, S
);
6574 QualType T
= TSI
->getType();
6575 if (TheDeclarator
.isInvalidType())
6578 if (DiagnoseUnexpandedParameterPack(Loc
, TSI
, UPPC_FriendDeclaration
))
6581 // This is definitely an error in C++98. It's probably meant to
6582 // be forbidden in C++0x, too, but the specification is just
6585 // The problem is with declarations like the following:
6586 // template <T> friend A<T>::foo;
6587 // where deciding whether a class C is a friend or not now hinges
6588 // on whether there exists an instantiation of A that causes
6589 // 'foo' to equal C. There are restrictions on class-heads
6590 // (which we declare (by fiat) elaborated friend declarations to
6591 // be) that makes this tractable.
6593 // FIXME: handle "template <> friend class A<T>;", which
6594 // is possibly well-formed? Who even knows?
6595 if (TempParams
.size() && !T
->isElaboratedTypeSpecifier()) {
6596 Diag(Loc
, diag::err_tagless_friend_type_template
)
6597 << DS
.getSourceRange();
6601 // C++98 [class.friend]p1: A friend of a class is a function
6602 // or class that is not a member of the class . . .
6603 // This is fixed in DR77, which just barely didn't make the C++03
6604 // deadline. It's also a very silly restriction that seriously
6605 // affects inner classes and which nobody else seems to implement;
6606 // thus we never diagnose it, not even in -pedantic.
6608 // But note that we could warn about it: it's always useless to
6609 // friend one of your own members (it's not, however, worthless to
6610 // friend a member of an arbitrary specialization of your template).
6613 if (unsigned NumTempParamLists
= TempParams
.size())
6614 D
= FriendTemplateDecl::Create(Context
, CurContext
, Loc
,
6616 TempParams
.release(),
6618 DS
.getFriendSpecLoc());
6620 D
= CheckFriendTypeDecl(DS
.getFriendSpecLoc(), TSI
);
6625 D
->setAccess(AS_public
);
6626 CurContext
->addDecl(D
);
6631 Decl
*Sema::ActOnFriendFunctionDecl(Scope
*S
, Declarator
&D
, bool IsDefinition
,
6632 MultiTemplateParamsArg TemplateParams
) {
6633 const DeclSpec
&DS
= D
.getDeclSpec();
6635 assert(DS
.isFriendSpecified());
6636 assert(DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
);
6638 SourceLocation Loc
= D
.getIdentifierLoc();
6639 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
6640 QualType T
= TInfo
->getType();
6642 // C++ [class.friend]p1
6643 // A friend of a class is a function or class....
6644 // Note that this sees through typedefs, which is intended.
6645 // It *doesn't* see through dependent types, which is correct
6646 // according to [temp.arg.type]p3:
6647 // If a declaration acquires a function type through a
6648 // type dependent on a template-parameter and this causes
6649 // a declaration that does not use the syntactic form of a
6650 // function declarator to have a function type, the program
6652 if (!T
->isFunctionType()) {
6653 Diag(Loc
, diag::err_unexpected_friend
);
6655 // It might be worthwhile to try to recover by creating an
6656 // appropriate declaration.
6660 // C++ [namespace.memdef]p3
6661 // - If a friend declaration in a non-local class first declares a
6662 // class or function, the friend class or function is a member
6663 // of the innermost enclosing namespace.
6664 // - The name of the friend is not found by simple name lookup
6665 // until a matching declaration is provided in that namespace
6666 // scope (either before or after the class declaration granting
6668 // - If a friend function is called, its name may be found by the
6669 // name lookup that considers functions from namespaces and
6670 // classes associated with the types of the function arguments.
6671 // - When looking for a prior declaration of a class or a function
6672 // declared as a friend, scopes outside the innermost enclosing
6673 // namespace scope are not considered.
6675 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
6676 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
6677 DeclarationName Name
= NameInfo
.getName();
6680 // Check for unexpanded parameter packs.
6681 if (DiagnoseUnexpandedParameterPack(Loc
, TInfo
, UPPC_FriendDeclaration
) ||
6682 DiagnoseUnexpandedParameterPack(NameInfo
, UPPC_FriendDeclaration
) ||
6683 DiagnoseUnexpandedParameterPack(SS
, UPPC_FriendDeclaration
))
6686 // The context we found the declaration in, or in which we should
6687 // create the declaration.
6690 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
6693 // FIXME: there are different rules in local classes
6695 // There are four cases here.
6696 // - There's no scope specifier, in which case we just go to the
6697 // appropriate scope and look for a function or function template
6698 // there as appropriate.
6699 // Recover from invalid scope qualifiers as if they just weren't there.
6700 if (SS
.isInvalid() || !SS
.isSet()) {
6701 // C++0x [namespace.memdef]p3:
6702 // If the name in a friend declaration is neither qualified nor
6703 // a template-id and the declaration is a function or an
6704 // elaborated-type-specifier, the lookup to determine whether
6705 // the entity has been previously declared shall not consider
6706 // any scopes outside the innermost enclosing namespace.
6707 // C++0x [class.friend]p11:
6708 // If a friend declaration appears in a local class and the name
6709 // specified is an unqualified name, a prior declaration is
6710 // looked up without considering scopes that are outside the
6711 // innermost enclosing non-class scope. For a friend function
6712 // declaration, if there is no prior declaration, the program is
6714 bool isLocal
= cast
<CXXRecordDecl
>(CurContext
)->isLocalClass();
6715 bool isTemplateId
= D
.getName().getKind() == UnqualifiedId::IK_TemplateId
;
6717 // Find the appropriate context according to the above.
6720 // Skip class contexts. If someone can cite chapter and verse
6721 // for this behavior, that would be nice --- it's what GCC and
6722 // EDG do, and it seems like a reasonable intent, but the spec
6723 // really only says that checks for unqualified existing
6724 // declarations should stop at the nearest enclosing namespace,
6725 // not that they should only consider the nearest enclosing
6727 while (DC
->isRecord())
6728 DC
= DC
->getParent();
6730 LookupQualifiedName(Previous
, DC
);
6732 // TODO: decide what we think about using declarations.
6733 if (isLocal
|| !Previous
.empty())
6737 if (isa
<TranslationUnitDecl
>(DC
)) break;
6739 if (DC
->isFileContext()) break;
6741 DC
= DC
->getParent();
6744 // C++ [class.friend]p1: A friend of a class is a function or
6745 // class that is not a member of the class . . .
6746 // C++0x changes this for both friend types and functions.
6747 // Most C++ 98 compilers do seem to give an error here, so
6749 if (!Previous
.empty() && DC
->Equals(CurContext
)
6750 && !getLangOptions().CPlusPlus0x
)
6751 Diag(DS
.getFriendSpecLoc(), diag::err_friend_is_member
);
6753 DCScope
= getScopeForDeclContext(S
, DC
);
6755 // - There's a non-dependent scope specifier, in which case we
6756 // compute it and do a previous lookup there for a function
6757 // or function template.
6758 } else if (!SS
.getScopeRep()->isDependent()) {
6759 DC
= computeDeclContext(SS
);
6762 if (RequireCompleteDeclContext(SS
, DC
)) return 0;
6764 LookupQualifiedName(Previous
, DC
);
6766 // Ignore things found implicitly in the wrong scope.
6767 // TODO: better diagnostics for this case. Suggesting the right
6768 // qualified scope would be nice...
6769 LookupResult::Filter F
= Previous
.makeFilter();
6770 while (F
.hasNext()) {
6771 NamedDecl
*D
= F
.next();
6772 if (!DC
->InEnclosingNamespaceSetOf(
6773 D
->getDeclContext()->getRedeclContext()))
6778 if (Previous
.empty()) {
6780 Diag(Loc
, diag::err_qualified_friend_not_found
) << Name
<< T
;
6784 // C++ [class.friend]p1: A friend of a class is a function or
6785 // class that is not a member of the class . . .
6786 if (DC
->Equals(CurContext
))
6787 Diag(DS
.getFriendSpecLoc(), diag::err_friend_is_member
);
6789 // - There's a scope specifier that does not match any template
6790 // parameter lists, in which case we use some arbitrary context,
6791 // create a method or method template, and wait for instantiation.
6792 // - There's a scope specifier that does match some template
6793 // parameter lists, which we don't handle right now.
6796 assert(isa
<CXXRecordDecl
>(DC
) && "friend declaration not in class?");
6799 if (!DC
->isRecord()) {
6800 // This implies that it has to be an operator or function.
6801 if (D
.getName().getKind() == UnqualifiedId::IK_ConstructorName
||
6802 D
.getName().getKind() == UnqualifiedId::IK_DestructorName
||
6803 D
.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId
) {
6804 Diag(Loc
, diag::err_introducing_special_friend
) <<
6805 (D
.getName().getKind() == UnqualifiedId::IK_ConstructorName
? 0 :
6806 D
.getName().getKind() == UnqualifiedId::IK_DestructorName
? 1 : 2);
6811 bool Redeclaration
= false;
6812 NamedDecl
*ND
= ActOnFunctionDeclarator(DCScope
, D
, DC
, T
, TInfo
, Previous
,
6813 move(TemplateParams
),
6818 assert(ND
->getDeclContext() == DC
);
6819 assert(ND
->getLexicalDeclContext() == CurContext
);
6821 // Add the function declaration to the appropriate lookup tables,
6822 // adjusting the redeclarations list as necessary. We don't
6823 // want to do this yet if the friending class is dependent.
6825 // Also update the scope-based lookup if the target context's
6826 // lookup context is in lexical scope.
6827 if (!CurContext
->isDependentContext()) {
6828 DC
= DC
->getRedeclContext();
6829 DC
->makeDeclVisibleInContext(ND
, /* Recoverable=*/ false);
6830 if (Scope
*EnclosingScope
= getScopeForDeclContext(S
, DC
))
6831 PushOnScopeChains(ND
, EnclosingScope
, /*AddToContext=*/ false);
6834 FriendDecl
*FrD
= FriendDecl::Create(Context
, CurContext
,
6835 D
.getIdentifierLoc(), ND
,
6836 DS
.getFriendSpecLoc());
6837 FrD
->setAccess(AS_public
);
6838 CurContext
->addDecl(FrD
);
6840 if (ND
->isInvalidDecl())
6841 FrD
->setInvalidDecl();
6844 if (FunctionTemplateDecl
*FTD
= dyn_cast
<FunctionTemplateDecl
>(ND
))
6845 FD
= FTD
->getTemplatedDecl();
6847 FD
= cast
<FunctionDecl
>(ND
);
6849 // Mark templated-scope function declarations as unsupported.
6850 if (FD
->getNumTemplateParameterLists())
6851 FrD
->setUnsupportedFriend(true);
6857 void Sema::SetDeclDeleted(Decl
*Dcl
, SourceLocation DelLoc
) {
6858 AdjustDeclIfTemplate(Dcl
);
6860 FunctionDecl
*Fn
= dyn_cast
<FunctionDecl
>(Dcl
);
6862 Diag(DelLoc
, diag::err_deleted_non_function
);
6865 if (const FunctionDecl
*Prev
= Fn
->getPreviousDeclaration()) {
6866 Diag(DelLoc
, diag::err_deleted_decl_not_first
);
6867 Diag(Prev
->getLocation(), diag::note_previous_declaration
);
6868 // If the declaration wasn't the first, we delete the function anyway for
6874 static void SearchForReturnInStmt(Sema
&Self
, Stmt
*S
) {
6875 for (Stmt::child_iterator CI
= S
->child_begin(), E
= S
->child_end(); CI
!= E
;
6877 Stmt
*SubStmt
= *CI
;
6880 if (isa
<ReturnStmt
>(SubStmt
))
6881 Self
.Diag(SubStmt
->getSourceRange().getBegin(),
6882 diag::err_return_in_constructor_handler
);
6883 if (!isa
<Expr
>(SubStmt
))
6884 SearchForReturnInStmt(Self
, SubStmt
);
6888 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt
*TryBlock
) {
6889 for (unsigned I
= 0, E
= TryBlock
->getNumHandlers(); I
!= E
; ++I
) {
6890 CXXCatchStmt
*Handler
= TryBlock
->getHandler(I
);
6891 SearchForReturnInStmt(*this, Handler
);
6895 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl
*New
,
6896 const CXXMethodDecl
*Old
) {
6897 QualType NewTy
= New
->getType()->getAs
<FunctionType
>()->getResultType();
6898 QualType OldTy
= Old
->getType()->getAs
<FunctionType
>()->getResultType();
6900 if (Context
.hasSameType(NewTy
, OldTy
) ||
6901 NewTy
->isDependentType() || OldTy
->isDependentType())
6904 // Check if the return types are covariant
6905 QualType NewClassTy
, OldClassTy
;
6907 /// Both types must be pointers or references to classes.
6908 if (const PointerType
*NewPT
= NewTy
->getAs
<PointerType
>()) {
6909 if (const PointerType
*OldPT
= OldTy
->getAs
<PointerType
>()) {
6910 NewClassTy
= NewPT
->getPointeeType();
6911 OldClassTy
= OldPT
->getPointeeType();
6913 } else if (const ReferenceType
*NewRT
= NewTy
->getAs
<ReferenceType
>()) {
6914 if (const ReferenceType
*OldRT
= OldTy
->getAs
<ReferenceType
>()) {
6915 if (NewRT
->getTypeClass() == OldRT
->getTypeClass()) {
6916 NewClassTy
= NewRT
->getPointeeType();
6917 OldClassTy
= OldRT
->getPointeeType();
6922 // The return types aren't either both pointers or references to a class type.
6923 if (NewClassTy
.isNull()) {
6924 Diag(New
->getLocation(),
6925 diag::err_different_return_type_for_overriding_virtual_function
)
6926 << New
->getDeclName() << NewTy
<< OldTy
;
6927 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
6932 // C++ [class.virtual]p6:
6933 // If the return type of D::f differs from the return type of B::f, the
6934 // class type in the return type of D::f shall be complete at the point of
6935 // declaration of D::f or shall be the class type D.
6936 if (const RecordType
*RT
= NewClassTy
->getAs
<RecordType
>()) {
6937 if (!RT
->isBeingDefined() &&
6938 RequireCompleteType(New
->getLocation(), NewClassTy
,
6939 PDiag(diag::err_covariant_return_incomplete
)
6940 << New
->getDeclName()))
6944 if (!Context
.hasSameUnqualifiedType(NewClassTy
, OldClassTy
)) {
6945 // Check if the new class derives from the old class.
6946 if (!IsDerivedFrom(NewClassTy
, OldClassTy
)) {
6947 Diag(New
->getLocation(),
6948 diag::err_covariant_return_not_derived
)
6949 << New
->getDeclName() << NewTy
<< OldTy
;
6950 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
6954 // Check if we the conversion from derived to base is valid.
6955 if (CheckDerivedToBaseConversion(NewClassTy
, OldClassTy
,
6956 diag::err_covariant_return_inaccessible_base
,
6957 diag::err_covariant_return_ambiguous_derived_to_base_conv
,
6958 // FIXME: Should this point to the return type?
6959 New
->getLocation(), SourceRange(), New
->getDeclName(), 0)) {
6960 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
6965 // The qualifiers of the return types must be the same.
6966 if (NewTy
.getLocalCVRQualifiers() != OldTy
.getLocalCVRQualifiers()) {
6967 Diag(New
->getLocation(),
6968 diag::err_covariant_return_type_different_qualifications
)
6969 << New
->getDeclName() << NewTy
<< OldTy
;
6970 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
6975 // The new class type must have the same or less qualifiers as the old type.
6976 if (NewClassTy
.isMoreQualifiedThan(OldClassTy
)) {
6977 Diag(New
->getLocation(),
6978 diag::err_covariant_return_type_class_type_more_qualified
)
6979 << New
->getDeclName() << NewTy
<< OldTy
;
6980 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
6987 /// \brief Mark the given method pure.
6989 /// \param Method the method to be marked pure.
6991 /// \param InitRange the source range that covers the "0" initializer.
6992 bool Sema::CheckPureMethod(CXXMethodDecl
*Method
, SourceRange InitRange
) {
6993 if (Method
->isVirtual() || Method
->getParent()->isDependentContext()) {
6998 if (!Method
->isInvalidDecl())
6999 Diag(Method
->getLocation(), diag::err_non_virtual_pure
)
7000 << Method
->getDeclName() << InitRange
;
7004 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7005 /// an initializer for the out-of-line declaration 'Dcl'. The scope
7006 /// is a fresh scope pushed for just this purpose.
7008 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7009 /// static data member of class X, names should be looked up in the scope of
7011 void Sema::ActOnCXXEnterDeclInitializer(Scope
*S
, Decl
*D
) {
7012 // If there is no declaration, there was an error parsing it.
7015 // We should only get called for declarations with scope specifiers, like:
7017 assert(D
->isOutOfLine());
7018 EnterDeclaratorContext(S
, D
->getDeclContext());
7021 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
7022 /// initializer for the out-of-line declaration 'D'.
7023 void Sema::ActOnCXXExitDeclInitializer(Scope
*S
, Decl
*D
) {
7024 // If there is no declaration, there was an error parsing it.
7027 assert(D
->isOutOfLine());
7028 ExitDeclaratorContext(S
);
7031 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7032 /// C++ if/switch/while/for statement.
7033 /// e.g: "if (int x = f()) {...}"
7034 DeclResult
Sema::ActOnCXXConditionDeclaration(Scope
*S
, Declarator
&D
) {
7036 // The declarator shall not specify a function or an array.
7037 // The type-specifier-seq shall not contain typedef and shall not declare a
7038 // new class or enumeration.
7039 assert(D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&&
7040 "Parser allowed 'typedef' as storage class of condition decl.");
7042 TagDecl
*OwnedTag
= 0;
7043 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
, &OwnedTag
);
7044 QualType Ty
= TInfo
->getType();
7046 if (Ty
->isFunctionType()) { // The declarator shall not specify a function...
7047 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7048 // would be created and CXXConditionDeclExpr wants a VarDecl.
7049 Diag(D
.getIdentifierLoc(), diag::err_invalid_use_of_function_type
)
7050 << D
.getSourceRange();
7051 return DeclResult();
7052 } else if (OwnedTag
&& OwnedTag
->isDefinition()) {
7053 // The type-specifier-seq shall not declare a new class or enumeration.
7054 Diag(OwnedTag
->getLocation(), diag::err_type_defined_in_condition
);
7057 Decl
*Dcl
= ActOnDeclarator(S
, D
);
7059 return DeclResult();
7064 void Sema::MarkVTableUsed(SourceLocation Loc
, CXXRecordDecl
*Class
,
7065 bool DefinitionRequired
) {
7066 // Ignore any vtable uses in unevaluated operands or for classes that do
7067 // not have a vtable.
7068 if (!Class
->isDynamicClass() || Class
->isDependentContext() ||
7069 CurContext
->isDependentContext() ||
7070 ExprEvalContexts
.back().Context
== Unevaluated
)
7073 // Try to insert this class into the map.
7074 Class
= cast
<CXXRecordDecl
>(Class
->getCanonicalDecl());
7075 std::pair
<llvm::DenseMap
<CXXRecordDecl
*, bool>::iterator
, bool>
7076 Pos
= VTablesUsed
.insert(std::make_pair(Class
, DefinitionRequired
));
7078 // If we already had an entry, check to see if we are promoting this vtable
7079 // to required a definition. If so, we need to reappend to the VTableUses
7080 // list, since we may have already processed the first entry.
7081 if (DefinitionRequired
&& !Pos
.first
->second
) {
7082 Pos
.first
->second
= true;
7084 // Otherwise, we can early exit.
7089 // Local classes need to have their virtual members marked
7090 // immediately. For all other classes, we mark their virtual members
7091 // at the end of the translation unit.
7092 if (Class
->isLocalClass())
7093 MarkVirtualMembersReferenced(Loc
, Class
);
7095 VTableUses
.push_back(std::make_pair(Class
, Loc
));
7098 bool Sema::DefineUsedVTables() {
7099 if (VTableUses
.empty())
7102 // Note: The VTableUses vector could grow as a result of marking
7103 // the members of a class as "used", so we check the size each
7104 // time through the loop and prefer indices (with are stable) to
7105 // iterators (which are not).
7106 for (unsigned I
= 0; I
!= VTableUses
.size(); ++I
) {
7107 CXXRecordDecl
*Class
= VTableUses
[I
].first
->getDefinition();
7111 SourceLocation Loc
= VTableUses
[I
].second
;
7113 // If this class has a key function, but that key function is
7114 // defined in another translation unit, we don't need to emit the
7115 // vtable even though we're using it.
7116 const CXXMethodDecl
*KeyFunction
= Context
.getKeyFunction(Class
);
7117 if (KeyFunction
&& !KeyFunction
->hasBody()) {
7118 switch (KeyFunction
->getTemplateSpecializationKind()) {
7119 case TSK_Undeclared
:
7120 case TSK_ExplicitSpecialization
:
7121 // The key function is in another translation unit. Mark all of the
7122 // virtual members of this class as referenced so that we can build a
7123 // vtable anyway (in order to do devirtualization when optimizations
7124 // are turned on for example.
7125 MarkVirtualMembersReferenced(Loc
, Class
);
7128 case TSK_ExplicitInstantiationDeclaration
:
7129 // The key function is in another translation unit.
7132 case TSK_ExplicitInstantiationDefinition
:
7133 case TSK_ImplicitInstantiation
:
7134 // We will be instantiating the key function.
7137 } else if (!KeyFunction
) {
7138 // If we have a class with no key function that is the subject
7139 // of an explicit instantiation declaration, suppress the
7140 // vtable; it will live with the explicit instantiation
7142 bool IsExplicitInstantiationDeclaration
7143 = Class
->getTemplateSpecializationKind()
7144 == TSK_ExplicitInstantiationDeclaration
;
7145 for (TagDecl::redecl_iterator R
= Class
->redecls_begin(),
7146 REnd
= Class
->redecls_end();
7148 TemplateSpecializationKind TSK
7149 = cast
<CXXRecordDecl
>(*R
)->getTemplateSpecializationKind();
7150 if (TSK
== TSK_ExplicitInstantiationDeclaration
)
7151 IsExplicitInstantiationDeclaration
= true;
7152 else if (TSK
== TSK_ExplicitInstantiationDefinition
) {
7153 IsExplicitInstantiationDeclaration
= false;
7158 if (IsExplicitInstantiationDeclaration
)
7162 // Mark all of the virtual members of this class as referenced, so
7163 // that we can build a vtable. Then, tell the AST consumer that a
7164 // vtable for this class is required.
7165 MarkVirtualMembersReferenced(Loc
, Class
);
7166 CXXRecordDecl
*Canonical
= cast
<CXXRecordDecl
>(Class
->getCanonicalDecl());
7167 Consumer
.HandleVTable(Class
, VTablesUsed
[Canonical
]);
7169 // Optionally warn if we're emitting a weak vtable.
7170 if (Class
->getLinkage() == ExternalLinkage
&&
7171 Class
->getTemplateSpecializationKind() != TSK_ImplicitInstantiation
) {
7172 if (!KeyFunction
|| (KeyFunction
->hasBody() && KeyFunction
->isInlined()))
7173 Diag(Class
->getLocation(), diag::warn_weak_vtable
) << Class
;
7181 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc
,
7182 const CXXRecordDecl
*RD
) {
7183 for (CXXRecordDecl::method_iterator i
= RD
->method_begin(),
7184 e
= RD
->method_end(); i
!= e
; ++i
) {
7185 CXXMethodDecl
*MD
= *i
;
7187 // C++ [basic.def.odr]p2:
7188 // [...] A virtual member function is used if it is not pure. [...]
7189 if (MD
->isVirtual() && !MD
->isPure())
7190 MarkDeclarationReferenced(Loc
, MD
);
7193 // Only classes that have virtual bases need a VTT.
7194 if (RD
->getNumVBases() == 0)
7197 for (CXXRecordDecl::base_class_const_iterator i
= RD
->bases_begin(),
7198 e
= RD
->bases_end(); i
!= e
; ++i
) {
7199 const CXXRecordDecl
*Base
=
7200 cast
<CXXRecordDecl
>(i
->getType()->getAs
<RecordType
>()->getDecl());
7201 if (Base
->getNumVBases() == 0)
7203 MarkVirtualMembersReferenced(Loc
, Base
);
7207 /// SetIvarInitializers - This routine builds initialization ASTs for the
7208 /// Objective-C implementation whose ivars need be initialized.
7209 void Sema::SetIvarInitializers(ObjCImplementationDecl
*ObjCImplementation
) {
7210 if (!getLangOptions().CPlusPlus
)
7212 if (ObjCInterfaceDecl
*OID
= ObjCImplementation
->getClassInterface()) {
7213 llvm::SmallVector
<ObjCIvarDecl
*, 8> ivars
;
7214 CollectIvarsToConstructOrDestruct(OID
, ivars
);
7217 llvm::SmallVector
<CXXCtorInitializer
*, 32> AllToInit
;
7218 for (unsigned i
= 0; i
< ivars
.size(); i
++) {
7219 FieldDecl
*Field
= ivars
[i
];
7220 if (Field
->isInvalidDecl())
7223 CXXCtorInitializer
*Member
;
7224 InitializedEntity InitEntity
= InitializedEntity::InitializeMember(Field
);
7225 InitializationKind InitKind
=
7226 InitializationKind::CreateDefault(ObjCImplementation
->getLocation());
7228 InitializationSequence
InitSeq(*this, InitEntity
, InitKind
, 0, 0);
7229 ExprResult MemberInit
=
7230 InitSeq
.Perform(*this, InitEntity
, InitKind
, MultiExprArg());
7231 MemberInit
= MaybeCreateExprWithCleanups(MemberInit
);
7232 // Note, MemberInit could actually come back empty if no initialization
7233 // is required (e.g., because it would call a trivial default constructor)
7234 if (!MemberInit
.get() || MemberInit
.isInvalid())
7238 new (Context
) CXXCtorInitializer(Context
, Field
, SourceLocation(),
7240 MemberInit
.takeAs
<Expr
>(),
7242 AllToInit
.push_back(Member
);
7244 // Be sure that the destructor is accessible and is marked as referenced.
7245 if (const RecordType
*RecordTy
7246 = Context
.getBaseElementType(Field
->getType())
7247 ->getAs
<RecordType
>()) {
7248 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
7249 if (CXXDestructorDecl
*Destructor
= LookupDestructor(RD
)) {
7250 MarkDeclarationReferenced(Field
->getLocation(), Destructor
);
7251 CheckDestructorAccess(Field
->getLocation(), Destructor
,
7252 PDiag(diag::err_access_dtor_ivar
)
7253 << Context
.getBaseElementType(Field
->getType()));
7257 ObjCImplementation
->setIvarInitializers(Context
,
7258 AllToInit
.data(), AllToInit
.size());