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_range I
= Node
->children(); I
; ++I
)
67 IsInvalid
|= Visit(*I
);
71 /// VisitDeclRefExpr - Visit a reference to a declaration, to
72 /// determine whether this declaration can be used in the default
73 /// argument expression.
74 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr
*DRE
) {
75 NamedDecl
*Decl
= DRE
->getDecl();
76 if (ParmVarDecl
*Param
= dyn_cast
<ParmVarDecl
>(Decl
)) {
77 // C++ [dcl.fct.default]p9
78 // Default arguments are evaluated each time the function is
79 // called. The order of evaluation of function arguments is
80 // unspecified. Consequently, parameters of a function shall not
81 // be used in default argument expressions, even if they are not
82 // evaluated. Parameters of a function declared before a default
83 // argument expression are in scope and can hide namespace and
84 // class member names.
85 return S
->Diag(DRE
->getSourceRange().getBegin(),
86 diag::err_param_default_argument_references_param
)
87 << Param
->getDeclName() << DefaultArg
->getSourceRange();
88 } else if (VarDecl
*VDecl
= dyn_cast
<VarDecl
>(Decl
)) {
89 // C++ [dcl.fct.default]p7
90 // Local variables shall not be used in default argument
92 if (VDecl
->isLocalVarDecl())
93 return S
->Diag(DRE
->getSourceRange().getBegin(),
94 diag::err_param_default_argument_references_local
)
95 << VDecl
->getDeclName() << DefaultArg
->getSourceRange();
101 /// VisitCXXThisExpr - Visit a C++ "this" expression.
102 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr
*ThisE
) {
103 // C++ [dcl.fct.default]p8:
104 // The keyword this shall not be used in a default argument of a
106 return S
->Diag(ThisE
->getSourceRange().getBegin(),
107 diag::err_param_default_argument_references_this
)
108 << ThisE
->getSourceRange();
113 Sema::SetParamDefaultArgument(ParmVarDecl
*Param
, Expr
*Arg
,
114 SourceLocation EqualLoc
) {
115 if (RequireCompleteType(Param
->getLocation(), Param
->getType(),
116 diag::err_typecheck_decl_incomplete_type
)) {
117 Param
->setInvalidDecl();
121 // C++ [dcl.fct.default]p5
122 // A default argument expression is implicitly converted (clause
123 // 4) to the parameter type. The default argument expression has
124 // the same semantic constraints as the initializer expression in
125 // a declaration of a variable of the parameter type, using the
126 // copy-initialization semantics (8.5).
127 InitializedEntity Entity
= InitializedEntity::InitializeParameter(Context
,
129 InitializationKind Kind
= InitializationKind::CreateCopy(Param
->getLocation(),
131 InitializationSequence
InitSeq(*this, Entity
, Kind
, &Arg
, 1);
132 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
,
133 MultiExprArg(*this, &Arg
, 1));
134 if (Result
.isInvalid())
136 Arg
= Result
.takeAs
<Expr
>();
138 CheckImplicitConversions(Arg
, EqualLoc
);
139 Arg
= MaybeCreateExprWithCleanups(Arg
);
141 // Okay: add the default argument to the parameter
142 Param
->setDefaultArg(Arg
);
144 // We have already instantiated this parameter; provide each of the
145 // instantiations with the uninstantiated default argument.
146 UnparsedDefaultArgInstantiationsMap::iterator InstPos
147 = UnparsedDefaultArgInstantiations
.find(Param
);
148 if (InstPos
!= UnparsedDefaultArgInstantiations
.end()) {
149 for (unsigned I
= 0, N
= InstPos
->second
.size(); I
!= N
; ++I
)
150 InstPos
->second
[I
]->setUninstantiatedDefaultArg(Arg
);
152 // We're done tracking this parameter's instantiations.
153 UnparsedDefaultArgInstantiations
.erase(InstPos
);
159 /// ActOnParamDefaultArgument - Check whether the default argument
160 /// provided for a function parameter is well-formed. If so, attach it
161 /// to the parameter declaration.
163 Sema::ActOnParamDefaultArgument(Decl
*param
, SourceLocation EqualLoc
,
165 if (!param
|| !DefaultArg
)
168 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(param
);
169 UnparsedDefaultArgLocs
.erase(Param
);
171 // Default arguments are only permitted in C++
172 if (!getLangOptions().CPlusPlus
) {
173 Diag(EqualLoc
, diag::err_param_default_argument
)
174 << DefaultArg
->getSourceRange();
175 Param
->setInvalidDecl();
179 // Check for unexpanded parameter packs.
180 if (DiagnoseUnexpandedParameterPack(DefaultArg
, UPPC_DefaultArgument
)) {
181 Param
->setInvalidDecl();
185 // Check that the default argument is well-formed
186 CheckDefaultArgumentVisitor
DefaultArgChecker(DefaultArg
, this);
187 if (DefaultArgChecker
.Visit(DefaultArg
)) {
188 Param
->setInvalidDecl();
192 SetParamDefaultArgument(Param
, DefaultArg
, EqualLoc
);
195 /// ActOnParamUnparsedDefaultArgument - We've seen a default
196 /// argument for a function parameter, but we can't parse it yet
197 /// because we're inside a class definition. Note that this default
198 /// argument will be parsed later.
199 void Sema::ActOnParamUnparsedDefaultArgument(Decl
*param
,
200 SourceLocation EqualLoc
,
201 SourceLocation ArgLoc
) {
205 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(param
);
207 Param
->setUnparsedDefaultArg();
209 UnparsedDefaultArgLocs
[Param
] = ArgLoc
;
212 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
213 /// the default argument for the parameter param failed.
214 void Sema::ActOnParamDefaultArgumentError(Decl
*param
) {
218 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(param
);
220 Param
->setInvalidDecl();
222 UnparsedDefaultArgLocs
.erase(Param
);
225 /// CheckExtraCXXDefaultArguments - Check for any extra default
226 /// arguments in the declarator, which is not a function declaration
227 /// or definition and therefore is not permitted to have default
228 /// arguments. This routine should be invoked for every declarator
229 /// that is not a function declaration or definition.
230 void Sema::CheckExtraCXXDefaultArguments(Declarator
&D
) {
231 // C++ [dcl.fct.default]p3
232 // A default argument expression shall be specified only in the
233 // parameter-declaration-clause of a function declaration or in a
234 // template-parameter (14.1). It shall not be specified for a
235 // parameter pack. If it is specified in a
236 // parameter-declaration-clause, it shall not occur within a
237 // declarator or abstract-declarator of a parameter-declaration.
238 for (unsigned i
= 0, e
= D
.getNumTypeObjects(); i
!= e
; ++i
) {
239 DeclaratorChunk
&chunk
= D
.getTypeObject(i
);
240 if (chunk
.Kind
== DeclaratorChunk::Function
) {
241 for (unsigned argIdx
= 0, e
= chunk
.Fun
.NumArgs
; argIdx
!= e
; ++argIdx
) {
243 cast
<ParmVarDecl
>(chunk
.Fun
.ArgInfo
[argIdx
].Param
);
244 if (Param
->hasUnparsedDefaultArg()) {
245 CachedTokens
*Toks
= chunk
.Fun
.ArgInfo
[argIdx
].DefaultArgTokens
;
246 Diag(Param
->getLocation(), diag::err_param_default_argument_nonfunc
)
247 << SourceRange((*Toks
)[1].getLocation(), Toks
->back().getLocation());
249 chunk
.Fun
.ArgInfo
[argIdx
].DefaultArgTokens
= 0;
250 } else if (Param
->getDefaultArg()) {
251 Diag(Param
->getLocation(), diag::err_param_default_argument_nonfunc
)
252 << Param
->getDefaultArg()->getSourceRange();
253 Param
->setDefaultArg(0);
260 // MergeCXXFunctionDecl - Merge two declarations of the same C++
261 // function, once we already know that they have the same
262 // type. Subroutine of MergeFunctionDecl. Returns true if there was an
263 // error, false otherwise.
264 bool Sema::MergeCXXFunctionDecl(FunctionDecl
*New
, FunctionDecl
*Old
) {
265 bool Invalid
= false;
267 // C++ [dcl.fct.default]p4:
268 // For non-template functions, default arguments can be added in
269 // later declarations of a function in the same
270 // scope. Declarations in different scopes have completely
271 // distinct sets of default arguments. That is, declarations in
272 // inner scopes do not acquire default arguments from
273 // declarations in outer scopes, and vice versa. In a given
274 // function declaration, all parameters subsequent to a
275 // parameter with a default argument shall have default
276 // arguments supplied in this or previous declarations. A
277 // default argument shall not be redefined by a later
278 // declaration (not even to the same value).
280 // C++ [dcl.fct.default]p6:
281 // Except for member functions of class templates, the default arguments
282 // in a member function definition that appears outside of the class
283 // definition are added to the set of default arguments provided by the
284 // member function declaration in the class definition.
285 for (unsigned p
= 0, NumParams
= Old
->getNumParams(); p
< NumParams
; ++p
) {
286 ParmVarDecl
*OldParam
= Old
->getParamDecl(p
);
287 ParmVarDecl
*NewParam
= New
->getParamDecl(p
);
289 if (OldParam
->hasDefaultArg() && NewParam
->hasDefaultArg()) {
290 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
291 // hint here. Alternatively, we could walk the type-source information
292 // for NewParam to find the last source location in the type... but it
293 // isn't worth the effort right now. This is the kind of test case that
294 // is hard to get right:
297 // void g(int (*fp)(int) = f);
298 // void g(int (*fp)(int) = &f);
299 Diag(NewParam
->getLocation(),
300 diag::err_param_default_argument_redefinition
)
301 << NewParam
->getDefaultArgRange();
303 // Look for the function declaration where the default argument was
304 // actually written, which may be a declaration prior to Old.
305 for (FunctionDecl
*Older
= Old
->getPreviousDeclaration();
306 Older
; Older
= Older
->getPreviousDeclaration()) {
307 if (!Older
->getParamDecl(p
)->hasDefaultArg())
310 OldParam
= Older
->getParamDecl(p
);
313 Diag(OldParam
->getLocation(), diag::note_previous_definition
)
314 << OldParam
->getDefaultArgRange();
316 } else if (OldParam
->hasDefaultArg()) {
317 // Merge the old default argument into the new parameter.
318 // It's important to use getInit() here; getDefaultArg()
319 // strips off any top-level ExprWithCleanups.
320 NewParam
->setHasInheritedDefaultArg();
321 if (OldParam
->hasUninstantiatedDefaultArg())
322 NewParam
->setUninstantiatedDefaultArg(
323 OldParam
->getUninstantiatedDefaultArg());
325 NewParam
->setDefaultArg(OldParam
->getInit());
326 } else if (NewParam
->hasDefaultArg()) {
327 if (New
->getDescribedFunctionTemplate()) {
328 // Paragraph 4, quoted above, only applies to non-template functions.
329 Diag(NewParam
->getLocation(),
330 diag::err_param_default_argument_template_redecl
)
331 << NewParam
->getDefaultArgRange();
332 Diag(Old
->getLocation(), diag::note_template_prev_declaration
)
334 } else if (New
->getTemplateSpecializationKind()
335 != TSK_ImplicitInstantiation
&&
336 New
->getTemplateSpecializationKind() != TSK_Undeclared
) {
337 // C++ [temp.expr.spec]p21:
338 // Default function arguments shall not be specified in a declaration
339 // or a definition for one of the following explicit specializations:
340 // - the explicit specialization of a function template;
341 // - the explicit specialization of a member function template;
342 // - the explicit specialization of a member function of a class
343 // template where the class template specialization to which the
344 // member function specialization belongs is implicitly
346 Diag(NewParam
->getLocation(), diag::err_template_spec_default_arg
)
347 << (New
->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization
)
348 << New
->getDeclName()
349 << NewParam
->getDefaultArgRange();
350 } else if (New
->getDeclContext()->isDependentContext()) {
351 // C++ [dcl.fct.default]p6 (DR217):
352 // Default arguments for a member function of a class template shall
353 // be specified on the initial declaration of the member function
354 // within the class template.
356 // Reading the tea leaves a bit in DR217 and its reference to DR205
357 // leads me to the conclusion that one cannot add default function
358 // arguments for an out-of-line definition of a member function of a
361 if (CXXRecordDecl
*Record
362 = dyn_cast
<CXXRecordDecl
>(New
->getDeclContext())) {
363 if (Record
->getDescribedClassTemplate())
365 else if (isa
<ClassTemplatePartialSpecializationDecl
>(Record
))
371 Diag(NewParam
->getLocation(),
372 diag::err_param_default_argument_member_template_redecl
)
374 << NewParam
->getDefaultArgRange();
379 if (CheckEquivalentExceptionSpec(Old
, New
))
385 /// CheckCXXDefaultArguments - Verify that the default arguments for a
386 /// function declaration are well-formed according to C++
387 /// [dcl.fct.default].
388 void Sema::CheckCXXDefaultArguments(FunctionDecl
*FD
) {
389 unsigned NumParams
= FD
->getNumParams();
392 // Find first parameter with a default argument
393 for (p
= 0; p
< NumParams
; ++p
) {
394 ParmVarDecl
*Param
= FD
->getParamDecl(p
);
395 if (Param
->hasDefaultArg())
399 // C++ [dcl.fct.default]p4:
400 // In a given function declaration, all parameters
401 // subsequent to a parameter with a default argument shall
402 // have default arguments supplied in this or previous
403 // declarations. A default argument shall not be redefined
404 // by a later declaration (not even to the same value).
405 unsigned LastMissingDefaultArg
= 0;
406 for (; p
< NumParams
; ++p
) {
407 ParmVarDecl
*Param
= FD
->getParamDecl(p
);
408 if (!Param
->hasDefaultArg()) {
409 if (Param
->isInvalidDecl())
410 /* We already complained about this parameter. */;
411 else if (Param
->getIdentifier())
412 Diag(Param
->getLocation(),
413 diag::err_param_default_argument_missing_name
)
414 << Param
->getIdentifier();
416 Diag(Param
->getLocation(),
417 diag::err_param_default_argument_missing
);
419 LastMissingDefaultArg
= p
;
423 if (LastMissingDefaultArg
> 0) {
424 // Some default arguments were missing. Clear out all of the
425 // default arguments up to (and including) the last missing
426 // default argument, so that we leave the function parameters
427 // in a semantically valid state.
428 for (p
= 0; p
<= LastMissingDefaultArg
; ++p
) {
429 ParmVarDecl
*Param
= FD
->getParamDecl(p
);
430 if (Param
->hasDefaultArg()) {
431 Param
->setDefaultArg(0);
437 /// isCurrentClassName - Determine whether the identifier II is the
438 /// name of the class type currently being defined. In the case of
439 /// nested classes, this will only return true if II is the name of
440 /// the innermost class.
441 bool Sema::isCurrentClassName(const IdentifierInfo
&II
, Scope
*,
442 const CXXScopeSpec
*SS
) {
443 assert(getLangOptions().CPlusPlus
&& "No class names in C!");
445 CXXRecordDecl
*CurDecl
;
446 if (SS
&& SS
->isSet() && !SS
->isInvalid()) {
447 DeclContext
*DC
= computeDeclContext(*SS
, true);
448 CurDecl
= dyn_cast_or_null
<CXXRecordDecl
>(DC
);
450 CurDecl
= dyn_cast_or_null
<CXXRecordDecl
>(CurContext
);
452 if (CurDecl
&& CurDecl
->getIdentifier())
453 return &II
== CurDecl
->getIdentifier();
458 /// \brief Check the validity of a C++ base class specifier.
460 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
461 /// and returns NULL otherwise.
463 Sema::CheckBaseSpecifier(CXXRecordDecl
*Class
,
464 SourceRange SpecifierRange
,
465 bool Virtual
, AccessSpecifier Access
,
466 TypeSourceInfo
*TInfo
,
467 SourceLocation EllipsisLoc
) {
468 QualType BaseType
= TInfo
->getType();
470 // C++ [class.union]p1:
471 // A union shall not have base classes.
472 if (Class
->isUnion()) {
473 Diag(Class
->getLocation(), diag::err_base_clause_on_union
)
478 if (EllipsisLoc
.isValid() &&
479 !TInfo
->getType()->containsUnexpandedParameterPack()) {
480 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
481 << TInfo
->getTypeLoc().getSourceRange();
482 EllipsisLoc
= SourceLocation();
485 if (BaseType
->isDependentType())
486 return new (Context
) CXXBaseSpecifier(SpecifierRange
, Virtual
,
487 Class
->getTagKind() == TTK_Class
,
488 Access
, TInfo
, EllipsisLoc
);
490 SourceLocation BaseLoc
= TInfo
->getTypeLoc().getBeginLoc();
492 // Base specifiers must be record types.
493 if (!BaseType
->isRecordType()) {
494 Diag(BaseLoc
, diag::err_base_must_be_class
) << SpecifierRange
;
498 // C++ [class.union]p1:
499 // A union shall not be used as a base class.
500 if (BaseType
->isUnionType()) {
501 Diag(BaseLoc
, diag::err_union_as_base_class
) << SpecifierRange
;
505 // C++ [class.derived]p2:
506 // The class-name in a base-specifier shall not be an incompletely
508 if (RequireCompleteType(BaseLoc
, BaseType
,
509 PDiag(diag::err_incomplete_base_class
)
510 << SpecifierRange
)) {
511 Class
->setInvalidDecl();
515 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
516 RecordDecl
*BaseDecl
= BaseType
->getAs
<RecordType
>()->getDecl();
517 assert(BaseDecl
&& "Record type has no declaration");
518 BaseDecl
= BaseDecl
->getDefinition();
519 assert(BaseDecl
&& "Base type is not incomplete, but has no definition");
520 CXXRecordDecl
* CXXBaseDecl
= cast
<CXXRecordDecl
>(BaseDecl
);
521 assert(CXXBaseDecl
&& "Base type is not a C++ type");
523 // C++ [class.derived]p2:
524 // If a class is marked with the class-virt-specifier final and it appears
525 // as a base-type-specifier in a base-clause (10 class.derived), the program
527 if (CXXBaseDecl
->hasAttr
<FinalAttr
>()) {
528 Diag(BaseLoc
, diag::err_class_marked_final_used_as_base
)
529 << CXXBaseDecl
->getDeclName();
530 Diag(CXXBaseDecl
->getLocation(), diag::note_previous_decl
)
531 << CXXBaseDecl
->getDeclName();
535 if (BaseDecl
->isInvalidDecl())
536 Class
->setInvalidDecl();
538 // Create the base specifier.
539 return new (Context
) CXXBaseSpecifier(SpecifierRange
, Virtual
,
540 Class
->getTagKind() == TTK_Class
,
541 Access
, TInfo
, EllipsisLoc
);
544 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
545 /// one entry in the base class list of a class specifier, for
547 /// class foo : public bar, virtual private baz {
548 /// 'public bar' and 'virtual private baz' are each base-specifiers.
550 Sema::ActOnBaseSpecifier(Decl
*classdecl
, SourceRange SpecifierRange
,
551 bool Virtual
, AccessSpecifier Access
,
552 ParsedType basetype
, SourceLocation BaseLoc
,
553 SourceLocation EllipsisLoc
) {
557 AdjustDeclIfTemplate(classdecl
);
558 CXXRecordDecl
*Class
= dyn_cast
<CXXRecordDecl
>(classdecl
);
562 TypeSourceInfo
*TInfo
= 0;
563 GetTypeFromParser(basetype
, &TInfo
);
565 if (EllipsisLoc
.isInvalid() &&
566 DiagnoseUnexpandedParameterPack(SpecifierRange
.getBegin(), TInfo
,
570 if (CXXBaseSpecifier
*BaseSpec
= CheckBaseSpecifier(Class
, SpecifierRange
,
571 Virtual
, Access
, TInfo
,
578 /// \brief Performs the actual work of attaching the given base class
579 /// specifiers to a C++ class.
580 bool Sema::AttachBaseSpecifiers(CXXRecordDecl
*Class
, CXXBaseSpecifier
**Bases
,
585 // Used to keep track of which base types we have already seen, so
586 // that we can properly diagnose redundant direct base types. Note
587 // that the key is always the unqualified canonical type of the base
589 std::map
<QualType
, CXXBaseSpecifier
*, QualTypeOrdering
> KnownBaseTypes
;
591 // Copy non-redundant base specifiers into permanent storage.
592 unsigned NumGoodBases
= 0;
593 bool Invalid
= false;
594 for (unsigned idx
= 0; idx
< NumBases
; ++idx
) {
596 = Context
.getCanonicalType(Bases
[idx
]->getType());
597 NewBaseType
= NewBaseType
.getLocalUnqualifiedType();
598 if (!Class
->hasObjectMember()) {
599 if (const RecordType
*FDTTy
=
600 NewBaseType
.getTypePtr()->getAs
<RecordType
>())
601 if (FDTTy
->getDecl()->hasObjectMember())
602 Class
->setHasObjectMember(true);
605 if (KnownBaseTypes
[NewBaseType
]) {
607 // A class shall not be specified as a direct base class of a
608 // derived class more than once.
609 Diag(Bases
[idx
]->getSourceRange().getBegin(),
610 diag::err_duplicate_base_class
)
611 << KnownBaseTypes
[NewBaseType
]->getType()
612 << Bases
[idx
]->getSourceRange();
614 // Delete the duplicate base class specifier; we're going to
615 // overwrite its pointer later.
616 Context
.Deallocate(Bases
[idx
]);
620 // Okay, add this new base class.
621 KnownBaseTypes
[NewBaseType
] = Bases
[idx
];
622 Bases
[NumGoodBases
++] = Bases
[idx
];
626 // Attach the remaining base class specifiers to the derived class.
627 Class
->setBases(Bases
, NumGoodBases
);
629 // Delete the remaining (good) base class specifiers, since their
630 // data has been copied into the CXXRecordDecl.
631 for (unsigned idx
= 0; idx
< NumGoodBases
; ++idx
)
632 Context
.Deallocate(Bases
[idx
]);
637 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
638 /// class, after checking whether there are any duplicate base
640 void Sema::ActOnBaseSpecifiers(Decl
*ClassDecl
, BaseTy
**Bases
,
642 if (!ClassDecl
|| !Bases
|| !NumBases
)
645 AdjustDeclIfTemplate(ClassDecl
);
646 AttachBaseSpecifiers(cast
<CXXRecordDecl
>(ClassDecl
),
647 (CXXBaseSpecifier
**)(Bases
), NumBases
);
650 static CXXRecordDecl
*GetClassForType(QualType T
) {
651 if (const RecordType
*RT
= T
->getAs
<RecordType
>())
652 return cast
<CXXRecordDecl
>(RT
->getDecl());
653 else if (const InjectedClassNameType
*ICT
= T
->getAs
<InjectedClassNameType
>())
654 return ICT
->getDecl();
659 /// \brief Determine whether the type \p Derived is a C++ class that is
660 /// derived from the type \p Base.
661 bool Sema::IsDerivedFrom(QualType Derived
, QualType Base
) {
662 if (!getLangOptions().CPlusPlus
)
665 CXXRecordDecl
*DerivedRD
= GetClassForType(Derived
);
669 CXXRecordDecl
*BaseRD
= GetClassForType(Base
);
673 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
674 return DerivedRD
->hasDefinition() && DerivedRD
->isDerivedFrom(BaseRD
);
677 /// \brief Determine whether the type \p Derived is a C++ class that is
678 /// derived from the type \p Base.
679 bool Sema::IsDerivedFrom(QualType Derived
, QualType Base
, CXXBasePaths
&Paths
) {
680 if (!getLangOptions().CPlusPlus
)
683 CXXRecordDecl
*DerivedRD
= GetClassForType(Derived
);
687 CXXRecordDecl
*BaseRD
= GetClassForType(Base
);
691 return DerivedRD
->isDerivedFrom(BaseRD
, Paths
);
694 void Sema::BuildBasePathArray(const CXXBasePaths
&Paths
,
695 CXXCastPath
&BasePathArray
) {
696 assert(BasePathArray
.empty() && "Base path array must be empty!");
697 assert(Paths
.isRecordingPaths() && "Must record paths!");
699 const CXXBasePath
&Path
= Paths
.front();
701 // We first go backward and check if we have a virtual base.
702 // FIXME: It would be better if CXXBasePath had the base specifier for
703 // the nearest virtual base.
705 for (unsigned I
= Path
.size(); I
!= 0; --I
) {
706 if (Path
[I
- 1].Base
->isVirtual()) {
712 // Now add all bases.
713 for (unsigned I
= Start
, E
= Path
.size(); I
!= E
; ++I
)
714 BasePathArray
.push_back(const_cast<CXXBaseSpecifier
*>(Path
[I
].Base
));
717 /// \brief Determine whether the given base path includes a virtual
719 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath
&BasePath
) {
720 for (CXXCastPath::const_iterator B
= BasePath
.begin(),
721 BEnd
= BasePath
.end();
723 if ((*B
)->isVirtual())
729 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
730 /// conversion (where Derived and Base are class types) is
731 /// well-formed, meaning that the conversion is unambiguous (and
732 /// that all of the base classes are accessible). Returns true
733 /// and emits a diagnostic if the code is ill-formed, returns false
734 /// otherwise. Loc is the location where this routine should point to
735 /// if there is an error, and Range is the source range to highlight
736 /// if there is an error.
738 Sema::CheckDerivedToBaseConversion(QualType Derived
, QualType Base
,
739 unsigned InaccessibleBaseID
,
740 unsigned AmbigiousBaseConvID
,
741 SourceLocation Loc
, SourceRange Range
,
742 DeclarationName Name
,
743 CXXCastPath
*BasePath
) {
744 // First, determine whether the path from Derived to Base is
745 // ambiguous. This is slightly more expensive than checking whether
746 // the Derived to Base conversion exists, because here we need to
747 // explore multiple paths to determine if there is an ambiguity.
748 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
749 /*DetectVirtual=*/false);
750 bool DerivationOkay
= IsDerivedFrom(Derived
, Base
, Paths
);
751 assert(DerivationOkay
&&
752 "Can only be used with a derived-to-base conversion");
753 (void)DerivationOkay
;
755 if (!Paths
.isAmbiguous(Context
.getCanonicalType(Base
).getUnqualifiedType())) {
756 if (InaccessibleBaseID
) {
757 // Check that the base class can be accessed.
758 switch (CheckBaseClassAccess(Loc
, Base
, Derived
, Paths
.front(),
759 InaccessibleBaseID
)) {
760 case AR_inaccessible
:
769 // Build a base path if necessary.
771 BuildBasePathArray(Paths
, *BasePath
);
775 // We know that the derived-to-base conversion is ambiguous, and
776 // we're going to produce a diagnostic. Perform the derived-to-base
777 // search just one more time to compute all of the possible paths so
778 // that we can print them out. This is more expensive than any of
779 // the previous derived-to-base checks we've done, but at this point
780 // performance isn't as much of an issue.
782 Paths
.setRecordingPaths(true);
783 bool StillOkay
= IsDerivedFrom(Derived
, Base
, Paths
);
784 assert(StillOkay
&& "Can only be used with a derived-to-base conversion");
787 // Build up a textual representation of the ambiguous paths, e.g.,
788 // D -> B -> A, that will be used to illustrate the ambiguous
789 // conversions in the diagnostic. We only print one of the paths
790 // to each base class subobject.
791 std::string PathDisplayStr
= getAmbiguousPathsDisplayString(Paths
);
793 Diag(Loc
, AmbigiousBaseConvID
)
794 << Derived
<< Base
<< PathDisplayStr
<< Range
<< Name
;
799 Sema::CheckDerivedToBaseConversion(QualType Derived
, QualType Base
,
800 SourceLocation Loc
, SourceRange Range
,
801 CXXCastPath
*BasePath
,
803 return CheckDerivedToBaseConversion(Derived
, Base
,
805 : diag::err_upcast_to_inaccessible_base
,
806 diag::err_ambiguous_derived_to_base_conv
,
807 Loc
, Range
, DeclarationName(),
812 /// @brief Builds a string representing ambiguous paths from a
813 /// specific derived class to different subobjects of the same base
816 /// This function builds a string that can be used in error messages
817 /// to show the different paths that one can take through the
818 /// inheritance hierarchy to go from the derived class to different
819 /// subobjects of a base class. The result looks something like this:
821 /// struct D -> struct B -> struct A
822 /// struct D -> struct C -> struct A
824 std::string
Sema::getAmbiguousPathsDisplayString(CXXBasePaths
&Paths
) {
825 std::string PathDisplayStr
;
826 std::set
<unsigned> DisplayedPaths
;
827 for (CXXBasePaths::paths_iterator Path
= Paths
.begin();
828 Path
!= Paths
.end(); ++Path
) {
829 if (DisplayedPaths
.insert(Path
->back().SubobjectNumber
).second
) {
830 // We haven't displayed a path to this particular base
831 // class subobject yet.
832 PathDisplayStr
+= "\n ";
833 PathDisplayStr
+= Context
.getTypeDeclType(Paths
.getOrigin()).getAsString();
834 for (CXXBasePath::const_iterator Element
= Path
->begin();
835 Element
!= Path
->end(); ++Element
)
836 PathDisplayStr
+= " -> " + Element
->Base
->getType().getAsString();
840 return PathDisplayStr
;
843 //===----------------------------------------------------------------------===//
844 // C++ class member Handling
845 //===----------------------------------------------------------------------===//
847 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
848 Decl
*Sema::ActOnAccessSpecifier(AccessSpecifier Access
,
849 SourceLocation ASLoc
,
850 SourceLocation ColonLoc
) {
851 assert(Access
!= AS_none
&& "Invalid kind for syntactic access specifier!");
852 AccessSpecDecl
*ASDecl
= AccessSpecDecl::Create(Context
, Access
, CurContext
,
854 CurContext
->addHiddenDecl(ASDecl
);
858 /// CheckOverrideControl - Check C++0x override control semantics.
859 void Sema::CheckOverrideControl(const Decl
*D
) {
860 const CXXMethodDecl
*MD
= llvm::dyn_cast
<CXXMethodDecl
>(D
);
861 if (!MD
|| !MD
->isVirtual())
864 if (MD
->isDependentContext())
867 // C++0x [class.virtual]p3:
868 // If a virtual function is marked with the virt-specifier override and does
869 // not override a member function of a base class,
870 // the program is ill-formed.
871 bool HasOverriddenMethods
=
872 MD
->begin_overridden_methods() != MD
->end_overridden_methods();
873 if (MD
->hasAttr
<OverrideAttr
>() && !HasOverriddenMethods
) {
874 Diag(MD
->getLocation(),
875 diag::err_function_marked_override_not_overriding
)
876 << MD
->getDeclName();
880 // C++0x [class.derived]p8:
881 // In a class definition marked with the class-virt-specifier explicit,
882 // if a virtual member function that is neither implicitly-declared nor a
883 // destructor overrides a member function of a base class and it is not
884 // marked with the virt-specifier override, the program is ill-formed.
885 if (MD
->getParent()->hasAttr
<ExplicitAttr
>() && !isa
<CXXDestructorDecl
>(MD
) &&
886 HasOverriddenMethods
&& !MD
->hasAttr
<OverrideAttr
>()) {
887 llvm::SmallVector
<const CXXMethodDecl
*, 4>
888 OverriddenMethods(MD
->begin_overridden_methods(),
889 MD
->end_overridden_methods());
891 Diag(MD
->getLocation(), diag::err_function_overriding_without_override
)
893 << (unsigned)OverriddenMethods
.size();
895 for (unsigned I
= 0; I
!= OverriddenMethods
.size(); ++I
)
896 Diag(OverriddenMethods
[I
]->getLocation(),
897 diag::note_overridden_virtual_function
);
901 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
902 /// function overrides a virtual member function marked 'final', according to
903 /// C++0x [class.virtual]p3.
904 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl
*New
,
905 const CXXMethodDecl
*Old
) {
906 if (!Old
->hasAttr
<FinalAttr
>())
909 Diag(New
->getLocation(), diag::err_final_function_overridden
)
910 << New
->getDeclName();
911 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
915 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
916 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
917 /// bitfield width if there is one and 'InitExpr' specifies the initializer if
920 Sema::ActOnCXXMemberDeclarator(Scope
*S
, AccessSpecifier AS
, Declarator
&D
,
921 MultiTemplateParamsArg TemplateParameterLists
,
922 ExprTy
*BW
, const VirtSpecifiers
&VS
,
923 ExprTy
*InitExpr
, bool IsDefinition
,
925 const DeclSpec
&DS
= D
.getDeclSpec();
926 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
927 DeclarationName Name
= NameInfo
.getName();
928 SourceLocation Loc
= NameInfo
.getLoc();
930 // For anonymous bitfields, the location should point to the type.
932 Loc
= D
.getSourceRange().getBegin();
934 Expr
*BitWidth
= static_cast<Expr
*>(BW
);
935 Expr
*Init
= static_cast<Expr
*>(InitExpr
);
937 assert(isa
<CXXRecordDecl
>(CurContext
));
938 assert(!DS
.isFriendSpecified());
941 if (D
.isFunctionDeclarator())
943 else if (D
.getNumTypeObjects() == 0 &&
944 D
.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename
) {
945 QualType TDType
= GetTypeFromParser(DS
.getRepAsType());
946 isFunc
= TDType
->isFunctionType();
949 // C++ 9.2p6: A member shall not be declared to have automatic storage
950 // duration (auto, register) or with the extern storage-class-specifier.
951 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
952 // data members and cannot be applied to names declared const or static,
953 // and cannot be applied to reference members.
954 switch (DS
.getStorageClassSpec()) {
955 case DeclSpec::SCS_unspecified
:
956 case DeclSpec::SCS_typedef
:
957 case DeclSpec::SCS_static
:
960 case DeclSpec::SCS_mutable
:
962 if (DS
.getStorageClassSpecLoc().isValid())
963 Diag(DS
.getStorageClassSpecLoc(), diag::err_mutable_function
);
965 Diag(DS
.getThreadSpecLoc(), diag::err_mutable_function
);
967 // FIXME: It would be nicer if the keyword was ignored only for this
968 // declarator. Otherwise we could get follow-up errors.
969 D
.getMutableDeclSpec().ClearStorageClassSpecs();
973 if (DS
.getStorageClassSpecLoc().isValid())
974 Diag(DS
.getStorageClassSpecLoc(),
975 diag::err_storageclass_invalid_for_member
);
977 Diag(DS
.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member
);
978 D
.getMutableDeclSpec().ClearStorageClassSpecs();
981 bool isInstField
= ((DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
||
982 DS
.getStorageClassSpec() == DeclSpec::SCS_mutable
) &&
987 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
990 if (SS
.isSet() && !SS
.isInvalid()) {
991 // The user provided a superfluous scope specifier inside a class
998 if ((DC
= computeDeclContext(SS
, false)) && DC
->Equals(CurContext
))
999 Diag(D
.getIdentifierLoc(), diag::warn_member_extra_qualification
)
1000 << Name
<< FixItHint::CreateRemoval(SS
.getRange());
1002 Diag(D
.getIdentifierLoc(), diag::err_member_qualification
)
1003 << Name
<< SS
.getRange();
1008 // FIXME: Check for template parameters!
1009 // FIXME: Check that the name is an identifier!
1010 Member
= HandleField(S
, cast
<CXXRecordDecl
>(CurContext
), Loc
, D
, BitWidth
,
1012 assert(Member
&& "HandleField never returns null");
1014 Member
= HandleDeclarator(S
, D
, move(TemplateParameterLists
), IsDefinition
);
1019 // Non-instance-fields can't have a bitfield.
1021 if (Member
->isInvalidDecl()) {
1022 // don't emit another diagnostic.
1023 } else if (isa
<VarDecl
>(Member
)) {
1024 // C++ 9.6p3: A bit-field shall not be a static member.
1025 // "static member 'A' cannot be a bit-field"
1026 Diag(Loc
, diag::err_static_not_bitfield
)
1027 << Name
<< BitWidth
->getSourceRange();
1028 } else if (isa
<TypedefDecl
>(Member
)) {
1029 // "typedef member 'x' cannot be a bit-field"
1030 Diag(Loc
, diag::err_typedef_not_bitfield
)
1031 << Name
<< BitWidth
->getSourceRange();
1033 // A function typedef ("typedef int f(); f a;").
1034 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1035 Diag(Loc
, diag::err_not_integral_type_bitfield
)
1036 << Name
<< cast
<ValueDecl
>(Member
)->getType()
1037 << BitWidth
->getSourceRange();
1041 Member
->setInvalidDecl();
1044 Member
->setAccess(AS
);
1046 // If we have declared a member function template, set the access of the
1047 // templated declaration as well.
1048 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(Member
))
1049 FunTmpl
->getTemplatedDecl()->setAccess(AS
);
1052 if (VS
.isOverrideSpecified()) {
1053 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(Member
);
1054 if (!MD
|| !MD
->isVirtual()) {
1055 Diag(Member
->getLocStart(),
1056 diag::override_keyword_only_allowed_on_virtual_member_functions
)
1057 << "override" << FixItHint::CreateRemoval(VS
.getOverrideLoc());
1059 MD
->addAttr(new (Context
) OverrideAttr(VS
.getOverrideLoc(), Context
));
1061 if (VS
.isFinalSpecified()) {
1062 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(Member
);
1063 if (!MD
|| !MD
->isVirtual()) {
1064 Diag(Member
->getLocStart(),
1065 diag::override_keyword_only_allowed_on_virtual_member_functions
)
1066 << "final" << FixItHint::CreateRemoval(VS
.getFinalLoc());
1068 MD
->addAttr(new (Context
) FinalAttr(VS
.getFinalLoc(), Context
));
1071 CheckOverrideControl(Member
);
1073 assert((Name
|| isInstField
) && "No identifier for non-field ?");
1076 AddInitializerToDecl(Member
, Init
, false);
1077 if (Deleted
) // FIXME: Source location is not very good.
1078 SetDeclDeleted(Member
, D
.getSourceRange().getBegin());
1081 FieldCollector
->Add(cast
<FieldDecl
>(Member
));
1085 /// \brief Find the direct and/or virtual base specifiers that
1086 /// correspond to the given base type, for use in base initialization
1087 /// within a constructor.
1088 static bool FindBaseInitializer(Sema
&SemaRef
,
1089 CXXRecordDecl
*ClassDecl
,
1091 const CXXBaseSpecifier
*&DirectBaseSpec
,
1092 const CXXBaseSpecifier
*&VirtualBaseSpec
) {
1093 // First, check for a direct base class.
1095 for (CXXRecordDecl::base_class_const_iterator Base
1096 = ClassDecl
->bases_begin();
1097 Base
!= ClassDecl
->bases_end(); ++Base
) {
1098 if (SemaRef
.Context
.hasSameUnqualifiedType(BaseType
, Base
->getType())) {
1099 // We found a direct base of this type. That's what we're
1101 DirectBaseSpec
= &*Base
;
1106 // Check for a virtual base class.
1107 // FIXME: We might be able to short-circuit this if we know in advance that
1108 // there are no virtual bases.
1109 VirtualBaseSpec
= 0;
1110 if (!DirectBaseSpec
|| !DirectBaseSpec
->isVirtual()) {
1111 // We haven't found a base yet; search the class hierarchy for a
1112 // virtual base class.
1113 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1114 /*DetectVirtual=*/false);
1115 if (SemaRef
.IsDerivedFrom(SemaRef
.Context
.getTypeDeclType(ClassDecl
),
1117 for (CXXBasePaths::paths_iterator Path
= Paths
.begin();
1118 Path
!= Paths
.end(); ++Path
) {
1119 if (Path
->back().Base
->isVirtual()) {
1120 VirtualBaseSpec
= Path
->back().Base
;
1127 return DirectBaseSpec
|| VirtualBaseSpec
;
1130 /// ActOnMemInitializer - Handle a C++ member initializer.
1132 Sema::ActOnMemInitializer(Decl
*ConstructorD
,
1135 IdentifierInfo
*MemberOrBase
,
1136 ParsedType TemplateTypeTy
,
1137 SourceLocation IdLoc
,
1138 SourceLocation LParenLoc
,
1139 ExprTy
**Args
, unsigned NumArgs
,
1140 SourceLocation RParenLoc
,
1141 SourceLocation EllipsisLoc
) {
1145 AdjustDeclIfTemplate(ConstructorD
);
1147 CXXConstructorDecl
*Constructor
1148 = dyn_cast
<CXXConstructorDecl
>(ConstructorD
);
1150 // The user wrote a constructor initializer on a function that is
1151 // not a C++ constructor. Ignore the error for now, because we may
1152 // have more member initializers coming; we'll diagnose it just
1153 // once in ActOnMemInitializers.
1157 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
1159 // C++ [class.base.init]p2:
1160 // Names in a mem-initializer-id are looked up in the scope of the
1161 // constructor's class and, if not found in that scope, are looked
1162 // up in the scope containing the constructor's definition.
1163 // [Note: if the constructor's class contains a member with the
1164 // same name as a direct or virtual base class of the class, a
1165 // mem-initializer-id naming the member or base class and composed
1166 // of a single identifier refers to the class member. A
1167 // mem-initializer-id for the hidden base class may be specified
1168 // using a qualified name. ]
1169 if (!SS
.getScopeRep() && !TemplateTypeTy
) {
1170 // Look for a member, first.
1171 FieldDecl
*Member
= 0;
1172 DeclContext::lookup_result Result
1173 = ClassDecl
->lookup(MemberOrBase
);
1174 if (Result
.first
!= Result
.second
) {
1175 Member
= dyn_cast
<FieldDecl
>(*Result
.first
);
1178 if (EllipsisLoc
.isValid())
1179 Diag(EllipsisLoc
, diag::err_pack_expansion_member_init
)
1180 << MemberOrBase
<< SourceRange(IdLoc
, RParenLoc
);
1182 return BuildMemberInitializer(Member
, (Expr
**)Args
, NumArgs
, IdLoc
,
1183 LParenLoc
, RParenLoc
);
1186 // Handle anonymous union case.
1187 if (IndirectFieldDecl
* IndirectField
1188 = dyn_cast
<IndirectFieldDecl
>(*Result
.first
)) {
1189 if (EllipsisLoc
.isValid())
1190 Diag(EllipsisLoc
, diag::err_pack_expansion_member_init
)
1191 << MemberOrBase
<< SourceRange(IdLoc
, RParenLoc
);
1193 return BuildMemberInitializer(IndirectField
, (Expr
**)Args
,
1195 LParenLoc
, RParenLoc
);
1199 // It didn't name a member, so see if it names a class.
1201 TypeSourceInfo
*TInfo
= 0;
1203 if (TemplateTypeTy
) {
1204 BaseType
= GetTypeFromParser(TemplateTypeTy
, &TInfo
);
1206 LookupResult
R(*this, MemberOrBase
, IdLoc
, LookupOrdinaryName
);
1207 LookupParsedName(R
, S
, &SS
);
1209 TypeDecl
*TyD
= R
.getAsSingle
<TypeDecl
>();
1211 if (R
.isAmbiguous()) return true;
1213 // We don't want access-control diagnostics here.
1214 R
.suppressDiagnostics();
1216 if (SS
.isSet() && isDependentScopeSpecifier(SS
)) {
1217 bool NotUnknownSpecialization
= false;
1218 DeclContext
*DC
= computeDeclContext(SS
, false);
1219 if (CXXRecordDecl
*Record
= dyn_cast_or_null
<CXXRecordDecl
>(DC
))
1220 NotUnknownSpecialization
= !Record
->hasAnyDependentBases();
1222 if (!NotUnknownSpecialization
) {
1223 // When the scope specifier can refer to a member of an unknown
1224 // specialization, we take it as a type name.
1225 BaseType
= CheckTypenameType(ETK_None
,
1226 (NestedNameSpecifier
*)SS
.getScopeRep(),
1227 *MemberOrBase
, SourceLocation(),
1228 SS
.getRange(), IdLoc
);
1229 if (BaseType
.isNull())
1233 R
.setLookupName(MemberOrBase
);
1237 // If no results were found, try to correct typos.
1238 if (R
.empty() && BaseType
.isNull() &&
1239 CorrectTypo(R
, S
, &SS
, ClassDecl
, 0, CTC_NoKeywords
) &&
1240 R
.isSingleResult()) {
1241 if (FieldDecl
*Member
= R
.getAsSingle
<FieldDecl
>()) {
1242 if (Member
->getDeclContext()->getRedeclContext()->Equals(ClassDecl
)) {
1243 // We have found a non-static data member with a similar
1244 // name to what was typed; complain and initialize that
1246 Diag(R
.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest
)
1247 << MemberOrBase
<< true << R
.getLookupName()
1248 << FixItHint::CreateReplacement(R
.getNameLoc(),
1249 R
.getLookupName().getAsString());
1250 Diag(Member
->getLocation(), diag::note_previous_decl
)
1251 << Member
->getDeclName();
1253 return BuildMemberInitializer(Member
, (Expr
**)Args
, NumArgs
, IdLoc
,
1254 LParenLoc
, RParenLoc
);
1256 } else if (TypeDecl
*Type
= R
.getAsSingle
<TypeDecl
>()) {
1257 const CXXBaseSpecifier
*DirectBaseSpec
;
1258 const CXXBaseSpecifier
*VirtualBaseSpec
;
1259 if (FindBaseInitializer(*this, ClassDecl
,
1260 Context
.getTypeDeclType(Type
),
1261 DirectBaseSpec
, VirtualBaseSpec
)) {
1262 // We have found a direct or virtual base class with a
1263 // similar name to what was typed; complain and initialize
1265 Diag(R
.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest
)
1266 << MemberOrBase
<< false << R
.getLookupName()
1267 << FixItHint::CreateReplacement(R
.getNameLoc(),
1268 R
.getLookupName().getAsString());
1270 const CXXBaseSpecifier
*BaseSpec
= DirectBaseSpec
? DirectBaseSpec
1272 Diag(BaseSpec
->getSourceRange().getBegin(),
1273 diag::note_base_class_specified_here
)
1274 << BaseSpec
->getType()
1275 << BaseSpec
->getSourceRange();
1282 if (!TyD
&& BaseType
.isNull()) {
1283 Diag(IdLoc
, diag::err_mem_init_not_member_or_class
)
1284 << MemberOrBase
<< SourceRange(IdLoc
, RParenLoc
);
1289 if (BaseType
.isNull()) {
1290 BaseType
= Context
.getTypeDeclType(TyD
);
1292 NestedNameSpecifier
*Qualifier
=
1293 static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
1295 // FIXME: preserve source range information
1296 BaseType
= Context
.getElaboratedType(ETK_None
, Qualifier
, BaseType
);
1302 TInfo
= Context
.getTrivialTypeSourceInfo(BaseType
, IdLoc
);
1304 return BuildBaseInitializer(BaseType
, TInfo
, (Expr
**)Args
, NumArgs
,
1305 LParenLoc
, RParenLoc
, ClassDecl
, EllipsisLoc
);
1308 /// Checks an initializer expression for use of uninitialized fields, such as
1309 /// containing the field that is being initialized. Returns true if there is an
1310 /// uninitialized field was used an updates the SourceLocation parameter; false
1312 static bool InitExprContainsUninitializedFields(const Stmt
*S
,
1313 const ValueDecl
*LhsField
,
1314 SourceLocation
*L
) {
1315 assert(isa
<FieldDecl
>(LhsField
) || isa
<IndirectFieldDecl
>(LhsField
));
1317 if (isa
<CallExpr
>(S
)) {
1318 // Do not descend into function calls or constructors, as the use
1319 // of an uninitialized field may be valid. One would have to inspect
1320 // the contents of the function/ctor to determine if it is safe or not.
1321 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1322 // may be safe, depending on what the function/ctor does.
1325 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(S
)) {
1326 const NamedDecl
*RhsField
= ME
->getMemberDecl();
1328 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(RhsField
)) {
1329 // The member expression points to a static data member.
1330 assert(VD
->isStaticDataMember() &&
1331 "Member points to non-static data member!");
1336 if (isa
<EnumConstantDecl
>(RhsField
)) {
1337 // The member expression points to an enum.
1341 if (RhsField
== LhsField
) {
1342 // Initializing a field with itself. Throw a warning.
1343 // But wait; there are exceptions!
1344 // Exception #1: The field may not belong to this record.
1345 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1346 const Expr
*base
= ME
->getBase();
1347 if (base
!= NULL
&& !isa
<CXXThisExpr
>(base
->IgnoreParenCasts())) {
1348 // Even though the field matches, it does not belong to this record.
1351 // None of the exceptions triggered; return true to indicate an
1352 // uninitialized field was used.
1353 *L
= ME
->getMemberLoc();
1356 } else if (isa
<SizeOfAlignOfExpr
>(S
)) {
1357 // sizeof/alignof doesn't reference contents, do not warn.
1359 } else if (const UnaryOperator
*UOE
= dyn_cast
<UnaryOperator
>(S
)) {
1360 // address-of doesn't reference contents (the pointer may be dereferenced
1361 // in the same expression but it would be rare; and weird).
1362 if (UOE
->getOpcode() == UO_AddrOf
)
1365 for (Stmt::const_child_range it
= S
->children(); it
; ++it
) {
1367 // An expression such as 'member(arg ?: "")' may trigger this.
1370 if (InitExprContainsUninitializedFields(*it
, LhsField
, L
))
1377 Sema::BuildMemberInitializer(ValueDecl
*Member
, Expr
**Args
,
1378 unsigned NumArgs
, SourceLocation IdLoc
,
1379 SourceLocation LParenLoc
,
1380 SourceLocation RParenLoc
) {
1381 FieldDecl
*DirectMember
= dyn_cast
<FieldDecl
>(Member
);
1382 IndirectFieldDecl
*IndirectMember
= dyn_cast
<IndirectFieldDecl
>(Member
);
1383 assert((DirectMember
|| IndirectMember
) &&
1384 "Member must be a FieldDecl or IndirectFieldDecl");
1386 if (Member
->isInvalidDecl())
1389 // Diagnose value-uses of fields to initialize themselves, e.g.
1391 // where foo is not also a parameter to the constructor.
1392 // TODO: implement -Wuninitialized and fold this into that framework.
1393 for (unsigned i
= 0; i
< NumArgs
; ++i
) {
1395 if (InitExprContainsUninitializedFields(Args
[i
], Member
, &L
)) {
1396 // FIXME: Return true in the case when other fields are used before being
1397 // uninitialized. For example, let this field be the i'th field. When
1398 // initializing the i'th field, throw a warning if any of the >= i'th
1399 // fields are used, as they are not yet initialized.
1400 // Right now we are only handling the case where the i'th field uses
1401 // itself in its initializer.
1402 Diag(L
, diag::warn_field_is_uninit
);
1406 bool HasDependentArg
= false;
1407 for (unsigned i
= 0; i
< NumArgs
; i
++)
1408 HasDependentArg
|= Args
[i
]->isTypeDependent();
1411 if (Member
->getType()->isDependentType() || HasDependentArg
) {
1412 // Can't check initialization for a member of dependent type or when
1413 // any of the arguments are type-dependent expressions.
1414 Init
= new (Context
) ParenListExpr(Context
, LParenLoc
, Args
, NumArgs
,
1417 // Erase any temporaries within this evaluation context; we're not
1418 // going to track them in the AST, since we'll be rebuilding the
1419 // ASTs during template instantiation.
1420 ExprTemporaries
.erase(
1421 ExprTemporaries
.begin() + ExprEvalContexts
.back().NumTemporaries
,
1422 ExprTemporaries
.end());
1424 // Initialize the member.
1425 InitializedEntity MemberEntity
=
1426 DirectMember
? InitializedEntity::InitializeMember(DirectMember
, 0)
1427 : InitializedEntity::InitializeMember(IndirectMember
, 0);
1428 InitializationKind Kind
=
1429 InitializationKind::CreateDirect(IdLoc
, LParenLoc
, RParenLoc
);
1431 InitializationSequence
InitSeq(*this, MemberEntity
, Kind
, Args
, NumArgs
);
1433 ExprResult MemberInit
=
1434 InitSeq
.Perform(*this, MemberEntity
, Kind
,
1435 MultiExprArg(*this, Args
, NumArgs
), 0);
1436 if (MemberInit
.isInvalid())
1439 CheckImplicitConversions(MemberInit
.get(), LParenLoc
);
1441 // C++0x [class.base.init]p7:
1442 // The initialization of each base and member constitutes a
1444 MemberInit
= MaybeCreateExprWithCleanups(MemberInit
);
1445 if (MemberInit
.isInvalid())
1448 // If we are in a dependent context, template instantiation will
1449 // perform this type-checking again. Just save the arguments that we
1450 // received in a ParenListExpr.
1451 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1452 // of the information that we have about the member
1453 // initializer. However, deconstructing the ASTs is a dicey process,
1454 // and this approach is far more likely to get the corner cases right.
1455 if (CurContext
->isDependentContext())
1456 Init
= new (Context
) ParenListExpr(Context
, LParenLoc
, Args
, NumArgs
,
1459 Init
= MemberInit
.get();
1463 return new (Context
) CXXCtorInitializer(Context
, DirectMember
,
1464 IdLoc
, LParenLoc
, Init
,
1467 return new (Context
) CXXCtorInitializer(Context
, IndirectMember
,
1468 IdLoc
, LParenLoc
, Init
,
1474 Sema::BuildDelegatingInitializer(TypeSourceInfo
*TInfo
,
1475 Expr
**Args
, unsigned NumArgs
,
1476 SourceLocation LParenLoc
,
1477 SourceLocation RParenLoc
,
1478 CXXRecordDecl
*ClassDecl
,
1479 SourceLocation EllipsisLoc
) {
1480 SourceLocation Loc
= TInfo
->getTypeLoc().getLocalSourceRange().getBegin();
1481 if (!LangOpts
.CPlusPlus0x
)
1482 return Diag(Loc
, diag::err_delegation_0x_only
)
1483 << TInfo
->getTypeLoc().getLocalSourceRange();
1485 return Diag(Loc
, diag::err_delegation_unimplemented
)
1486 << TInfo
->getTypeLoc().getLocalSourceRange();
1490 Sema::BuildBaseInitializer(QualType BaseType
, TypeSourceInfo
*BaseTInfo
,
1491 Expr
**Args
, unsigned NumArgs
,
1492 SourceLocation LParenLoc
, SourceLocation RParenLoc
,
1493 CXXRecordDecl
*ClassDecl
,
1494 SourceLocation EllipsisLoc
) {
1495 bool HasDependentArg
= false;
1496 for (unsigned i
= 0; i
< NumArgs
; i
++)
1497 HasDependentArg
|= Args
[i
]->isTypeDependent();
1499 SourceLocation BaseLoc
1500 = BaseTInfo
->getTypeLoc().getLocalSourceRange().getBegin();
1502 if (!BaseType
->isDependentType() && !BaseType
->isRecordType())
1503 return Diag(BaseLoc
, diag::err_base_init_does_not_name_class
)
1504 << BaseType
<< BaseTInfo
->getTypeLoc().getLocalSourceRange();
1506 // C++ [class.base.init]p2:
1507 // [...] Unless the mem-initializer-id names a nonstatic data
1508 // member of the constructor's class or a direct or virtual base
1509 // of that class, the mem-initializer is ill-formed. A
1510 // mem-initializer-list can initialize a base class using any
1511 // name that denotes that base class type.
1512 bool Dependent
= BaseType
->isDependentType() || HasDependentArg
;
1514 if (EllipsisLoc
.isValid()) {
1515 // This is a pack expansion.
1516 if (!BaseType
->containsUnexpandedParameterPack()) {
1517 Diag(EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
1518 << SourceRange(BaseLoc
, RParenLoc
);
1520 EllipsisLoc
= SourceLocation();
1523 // Check for any unexpanded parameter packs.
1524 if (DiagnoseUnexpandedParameterPack(BaseLoc
, BaseTInfo
, UPPC_Initializer
))
1527 for (unsigned I
= 0; I
!= NumArgs
; ++I
)
1528 if (DiagnoseUnexpandedParameterPack(Args
[I
]))
1532 // Check for direct and virtual base classes.
1533 const CXXBaseSpecifier
*DirectBaseSpec
= 0;
1534 const CXXBaseSpecifier
*VirtualBaseSpec
= 0;
1536 if (Context
.hasSameUnqualifiedType(QualType(ClassDecl
->getTypeForDecl(),0),
1538 return BuildDelegatingInitializer(BaseTInfo
, Args
, NumArgs
,
1539 LParenLoc
, RParenLoc
, ClassDecl
,
1542 FindBaseInitializer(*this, ClassDecl
, BaseType
, DirectBaseSpec
,
1545 // C++ [base.class.init]p2:
1546 // Unless the mem-initializer-id names a nonstatic data member of the
1547 // constructor's class or a direct or virtual base of that class, the
1548 // mem-initializer is ill-formed.
1549 if (!DirectBaseSpec
&& !VirtualBaseSpec
) {
1550 // If the class has any dependent bases, then it's possible that
1551 // one of those types will resolve to the same type as
1552 // BaseType. Therefore, just treat this as a dependent base
1553 // class initialization. FIXME: Should we try to check the
1554 // initialization anyway? It seems odd.
1555 if (ClassDecl
->hasAnyDependentBases())
1558 return Diag(BaseLoc
, diag::err_not_direct_base_or_virtual
)
1559 << BaseType
<< Context
.getTypeDeclType(ClassDecl
)
1560 << BaseTInfo
->getTypeLoc().getLocalSourceRange();
1565 // Can't check initialization for a base of dependent type or when
1566 // any of the arguments are type-dependent expressions.
1568 = Owned(new (Context
) ParenListExpr(Context
, LParenLoc
, Args
, NumArgs
,
1571 // Erase any temporaries within this evaluation context; we're not
1572 // going to track them in the AST, since we'll be rebuilding the
1573 // ASTs during template instantiation.
1574 ExprTemporaries
.erase(
1575 ExprTemporaries
.begin() + ExprEvalContexts
.back().NumTemporaries
,
1576 ExprTemporaries
.end());
1578 return new (Context
) CXXCtorInitializer(Context
, BaseTInfo
,
1579 /*IsVirtual=*/false,
1581 BaseInit
.takeAs
<Expr
>(),
1586 // C++ [base.class.init]p2:
1587 // If a mem-initializer-id is ambiguous because it designates both
1588 // a direct non-virtual base class and an inherited virtual base
1589 // class, the mem-initializer is ill-formed.
1590 if (DirectBaseSpec
&& VirtualBaseSpec
)
1591 return Diag(BaseLoc
, diag::err_base_init_direct_and_virtual
)
1592 << BaseType
<< BaseTInfo
->getTypeLoc().getLocalSourceRange();
1594 CXXBaseSpecifier
*BaseSpec
1595 = const_cast<CXXBaseSpecifier
*>(DirectBaseSpec
);
1597 BaseSpec
= const_cast<CXXBaseSpecifier
*>(VirtualBaseSpec
);
1599 // Initialize the base.
1600 InitializedEntity BaseEntity
=
1601 InitializedEntity::InitializeBase(Context
, BaseSpec
, VirtualBaseSpec
);
1602 InitializationKind Kind
=
1603 InitializationKind::CreateDirect(BaseLoc
, LParenLoc
, RParenLoc
);
1605 InitializationSequence
InitSeq(*this, BaseEntity
, Kind
, Args
, NumArgs
);
1607 ExprResult BaseInit
=
1608 InitSeq
.Perform(*this, BaseEntity
, Kind
,
1609 MultiExprArg(*this, Args
, NumArgs
), 0);
1610 if (BaseInit
.isInvalid())
1613 CheckImplicitConversions(BaseInit
.get(), LParenLoc
);
1615 // C++0x [class.base.init]p7:
1616 // The initialization of each base and member constitutes a
1618 BaseInit
= MaybeCreateExprWithCleanups(BaseInit
);
1619 if (BaseInit
.isInvalid())
1622 // If we are in a dependent context, template instantiation will
1623 // perform this type-checking again. Just save the arguments that we
1624 // received in a ParenListExpr.
1625 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1626 // of the information that we have about the base
1627 // initializer. However, deconstructing the ASTs is a dicey process,
1628 // and this approach is far more likely to get the corner cases right.
1629 if (CurContext
->isDependentContext()) {
1631 = Owned(new (Context
) ParenListExpr(Context
, LParenLoc
, Args
, NumArgs
,
1633 return new (Context
) CXXCtorInitializer(Context
, BaseTInfo
,
1634 BaseSpec
->isVirtual(),
1636 Init
.takeAs
<Expr
>(),
1641 return new (Context
) CXXCtorInitializer(Context
, BaseTInfo
,
1642 BaseSpec
->isVirtual(),
1644 BaseInit
.takeAs
<Expr
>(),
1649 /// ImplicitInitializerKind - How an implicit base or member initializer should
1650 /// initialize its base or member.
1651 enum ImplicitInitializerKind
{
1658 BuildImplicitBaseInitializer(Sema
&SemaRef
, CXXConstructorDecl
*Constructor
,
1659 ImplicitInitializerKind ImplicitInitKind
,
1660 CXXBaseSpecifier
*BaseSpec
,
1661 bool IsInheritedVirtualBase
,
1662 CXXCtorInitializer
*&CXXBaseInit
) {
1663 InitializedEntity InitEntity
1664 = InitializedEntity::InitializeBase(SemaRef
.Context
, BaseSpec
,
1665 IsInheritedVirtualBase
);
1667 ExprResult BaseInit
;
1669 switch (ImplicitInitKind
) {
1671 InitializationKind InitKind
1672 = InitializationKind::CreateDefault(Constructor
->getLocation());
1673 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
, 0, 0);
1674 BaseInit
= InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
,
1675 MultiExprArg(SemaRef
, 0, 0));
1680 ParmVarDecl
*Param
= Constructor
->getParamDecl(0);
1681 QualType ParamType
= Param
->getType().getNonReferenceType();
1684 DeclRefExpr::Create(SemaRef
.Context
, 0, SourceRange(), Param
,
1685 Constructor
->getLocation(), ParamType
,
1688 // Cast to the base class to avoid ambiguities.
1690 SemaRef
.Context
.getQualifiedType(BaseSpec
->getType().getUnqualifiedType(),
1691 ParamType
.getQualifiers());
1693 CXXCastPath BasePath
;
1694 BasePath
.push_back(BaseSpec
);
1695 SemaRef
.ImpCastExprToType(CopyCtorArg
, ArgTy
,
1696 CK_UncheckedDerivedToBase
,
1697 VK_LValue
, &BasePath
);
1699 InitializationKind InitKind
1700 = InitializationKind::CreateDirect(Constructor
->getLocation(),
1701 SourceLocation(), SourceLocation());
1702 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
,
1704 BaseInit
= InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
,
1705 MultiExprArg(&CopyCtorArg
, 1));
1710 assert(false && "Unhandled initializer kind!");
1713 BaseInit
= SemaRef
.MaybeCreateExprWithCleanups(BaseInit
);
1714 if (BaseInit
.isInvalid())
1718 new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
,
1719 SemaRef
.Context
.getTrivialTypeSourceInfo(BaseSpec
->getType(),
1721 BaseSpec
->isVirtual(),
1723 BaseInit
.takeAs
<Expr
>(),
1731 BuildImplicitMemberInitializer(Sema
&SemaRef
, CXXConstructorDecl
*Constructor
,
1732 ImplicitInitializerKind ImplicitInitKind
,
1734 CXXCtorInitializer
*&CXXMemberInit
) {
1735 if (Field
->isInvalidDecl())
1738 SourceLocation Loc
= Constructor
->getLocation();
1740 if (ImplicitInitKind
== IIK_Copy
) {
1741 ParmVarDecl
*Param
= Constructor
->getParamDecl(0);
1742 QualType ParamType
= Param
->getType().getNonReferenceType();
1744 Expr
*MemberExprBase
=
1745 DeclRefExpr::Create(SemaRef
.Context
, 0, SourceRange(), Param
,
1746 Loc
, ParamType
, VK_LValue
, 0);
1748 // Build a reference to this field within the parameter.
1750 LookupResult
MemberLookup(SemaRef
, Field
->getDeclName(), Loc
,
1751 Sema::LookupMemberName
);
1752 MemberLookup
.addDecl(Field
, AS_public
);
1753 MemberLookup
.resolveKind();
1754 ExprResult CopyCtorArg
1755 = SemaRef
.BuildMemberReferenceExpr(MemberExprBase
,
1759 /*FirstQualifierInScope=*/0,
1761 /*TemplateArgs=*/0);
1762 if (CopyCtorArg
.isInvalid())
1765 // When the field we are copying is an array, create index variables for
1766 // each dimension of the array. We use these index variables to subscript
1767 // the source array, and other clients (e.g., CodeGen) will perform the
1768 // necessary iteration with these index variables.
1769 llvm::SmallVector
<VarDecl
*, 4> IndexVariables
;
1770 QualType BaseType
= Field
->getType();
1771 QualType SizeType
= SemaRef
.Context
.getSizeType();
1772 while (const ConstantArrayType
*Array
1773 = SemaRef
.Context
.getAsConstantArrayType(BaseType
)) {
1774 // Create the iteration variable for this array index.
1775 IdentifierInfo
*IterationVarName
= 0;
1777 llvm::SmallString
<8> Str
;
1778 llvm::raw_svector_ostream
OS(Str
);
1779 OS
<< "__i" << IndexVariables
.size();
1780 IterationVarName
= &SemaRef
.Context
.Idents
.get(OS
.str());
1782 VarDecl
*IterationVar
1783 = VarDecl::Create(SemaRef
.Context
, SemaRef
.CurContext
, Loc
,
1784 IterationVarName
, SizeType
,
1785 SemaRef
.Context
.getTrivialTypeSourceInfo(SizeType
, Loc
),
1787 IndexVariables
.push_back(IterationVar
);
1789 // Create a reference to the iteration variable.
1790 ExprResult IterationVarRef
1791 = SemaRef
.BuildDeclRefExpr(IterationVar
, SizeType
, VK_RValue
, Loc
);
1792 assert(!IterationVarRef
.isInvalid() &&
1793 "Reference to invented variable cannot fail!");
1795 // Subscript the array with this iteration variable.
1796 CopyCtorArg
= SemaRef
.CreateBuiltinArraySubscriptExpr(CopyCtorArg
.take(),
1798 IterationVarRef
.take(),
1800 if (CopyCtorArg
.isInvalid())
1803 BaseType
= Array
->getElementType();
1806 // Construct the entity that we will be initializing. For an array, this
1807 // will be first element in the array, which may require several levels
1808 // of array-subscript entities.
1809 llvm::SmallVector
<InitializedEntity
, 4> Entities
;
1810 Entities
.reserve(1 + IndexVariables
.size());
1811 Entities
.push_back(InitializedEntity::InitializeMember(Field
));
1812 for (unsigned I
= 0, N
= IndexVariables
.size(); I
!= N
; ++I
)
1813 Entities
.push_back(InitializedEntity::InitializeElement(SemaRef
.Context
,
1817 // Direct-initialize to use the copy constructor.
1818 InitializationKind InitKind
=
1819 InitializationKind::CreateDirect(Loc
, SourceLocation(), SourceLocation());
1821 Expr
*CopyCtorArgE
= CopyCtorArg
.takeAs
<Expr
>();
1822 InitializationSequence
InitSeq(SemaRef
, Entities
.back(), InitKind
,
1825 ExprResult MemberInit
1826 = InitSeq
.Perform(SemaRef
, Entities
.back(), InitKind
,
1827 MultiExprArg(&CopyCtorArgE
, 1));
1828 MemberInit
= SemaRef
.MaybeCreateExprWithCleanups(MemberInit
);
1829 if (MemberInit
.isInvalid())
1833 = CXXCtorInitializer::Create(SemaRef
.Context
, Field
, Loc
, Loc
,
1834 MemberInit
.takeAs
<Expr
>(), Loc
,
1835 IndexVariables
.data(),
1836 IndexVariables
.size());
1840 assert(ImplicitInitKind
== IIK_Default
&& "Unhandled implicit init kind!");
1842 QualType FieldBaseElementType
=
1843 SemaRef
.Context
.getBaseElementType(Field
->getType());
1845 if (FieldBaseElementType
->isRecordType()) {
1846 InitializedEntity InitEntity
= InitializedEntity::InitializeMember(Field
);
1847 InitializationKind InitKind
=
1848 InitializationKind::CreateDefault(Loc
);
1850 InitializationSequence
InitSeq(SemaRef
, InitEntity
, InitKind
, 0, 0);
1851 ExprResult MemberInit
=
1852 InitSeq
.Perform(SemaRef
, InitEntity
, InitKind
, MultiExprArg());
1854 MemberInit
= SemaRef
.MaybeCreateExprWithCleanups(MemberInit
);
1855 if (MemberInit
.isInvalid())
1859 new (SemaRef
.Context
) CXXCtorInitializer(SemaRef
.Context
,
1866 if (FieldBaseElementType
->isReferenceType()) {
1867 SemaRef
.Diag(Constructor
->getLocation(),
1868 diag::err_uninitialized_member_in_ctor
)
1869 << (int)Constructor
->isImplicit()
1870 << SemaRef
.Context
.getTagDeclType(Constructor
->getParent())
1871 << 0 << Field
->getDeclName();
1872 SemaRef
.Diag(Field
->getLocation(), diag::note_declared_at
);
1876 if (FieldBaseElementType
.isConstQualified()) {
1877 SemaRef
.Diag(Constructor
->getLocation(),
1878 diag::err_uninitialized_member_in_ctor
)
1879 << (int)Constructor
->isImplicit()
1880 << SemaRef
.Context
.getTagDeclType(Constructor
->getParent())
1881 << 1 << Field
->getDeclName();
1882 SemaRef
.Diag(Field
->getLocation(), diag::note_declared_at
);
1886 // Nothing to initialize.
1892 struct BaseAndFieldInfo
{
1894 CXXConstructorDecl
*Ctor
;
1895 bool AnyErrorsInInits
;
1896 ImplicitInitializerKind IIK
;
1897 llvm::DenseMap
<const void *, CXXCtorInitializer
*> AllBaseFields
;
1898 llvm::SmallVector
<CXXCtorInitializer
*, 8> AllToInit
;
1900 BaseAndFieldInfo(Sema
&S
, CXXConstructorDecl
*Ctor
, bool ErrorsInInits
)
1901 : S(S
), Ctor(Ctor
), AnyErrorsInInits(ErrorsInInits
) {
1902 // FIXME: Handle implicit move constructors.
1903 if (Ctor
->isImplicit() && Ctor
->isCopyConstructor())
1911 static bool CollectFieldInitializer(BaseAndFieldInfo
&Info
,
1912 FieldDecl
*Top
, FieldDecl
*Field
) {
1914 // Overwhelmingly common case: we have a direct initializer for this field.
1915 if (CXXCtorInitializer
*Init
= Info
.AllBaseFields
.lookup(Field
)) {
1916 Info
.AllToInit
.push_back(Init
);
1920 if (Info
.IIK
== IIK_Default
&& Field
->isAnonymousStructOrUnion()) {
1921 const RecordType
*FieldClassType
= Field
->getType()->getAs
<RecordType
>();
1922 assert(FieldClassType
&& "anonymous struct/union without record type");
1923 CXXRecordDecl
*FieldClassDecl
1924 = cast
<CXXRecordDecl
>(FieldClassType
->getDecl());
1926 // Even though union members never have non-trivial default
1927 // constructions in C++03, we still build member initializers for aggregate
1928 // record types which can be union members, and C++0x allows non-trivial
1929 // default constructors for union members, so we ensure that only one
1930 // member is initialized for these.
1931 if (FieldClassDecl
->isUnion()) {
1932 // First check for an explicit initializer for one field.
1933 for (RecordDecl::field_iterator FA
= FieldClassDecl
->field_begin(),
1934 EA
= FieldClassDecl
->field_end(); FA
!= EA
; FA
++) {
1935 if (CXXCtorInitializer
*Init
= Info
.AllBaseFields
.lookup(*FA
)) {
1936 Info
.AllToInit
.push_back(Init
);
1938 // Once we've initialized a field of an anonymous union, the union
1939 // field in the class is also initialized, so exit immediately.
1941 } else if ((*FA
)->isAnonymousStructOrUnion()) {
1942 if (CollectFieldInitializer(Info
, Top
, *FA
))
1947 // Fallthrough and construct a default initializer for the union as
1948 // a whole, which can call its default constructor if such a thing exists
1949 // (C++0x perhaps). FIXME: It's not clear that this is the correct
1950 // behavior going forward with C++0x, when anonymous unions there are
1951 // finalized, we should revisit this.
1953 // For structs, we simply descend through to initialize all members where
1955 for (RecordDecl::field_iterator FA
= FieldClassDecl
->field_begin(),
1956 EA
= FieldClassDecl
->field_end(); FA
!= EA
; FA
++) {
1957 if (CollectFieldInitializer(Info
, Top
, *FA
))
1963 // Don't try to build an implicit initializer if there were semantic
1964 // errors in any of the initializers (and therefore we might be
1965 // missing some that the user actually wrote).
1966 if (Info
.AnyErrorsInInits
)
1969 CXXCtorInitializer
*Init
= 0;
1970 if (BuildImplicitMemberInitializer(Info
.S
, Info
.Ctor
, Info
.IIK
, Field
, Init
))
1974 Info
.AllToInit
.push_back(Init
);
1980 Sema::SetCtorInitializers(CXXConstructorDecl
*Constructor
,
1981 CXXCtorInitializer
**Initializers
,
1982 unsigned NumInitializers
,
1984 if (Constructor
->getDeclContext()->isDependentContext()) {
1985 // Just store the initializers as written, they will be checked during
1987 if (NumInitializers
> 0) {
1988 Constructor
->setNumCtorInitializers(NumInitializers
);
1989 CXXCtorInitializer
**baseOrMemberInitializers
=
1990 new (Context
) CXXCtorInitializer
*[NumInitializers
];
1991 memcpy(baseOrMemberInitializers
, Initializers
,
1992 NumInitializers
* sizeof(CXXCtorInitializer
*));
1993 Constructor
->setCtorInitializers(baseOrMemberInitializers
);
1999 BaseAndFieldInfo
Info(*this, Constructor
, AnyErrors
);
2001 // We need to build the initializer AST according to order of construction
2002 // and not what user specified in the Initializers list.
2003 CXXRecordDecl
*ClassDecl
= Constructor
->getParent()->getDefinition();
2007 bool HadError
= false;
2009 for (unsigned i
= 0; i
< NumInitializers
; i
++) {
2010 CXXCtorInitializer
*Member
= Initializers
[i
];
2012 if (Member
->isBaseInitializer())
2013 Info
.AllBaseFields
[Member
->getBaseClass()->getAs
<RecordType
>()] = Member
;
2015 Info
.AllBaseFields
[Member
->getAnyMember()] = Member
;
2018 // Keep track of the direct virtual bases.
2019 llvm::SmallPtrSet
<CXXBaseSpecifier
*, 16> DirectVBases
;
2020 for (CXXRecordDecl::base_class_iterator I
= ClassDecl
->bases_begin(),
2021 E
= ClassDecl
->bases_end(); I
!= E
; ++I
) {
2023 DirectVBases
.insert(I
);
2026 // Push virtual bases before others.
2027 for (CXXRecordDecl::base_class_iterator VBase
= ClassDecl
->vbases_begin(),
2028 E
= ClassDecl
->vbases_end(); VBase
!= E
; ++VBase
) {
2030 if (CXXCtorInitializer
*Value
2031 = Info
.AllBaseFields
.lookup(VBase
->getType()->getAs
<RecordType
>())) {
2032 Info
.AllToInit
.push_back(Value
);
2033 } else if (!AnyErrors
) {
2034 bool IsInheritedVirtualBase
= !DirectVBases
.count(VBase
);
2035 CXXCtorInitializer
*CXXBaseInit
;
2036 if (BuildImplicitBaseInitializer(*this, Constructor
, Info
.IIK
,
2037 VBase
, IsInheritedVirtualBase
,
2043 Info
.AllToInit
.push_back(CXXBaseInit
);
2047 // Non-virtual bases.
2048 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
2049 E
= ClassDecl
->bases_end(); Base
!= E
; ++Base
) {
2050 // Virtuals are in the virtual base list and already constructed.
2051 if (Base
->isVirtual())
2054 if (CXXCtorInitializer
*Value
2055 = Info
.AllBaseFields
.lookup(Base
->getType()->getAs
<RecordType
>())) {
2056 Info
.AllToInit
.push_back(Value
);
2057 } else if (!AnyErrors
) {
2058 CXXCtorInitializer
*CXXBaseInit
;
2059 if (BuildImplicitBaseInitializer(*this, Constructor
, Info
.IIK
,
2060 Base
, /*IsInheritedVirtualBase=*/false,
2066 Info
.AllToInit
.push_back(CXXBaseInit
);
2071 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
2072 E
= ClassDecl
->field_end(); Field
!= E
; ++Field
) {
2073 if ((*Field
)->getType()->isIncompleteArrayType()) {
2074 assert(ClassDecl
->hasFlexibleArrayMember() &&
2075 "Incomplete array type is not valid");
2078 if (CollectFieldInitializer(Info
, *Field
, *Field
))
2082 NumInitializers
= Info
.AllToInit
.size();
2083 if (NumInitializers
> 0) {
2084 Constructor
->setNumCtorInitializers(NumInitializers
);
2085 CXXCtorInitializer
**baseOrMemberInitializers
=
2086 new (Context
) CXXCtorInitializer
*[NumInitializers
];
2087 memcpy(baseOrMemberInitializers
, Info
.AllToInit
.data(),
2088 NumInitializers
* sizeof(CXXCtorInitializer
*));
2089 Constructor
->setCtorInitializers(baseOrMemberInitializers
);
2091 // Constructors implicitly reference the base and member
2093 MarkBaseAndMemberDestructorsReferenced(Constructor
->getLocation(),
2094 Constructor
->getParent());
2100 static void *GetKeyForTopLevelField(FieldDecl
*Field
) {
2101 // For anonymous unions, use the class declaration as the key.
2102 if (const RecordType
*RT
= Field
->getType()->getAs
<RecordType
>()) {
2103 if (RT
->getDecl()->isAnonymousStructOrUnion())
2104 return static_cast<void *>(RT
->getDecl());
2106 return static_cast<void *>(Field
);
2109 static void *GetKeyForBase(ASTContext
&Context
, QualType BaseType
) {
2110 return const_cast<Type
*>(Context
.getCanonicalType(BaseType
).getTypePtr());
2113 static void *GetKeyForMember(ASTContext
&Context
,
2114 CXXCtorInitializer
*Member
) {
2115 if (!Member
->isAnyMemberInitializer())
2116 return GetKeyForBase(Context
, QualType(Member
->getBaseClass(), 0));
2118 // For fields injected into the class via declaration of an anonymous union,
2119 // use its anonymous union class declaration as the unique key.
2120 FieldDecl
*Field
= Member
->getAnyMember();
2122 // If the field is a member of an anonymous struct or union, our key
2123 // is the anonymous record decl that's a direct child of the class.
2124 RecordDecl
*RD
= Field
->getParent();
2125 if (RD
->isAnonymousStructOrUnion()) {
2127 RecordDecl
*Parent
= cast
<RecordDecl
>(RD
->getDeclContext());
2128 if (Parent
->isAnonymousStructOrUnion())
2134 return static_cast<void *>(RD
);
2137 return static_cast<void *>(Field
);
2141 DiagnoseBaseOrMemInitializerOrder(Sema
&SemaRef
,
2142 const CXXConstructorDecl
*Constructor
,
2143 CXXCtorInitializer
**Inits
,
2144 unsigned NumInits
) {
2145 if (Constructor
->getDeclContext()->isDependentContext())
2148 // Don't check initializers order unless the warning is enabled at the
2149 // location of at least one initializer.
2150 bool ShouldCheckOrder
= false;
2151 for (unsigned InitIndex
= 0; InitIndex
!= NumInits
; ++InitIndex
) {
2152 CXXCtorInitializer
*Init
= Inits
[InitIndex
];
2153 if (SemaRef
.Diags
.getDiagnosticLevel(diag::warn_initializer_out_of_order
,
2154 Init
->getSourceLocation())
2155 != Diagnostic::Ignored
) {
2156 ShouldCheckOrder
= true;
2160 if (!ShouldCheckOrder
)
2163 // Build the list of bases and members in the order that they'll
2164 // actually be initialized. The explicit initializers should be in
2165 // this same order but may be missing things.
2166 llvm::SmallVector
<const void*, 32> IdealInitKeys
;
2168 const CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
2170 // 1. Virtual bases.
2171 for (CXXRecordDecl::base_class_const_iterator VBase
=
2172 ClassDecl
->vbases_begin(),
2173 E
= ClassDecl
->vbases_end(); VBase
!= E
; ++VBase
)
2174 IdealInitKeys
.push_back(GetKeyForBase(SemaRef
.Context
, VBase
->getType()));
2176 // 2. Non-virtual bases.
2177 for (CXXRecordDecl::base_class_const_iterator Base
= ClassDecl
->bases_begin(),
2178 E
= ClassDecl
->bases_end(); Base
!= E
; ++Base
) {
2179 if (Base
->isVirtual())
2181 IdealInitKeys
.push_back(GetKeyForBase(SemaRef
.Context
, Base
->getType()));
2184 // 3. Direct fields.
2185 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
2186 E
= ClassDecl
->field_end(); Field
!= E
; ++Field
)
2187 IdealInitKeys
.push_back(GetKeyForTopLevelField(*Field
));
2189 unsigned NumIdealInits
= IdealInitKeys
.size();
2190 unsigned IdealIndex
= 0;
2192 CXXCtorInitializer
*PrevInit
= 0;
2193 for (unsigned InitIndex
= 0; InitIndex
!= NumInits
; ++InitIndex
) {
2194 CXXCtorInitializer
*Init
= Inits
[InitIndex
];
2195 void *InitKey
= GetKeyForMember(SemaRef
.Context
, Init
);
2197 // Scan forward to try to find this initializer in the idealized
2198 // initializers list.
2199 for (; IdealIndex
!= NumIdealInits
; ++IdealIndex
)
2200 if (InitKey
== IdealInitKeys
[IdealIndex
])
2203 // If we didn't find this initializer, it must be because we
2204 // scanned past it on a previous iteration. That can only
2205 // happen if we're out of order; emit a warning.
2206 if (IdealIndex
== NumIdealInits
&& PrevInit
) {
2207 Sema::SemaDiagnosticBuilder D
=
2208 SemaRef
.Diag(PrevInit
->getSourceLocation(),
2209 diag::warn_initializer_out_of_order
);
2211 if (PrevInit
->isAnyMemberInitializer())
2212 D
<< 0 << PrevInit
->getAnyMember()->getDeclName();
2214 D
<< 1 << PrevInit
->getBaseClassInfo()->getType();
2216 if (Init
->isAnyMemberInitializer())
2217 D
<< 0 << Init
->getAnyMember()->getDeclName();
2219 D
<< 1 << Init
->getBaseClassInfo()->getType();
2221 // Move back to the initializer's location in the ideal list.
2222 for (IdealIndex
= 0; IdealIndex
!= NumIdealInits
; ++IdealIndex
)
2223 if (InitKey
== IdealInitKeys
[IdealIndex
])
2226 assert(IdealIndex
!= NumIdealInits
&&
2227 "initializer not found in initializer list");
2235 bool CheckRedundantInit(Sema
&S
,
2236 CXXCtorInitializer
*Init
,
2237 CXXCtorInitializer
*&PrevInit
) {
2243 if (FieldDecl
*Field
= Init
->getMember())
2244 S
.Diag(Init
->getSourceLocation(),
2245 diag::err_multiple_mem_initialization
)
2246 << Field
->getDeclName()
2247 << Init
->getSourceRange();
2249 const Type
*BaseClass
= Init
->getBaseClass();
2250 assert(BaseClass
&& "neither field nor base");
2251 S
.Diag(Init
->getSourceLocation(),
2252 diag::err_multiple_base_initialization
)
2253 << QualType(BaseClass
, 0)
2254 << Init
->getSourceRange();
2256 S
.Diag(PrevInit
->getSourceLocation(), diag::note_previous_initializer
)
2257 << 0 << PrevInit
->getSourceRange();
2262 typedef std::pair
<NamedDecl
*, CXXCtorInitializer
*> UnionEntry
;
2263 typedef llvm::DenseMap
<RecordDecl
*, UnionEntry
> RedundantUnionMap
;
2265 bool CheckRedundantUnionInit(Sema
&S
,
2266 CXXCtorInitializer
*Init
,
2267 RedundantUnionMap
&Unions
) {
2268 FieldDecl
*Field
= Init
->getAnyMember();
2269 RecordDecl
*Parent
= Field
->getParent();
2270 if (!Parent
->isAnonymousStructOrUnion())
2273 NamedDecl
*Child
= Field
;
2275 if (Parent
->isUnion()) {
2276 UnionEntry
&En
= Unions
[Parent
];
2277 if (En
.first
&& En
.first
!= Child
) {
2278 S
.Diag(Init
->getSourceLocation(),
2279 diag::err_multiple_mem_union_initialization
)
2280 << Field
->getDeclName()
2281 << Init
->getSourceRange();
2282 S
.Diag(En
.second
->getSourceLocation(), diag::note_previous_initializer
)
2283 << 0 << En
.second
->getSourceRange();
2285 } else if (!En
.first
) {
2292 Parent
= cast
<RecordDecl
>(Parent
->getDeclContext());
2293 } while (Parent
->isAnonymousStructOrUnion());
2299 /// ActOnMemInitializers - Handle the member initializers for a constructor.
2300 void Sema::ActOnMemInitializers(Decl
*ConstructorDecl
,
2301 SourceLocation ColonLoc
,
2302 MemInitTy
**meminits
, unsigned NumMemInits
,
2304 if (!ConstructorDecl
)
2307 AdjustDeclIfTemplate(ConstructorDecl
);
2309 CXXConstructorDecl
*Constructor
2310 = dyn_cast
<CXXConstructorDecl
>(ConstructorDecl
);
2313 Diag(ColonLoc
, diag::err_only_constructors_take_base_inits
);
2317 CXXCtorInitializer
**MemInits
=
2318 reinterpret_cast<CXXCtorInitializer
**>(meminits
);
2320 // Mapping for the duplicate initializers check.
2321 // For member initializers, this is keyed with a FieldDecl*.
2322 // For base initializers, this is keyed with a Type*.
2323 llvm::DenseMap
<void*, CXXCtorInitializer
*> Members
;
2325 // Mapping for the inconsistent anonymous-union initializers check.
2326 RedundantUnionMap MemberUnions
;
2328 bool HadError
= false;
2329 for (unsigned i
= 0; i
< NumMemInits
; i
++) {
2330 CXXCtorInitializer
*Init
= MemInits
[i
];
2332 // Set the source order index.
2333 Init
->setSourceOrder(i
);
2335 if (Init
->isAnyMemberInitializer()) {
2336 FieldDecl
*Field
= Init
->getAnyMember();
2337 if (CheckRedundantInit(*this, Init
, Members
[Field
]) ||
2338 CheckRedundantUnionInit(*this, Init
, MemberUnions
))
2341 void *Key
= GetKeyForBase(Context
, QualType(Init
->getBaseClass(), 0));
2342 if (CheckRedundantInit(*this, Init
, Members
[Key
]))
2350 DiagnoseBaseOrMemInitializerOrder(*this, Constructor
, MemInits
, NumMemInits
);
2352 SetCtorInitializers(Constructor
, MemInits
, NumMemInits
, AnyErrors
);
2356 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location
,
2357 CXXRecordDecl
*ClassDecl
) {
2358 // Ignore dependent contexts.
2359 if (ClassDecl
->isDependentContext())
2362 // FIXME: all the access-control diagnostics are positioned on the
2363 // field/base declaration. That's probably good; that said, the
2364 // user might reasonably want to know why the destructor is being
2365 // emitted, and we currently don't say.
2367 // Non-static data members.
2368 for (CXXRecordDecl::field_iterator I
= ClassDecl
->field_begin(),
2369 E
= ClassDecl
->field_end(); I
!= E
; ++I
) {
2370 FieldDecl
*Field
= *I
;
2371 if (Field
->isInvalidDecl())
2373 QualType FieldType
= Context
.getBaseElementType(Field
->getType());
2375 const RecordType
* RT
= FieldType
->getAs
<RecordType
>();
2379 CXXRecordDecl
*FieldClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
2380 if (FieldClassDecl
->hasTrivialDestructor())
2383 CXXDestructorDecl
*Dtor
= LookupDestructor(FieldClassDecl
);
2384 CheckDestructorAccess(Field
->getLocation(), Dtor
,
2385 PDiag(diag::err_access_dtor_field
)
2386 << Field
->getDeclName()
2389 MarkDeclarationReferenced(Location
, const_cast<CXXDestructorDecl
*>(Dtor
));
2392 llvm::SmallPtrSet
<const RecordType
*, 8> DirectVirtualBases
;
2395 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
2396 E
= ClassDecl
->bases_end(); Base
!= E
; ++Base
) {
2397 // Bases are always records in a well-formed non-dependent class.
2398 const RecordType
*RT
= Base
->getType()->getAs
<RecordType
>();
2400 // Remember direct virtual bases.
2401 if (Base
->isVirtual())
2402 DirectVirtualBases
.insert(RT
);
2404 // Ignore trivial destructors.
2405 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
2406 if (BaseClassDecl
->hasTrivialDestructor())
2409 CXXDestructorDecl
*Dtor
= LookupDestructor(BaseClassDecl
);
2411 // FIXME: caret should be on the start of the class name
2412 CheckDestructorAccess(Base
->getSourceRange().getBegin(), Dtor
,
2413 PDiag(diag::err_access_dtor_base
)
2415 << Base
->getSourceRange());
2417 MarkDeclarationReferenced(Location
, const_cast<CXXDestructorDecl
*>(Dtor
));
2421 for (CXXRecordDecl::base_class_iterator VBase
= ClassDecl
->vbases_begin(),
2422 E
= ClassDecl
->vbases_end(); VBase
!= E
; ++VBase
) {
2424 // Bases are always records in a well-formed non-dependent class.
2425 const RecordType
*RT
= VBase
->getType()->getAs
<RecordType
>();
2427 // Ignore direct virtual bases.
2428 if (DirectVirtualBases
.count(RT
))
2431 // Ignore trivial destructors.
2432 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(RT
->getDecl());
2433 if (BaseClassDecl
->hasTrivialDestructor())
2436 CXXDestructorDecl
*Dtor
= LookupDestructor(BaseClassDecl
);
2437 CheckDestructorAccess(ClassDecl
->getLocation(), Dtor
,
2438 PDiag(diag::err_access_dtor_vbase
)
2439 << VBase
->getType());
2441 MarkDeclarationReferenced(Location
, const_cast<CXXDestructorDecl
*>(Dtor
));
2445 void Sema::ActOnDefaultCtorInitializers(Decl
*CDtorDecl
) {
2449 if (CXXConstructorDecl
*Constructor
2450 = dyn_cast
<CXXConstructorDecl
>(CDtorDecl
))
2451 SetCtorInitializers(Constructor
, 0, 0, /*AnyErrors=*/false);
2454 bool Sema::RequireNonAbstractType(SourceLocation Loc
, QualType T
,
2455 unsigned DiagID
, AbstractDiagSelID SelID
) {
2457 return RequireNonAbstractType(Loc
, T
, PDiag(DiagID
));
2459 return RequireNonAbstractType(Loc
, T
, PDiag(DiagID
) << SelID
);
2462 bool Sema::RequireNonAbstractType(SourceLocation Loc
, QualType T
,
2463 const PartialDiagnostic
&PD
) {
2464 if (!getLangOptions().CPlusPlus
)
2467 if (const ArrayType
*AT
= Context
.getAsArrayType(T
))
2468 return RequireNonAbstractType(Loc
, AT
->getElementType(), PD
);
2470 if (const PointerType
*PT
= T
->getAs
<PointerType
>()) {
2471 // Find the innermost pointer type.
2472 while (const PointerType
*T
= PT
->getPointeeType()->getAs
<PointerType
>())
2475 if (const ArrayType
*AT
= Context
.getAsArrayType(PT
->getPointeeType()))
2476 return RequireNonAbstractType(Loc
, AT
->getElementType(), PD
);
2479 const RecordType
*RT
= T
->getAs
<RecordType
>();
2483 const CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RT
->getDecl());
2485 // We can't answer whether something is abstract until it has a
2486 // definition. If it's currently being defined, we'll walk back
2487 // over all the declarations when we have a full definition.
2488 const CXXRecordDecl
*Def
= RD
->getDefinition();
2489 if (!Def
|| Def
->isBeingDefined())
2492 if (!RD
->isAbstract())
2495 Diag(Loc
, PD
) << RD
->getDeclName();
2496 DiagnoseAbstractType(RD
);
2501 void Sema::DiagnoseAbstractType(const CXXRecordDecl
*RD
) {
2502 // Check if we've already emitted the list of pure virtual functions
2504 if (PureVirtualClassDiagSet
&& PureVirtualClassDiagSet
->count(RD
))
2507 CXXFinalOverriderMap FinalOverriders
;
2508 RD
->getFinalOverriders(FinalOverriders
);
2510 // Keep a set of seen pure methods so we won't diagnose the same method
2512 llvm::SmallPtrSet
<const CXXMethodDecl
*, 8> SeenPureMethods
;
2514 for (CXXFinalOverriderMap::iterator M
= FinalOverriders
.begin(),
2515 MEnd
= FinalOverriders
.end();
2518 for (OverridingMethods::iterator SO
= M
->second
.begin(),
2519 SOEnd
= M
->second
.end();
2520 SO
!= SOEnd
; ++SO
) {
2521 // C++ [class.abstract]p4:
2522 // A class is abstract if it contains or inherits at least one
2523 // pure virtual function for which the final overrider is pure
2527 if (SO
->second
.size() != 1)
2530 if (!SO
->second
.front().Method
->isPure())
2533 if (!SeenPureMethods
.insert(SO
->second
.front().Method
))
2536 Diag(SO
->second
.front().Method
->getLocation(),
2537 diag::note_pure_virtual_function
)
2538 << SO
->second
.front().Method
->getDeclName();
2542 if (!PureVirtualClassDiagSet
)
2543 PureVirtualClassDiagSet
.reset(new RecordDeclSetTy
);
2544 PureVirtualClassDiagSet
->insert(RD
);
2548 struct AbstractUsageInfo
{
2550 CXXRecordDecl
*Record
;
2551 CanQualType AbstractType
;
2554 AbstractUsageInfo(Sema
&S
, CXXRecordDecl
*Record
)
2555 : S(S
), Record(Record
),
2556 AbstractType(S
.Context
.getCanonicalType(
2557 S
.Context
.getTypeDeclType(Record
))),
2560 void DiagnoseAbstractType() {
2561 if (Invalid
) return;
2562 S
.DiagnoseAbstractType(Record
);
2566 void CheckType(const NamedDecl
*D
, TypeLoc TL
, Sema::AbstractDiagSelID Sel
);
2569 struct CheckAbstractUsage
{
2570 AbstractUsageInfo
&Info
;
2571 const NamedDecl
*Ctx
;
2573 CheckAbstractUsage(AbstractUsageInfo
&Info
, const NamedDecl
*Ctx
)
2574 : Info(Info
), Ctx(Ctx
) {}
2576 void Visit(TypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
2577 switch (TL
.getTypeLocClass()) {
2578 #define ABSTRACT_TYPELOC(CLASS, PARENT)
2579 #define TYPELOC(CLASS, PARENT) \
2580 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2581 #include "clang/AST/TypeLocNodes.def"
2585 void Check(FunctionProtoTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
2586 Visit(TL
.getResultLoc(), Sema::AbstractReturnType
);
2587 for (unsigned I
= 0, E
= TL
.getNumArgs(); I
!= E
; ++I
) {
2588 TypeSourceInfo
*TSI
= TL
.getArg(I
)->getTypeSourceInfo();
2589 if (TSI
) Visit(TSI
->getTypeLoc(), Sema::AbstractParamType
);
2593 void Check(ArrayTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
2594 Visit(TL
.getElementLoc(), Sema::AbstractArrayType
);
2597 void Check(TemplateSpecializationTypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
2598 // Visit the type parameters from a permissive context.
2599 for (unsigned I
= 0, E
= TL
.getNumArgs(); I
!= E
; ++I
) {
2600 TemplateArgumentLoc TAL
= TL
.getArgLoc(I
);
2601 if (TAL
.getArgument().getKind() == TemplateArgument::Type
)
2602 if (TypeSourceInfo
*TSI
= TAL
.getTypeSourceInfo())
2603 Visit(TSI
->getTypeLoc(), Sema::AbstractNone
);
2604 // TODO: other template argument types?
2608 // Visit pointee types from a permissive context.
2609 #define CheckPolymorphic(Type) \
2610 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2611 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2613 CheckPolymorphic(PointerTypeLoc
)
2614 CheckPolymorphic(ReferenceTypeLoc
)
2615 CheckPolymorphic(MemberPointerTypeLoc
)
2616 CheckPolymorphic(BlockPointerTypeLoc
)
2618 /// Handle all the types we haven't given a more specific
2619 /// implementation for above.
2620 void Check(TypeLoc TL
, Sema::AbstractDiagSelID Sel
) {
2621 // Every other kind of type that we haven't called out already
2622 // that has an inner type is either (1) sugar or (2) contains that
2623 // inner type in some way as a subobject.
2624 if (TypeLoc Next
= TL
.getNextTypeLoc())
2625 return Visit(Next
, Sel
);
2627 // If there's no inner type and we're in a permissive context,
2629 if (Sel
== Sema::AbstractNone
) return;
2631 // Check whether the type matches the abstract type.
2632 QualType T
= TL
.getType();
2633 if (T
->isArrayType()) {
2634 Sel
= Sema::AbstractArrayType
;
2635 T
= Info
.S
.Context
.getBaseElementType(T
);
2637 CanQualType CT
= T
->getCanonicalTypeUnqualified().getUnqualifiedType();
2638 if (CT
!= Info
.AbstractType
) return;
2640 // It matched; do some magic.
2641 if (Sel
== Sema::AbstractArrayType
) {
2642 Info
.S
.Diag(Ctx
->getLocation(), diag::err_array_of_abstract_type
)
2643 << T
<< TL
.getSourceRange();
2645 Info
.S
.Diag(Ctx
->getLocation(), diag::err_abstract_type_in_decl
)
2646 << Sel
<< T
<< TL
.getSourceRange();
2648 Info
.DiagnoseAbstractType();
2652 void AbstractUsageInfo::CheckType(const NamedDecl
*D
, TypeLoc TL
,
2653 Sema::AbstractDiagSelID Sel
) {
2654 CheckAbstractUsage(*this, D
).Visit(TL
, Sel
);
2659 /// Check for invalid uses of an abstract type in a method declaration.
2660 static void CheckAbstractClassUsage(AbstractUsageInfo
&Info
,
2661 CXXMethodDecl
*MD
) {
2662 // No need to do the check on definitions, which require that
2663 // the return/param types be complete.
2664 if (MD
->isThisDeclarationADefinition())
2667 // For safety's sake, just ignore it if we don't have type source
2668 // information. This should never happen for non-implicit methods,
2670 if (TypeSourceInfo
*TSI
= MD
->getTypeSourceInfo())
2671 Info
.CheckType(MD
, TSI
->getTypeLoc(), Sema::AbstractNone
);
2674 /// Check for invalid uses of an abstract type within a class definition.
2675 static void CheckAbstractClassUsage(AbstractUsageInfo
&Info
,
2676 CXXRecordDecl
*RD
) {
2677 for (CXXRecordDecl::decl_iterator
2678 I
= RD
->decls_begin(), E
= RD
->decls_end(); I
!= E
; ++I
) {
2680 if (D
->isImplicit()) continue;
2682 // Methods and method templates.
2683 if (isa
<CXXMethodDecl
>(D
)) {
2684 CheckAbstractClassUsage(Info
, cast
<CXXMethodDecl
>(D
));
2685 } else if (isa
<FunctionTemplateDecl
>(D
)) {
2686 FunctionDecl
*FD
= cast
<FunctionTemplateDecl
>(D
)->getTemplatedDecl();
2687 CheckAbstractClassUsage(Info
, cast
<CXXMethodDecl
>(FD
));
2689 // Fields and static variables.
2690 } else if (isa
<FieldDecl
>(D
)) {
2691 FieldDecl
*FD
= cast
<FieldDecl
>(D
);
2692 if (TypeSourceInfo
*TSI
= FD
->getTypeSourceInfo())
2693 Info
.CheckType(FD
, TSI
->getTypeLoc(), Sema::AbstractFieldType
);
2694 } else if (isa
<VarDecl
>(D
)) {
2695 VarDecl
*VD
= cast
<VarDecl
>(D
);
2696 if (TypeSourceInfo
*TSI
= VD
->getTypeSourceInfo())
2697 Info
.CheckType(VD
, TSI
->getTypeLoc(), Sema::AbstractVariableType
);
2699 // Nested classes and class templates.
2700 } else if (isa
<CXXRecordDecl
>(D
)) {
2701 CheckAbstractClassUsage(Info
, cast
<CXXRecordDecl
>(D
));
2702 } else if (isa
<ClassTemplateDecl
>(D
)) {
2703 CheckAbstractClassUsage(Info
,
2704 cast
<ClassTemplateDecl
>(D
)->getTemplatedDecl());
2709 /// \brief Perform semantic checks on a class definition that has been
2710 /// completing, introducing implicitly-declared members, checking for
2711 /// abstract types, etc.
2712 void Sema::CheckCompletedCXXClass(CXXRecordDecl
*Record
) {
2716 if (Record
->isAbstract() && !Record
->isInvalidDecl()) {
2717 AbstractUsageInfo
Info(*this, Record
);
2718 CheckAbstractClassUsage(Info
, Record
);
2721 // If this is not an aggregate type and has no user-declared constructor,
2722 // complain about any non-static data members of reference or const scalar
2723 // type, since they will never get initializers.
2724 if (!Record
->isInvalidDecl() && !Record
->isDependentType() &&
2725 !Record
->isAggregate() && !Record
->hasUserDeclaredConstructor()) {
2726 bool Complained
= false;
2727 for (RecordDecl::field_iterator F
= Record
->field_begin(),
2728 FEnd
= Record
->field_end();
2730 if (F
->getType()->isReferenceType() ||
2731 (F
->getType().isConstQualified() && F
->getType()->isScalarType())) {
2733 Diag(Record
->getLocation(), diag::warn_no_constructor_for_refconst
)
2734 << Record
->getTagKind() << Record
;
2738 Diag(F
->getLocation(), diag::note_refconst_member_not_initialized
)
2739 << F
->getType()->isReferenceType()
2740 << F
->getDeclName();
2745 if (Record
->isDynamicClass() && !Record
->isDependentType())
2746 DynamicClasses
.push_back(Record
);
2748 if (Record
->getIdentifier()) {
2749 // C++ [class.mem]p13:
2750 // If T is the name of a class, then each of the following shall have a
2751 // name different from T:
2752 // - every member of every anonymous union that is a member of class T.
2754 // C++ [class.mem]p14:
2755 // In addition, if class T has a user-declared constructor (12.1), every
2756 // non-static data member of class T shall have a name different from T.
2757 for (DeclContext::lookup_result R
= Record
->lookup(Record
->getDeclName());
2758 R
.first
!= R
.second
; ++R
.first
) {
2759 NamedDecl
*D
= *R
.first
;
2760 if ((isa
<FieldDecl
>(D
) && Record
->hasUserDeclaredConstructor()) ||
2761 isa
<IndirectFieldDecl
>(D
)) {
2762 Diag(D
->getLocation(), diag::err_member_name_of_class
)
2763 << D
->getDeclName();
2769 // Warn if the class has virtual methods but non-virtual public destructor.
2770 if (Record
->isDynamicClass() && !Record
->isDependentType()) {
2771 CXXDestructorDecl
*dtor
= Record
->getDestructor();
2772 if (!dtor
|| (!dtor
->isVirtual() && dtor
->getAccess() == AS_public
))
2773 Diag(dtor
? dtor
->getLocation() : Record
->getLocation(),
2774 diag::warn_non_virtual_dtor
) << Context
.getRecordType(Record
);
2777 // See if a method overloads virtual methods in a base
2778 /// class without overriding any.
2779 if (!Record
->isDependentType()) {
2780 for (CXXRecordDecl::method_iterator M
= Record
->method_begin(),
2781 MEnd
= Record
->method_end();
2783 DiagnoseHiddenVirtualMethods(Record
, *M
);
2787 // Declare inherited constructors. We do this eagerly here because:
2788 // - The standard requires an eager diagnostic for conflicting inherited
2789 // constructors from different classes.
2790 // - The lazy declaration of the other implicit constructors is so as to not
2791 // waste space and performance on classes that are not meant to be
2792 // instantiated (e.g. meta-functions). This doesn't apply to classes that
2793 // have inherited constructors.
2794 DeclareInheritedConstructors(Record
);
2797 /// \brief Data used with FindHiddenVirtualMethod
2798 struct FindHiddenVirtualMethodData
{
2800 CXXMethodDecl
*Method
;
2801 llvm::SmallPtrSet
<const CXXMethodDecl
*, 8> OverridenAndUsingBaseMethods
;
2802 llvm::SmallVector
<CXXMethodDecl
*, 8> OverloadedMethods
;
2805 /// \brief Member lookup function that determines whether a given C++
2806 /// method overloads virtual methods in a base class without overriding any,
2807 /// to be used with CXXRecordDecl::lookupInBases().
2808 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier
*Specifier
,
2811 RecordDecl
*BaseRecord
= Specifier
->getType()->getAs
<RecordType
>()->getDecl();
2813 FindHiddenVirtualMethodData
&Data
2814 = *static_cast<FindHiddenVirtualMethodData
*>(UserData
);
2816 DeclarationName Name
= Data
.Method
->getDeclName();
2817 assert(Name
.getNameKind() == DeclarationName::Identifier
);
2819 bool foundSameNameMethod
= false;
2820 llvm::SmallVector
<CXXMethodDecl
*, 8> overloadedMethods
;
2821 for (Path
.Decls
= BaseRecord
->lookup(Name
);
2822 Path
.Decls
.first
!= Path
.Decls
.second
;
2823 ++Path
.Decls
.first
) {
2824 NamedDecl
*D
= *Path
.Decls
.first
;
2825 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(D
)) {
2826 MD
= MD
->getCanonicalDecl();
2827 foundSameNameMethod
= true;
2828 // Interested only in hidden virtual methods.
2829 if (!MD
->isVirtual())
2831 // If the method we are checking overrides a method from its base
2832 // don't warn about the other overloaded methods.
2833 if (!Data
.S
->IsOverload(Data
.Method
, MD
, false))
2835 // Collect the overload only if its hidden.
2836 if (!Data
.OverridenAndUsingBaseMethods
.count(MD
))
2837 overloadedMethods
.push_back(MD
);
2841 if (foundSameNameMethod
)
2842 Data
.OverloadedMethods
.append(overloadedMethods
.begin(),
2843 overloadedMethods
.end());
2844 return foundSameNameMethod
;
2847 /// \brief See if a method overloads virtual methods in a base class without
2849 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl
*DC
, CXXMethodDecl
*MD
) {
2850 if (Diags
.getDiagnosticLevel(diag::warn_overloaded_virtual
,
2851 MD
->getLocation()) == Diagnostic::Ignored
)
2853 if (MD
->getDeclName().getNameKind() != DeclarationName::Identifier
)
2856 CXXBasePaths
Paths(/*FindAmbiguities=*/true, // true to look in all bases.
2857 /*bool RecordPaths=*/false,
2858 /*bool DetectVirtual=*/false);
2859 FindHiddenVirtualMethodData Data
;
2863 // Keep the base methods that were overriden or introduced in the subclass
2864 // by 'using' in a set. A base method not in this set is hidden.
2865 for (DeclContext::lookup_result res
= DC
->lookup(MD
->getDeclName());
2866 res
.first
!= res
.second
; ++res
.first
) {
2867 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(*res
.first
))
2868 for (CXXMethodDecl::method_iterator I
= MD
->begin_overridden_methods(),
2869 E
= MD
->end_overridden_methods();
2871 Data
.OverridenAndUsingBaseMethods
.insert((*I
)->getCanonicalDecl());
2872 if (UsingShadowDecl
*shad
= dyn_cast
<UsingShadowDecl
>(*res
.first
))
2873 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(shad
->getTargetDecl()))
2874 Data
.OverridenAndUsingBaseMethods
.insert(MD
->getCanonicalDecl());
2877 if (DC
->lookupInBases(&FindHiddenVirtualMethod
, &Data
, Paths
) &&
2878 !Data
.OverloadedMethods
.empty()) {
2879 Diag(MD
->getLocation(), diag::warn_overloaded_virtual
)
2880 << MD
<< (Data
.OverloadedMethods
.size() > 1);
2882 for (unsigned i
= 0, e
= Data
.OverloadedMethods
.size(); i
!= e
; ++i
) {
2883 CXXMethodDecl
*overloadedMD
= Data
.OverloadedMethods
[i
];
2884 Diag(overloadedMD
->getLocation(),
2885 diag::note_hidden_overloaded_virtual_declared_here
) << overloadedMD
;
2890 void Sema::ActOnFinishCXXMemberSpecification(Scope
* S
, SourceLocation RLoc
,
2892 SourceLocation LBrac
,
2893 SourceLocation RBrac
,
2894 AttributeList
*AttrList
) {
2898 AdjustDeclIfTemplate(TagDecl
);
2900 ActOnFields(S
, RLoc
, TagDecl
,
2901 // strict aliasing violation!
2902 reinterpret_cast<Decl
**>(FieldCollector
->getCurFields()),
2903 FieldCollector
->getCurNumFields(), LBrac
, RBrac
, AttrList
);
2905 CheckCompletedCXXClass(
2906 dyn_cast_or_null
<CXXRecordDecl
>(TagDecl
));
2910 /// \brief Helper class that collects exception specifications for
2911 /// implicitly-declared special member functions.
2912 class ImplicitExceptionSpecification
{
2913 ASTContext
&Context
;
2914 bool AllowsAllExceptions
;
2915 llvm::SmallPtrSet
<CanQualType
, 4> ExceptionsSeen
;
2916 llvm::SmallVector
<QualType
, 4> Exceptions
;
2919 explicit ImplicitExceptionSpecification(ASTContext
&Context
)
2920 : Context(Context
), AllowsAllExceptions(false) { }
2922 /// \brief Whether the special member function should have any
2923 /// exception specification at all.
2924 bool hasExceptionSpecification() const {
2925 return !AllowsAllExceptions
;
2928 /// \brief Whether the special member function should have a
2929 /// throw(...) exception specification (a Microsoft extension).
2930 bool hasAnyExceptionSpecification() const {
2934 /// \brief The number of exceptions in the exception specification.
2935 unsigned size() const { return Exceptions
.size(); }
2937 /// \brief The set of exceptions in the exception specification.
2938 const QualType
*data() const { return Exceptions
.data(); }
2940 /// \brief Note that
2941 void CalledDecl(CXXMethodDecl
*Method
) {
2942 // If we already know that we allow all exceptions, do nothing.
2943 if (AllowsAllExceptions
|| !Method
)
2946 const FunctionProtoType
*Proto
2947 = Method
->getType()->getAs
<FunctionProtoType
>();
2949 // If this function can throw any exceptions, make a note of that.
2950 if (!Proto
->hasExceptionSpec() || Proto
->hasAnyExceptionSpec()) {
2951 AllowsAllExceptions
= true;
2952 ExceptionsSeen
.clear();
2957 // Record the exceptions in this function's exception specification.
2958 for (FunctionProtoType::exception_iterator E
= Proto
->exception_begin(),
2959 EEnd
= Proto
->exception_end();
2961 if (ExceptionsSeen
.insert(Context
.getCanonicalType(*E
)))
2962 Exceptions
.push_back(*E
);
2968 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
2969 /// special functions, such as the default constructor, copy
2970 /// constructor, or destructor, to the given C++ class (C++
2971 /// [special]p1). This routine can only be executed just before the
2972 /// definition of the class is complete.
2973 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl
*ClassDecl
) {
2974 if (!ClassDecl
->hasUserDeclaredConstructor())
2975 ++ASTContext::NumImplicitDefaultConstructors
;
2977 if (!ClassDecl
->hasUserDeclaredCopyConstructor())
2978 ++ASTContext::NumImplicitCopyConstructors
;
2980 if (!ClassDecl
->hasUserDeclaredCopyAssignment()) {
2981 ++ASTContext::NumImplicitCopyAssignmentOperators
;
2983 // If we have a dynamic class, then the copy assignment operator may be
2984 // virtual, so we have to declare it immediately. This ensures that, e.g.,
2985 // it shows up in the right place in the vtable and that we diagnose
2986 // problems with the implicit exception specification.
2987 if (ClassDecl
->isDynamicClass())
2988 DeclareImplicitCopyAssignment(ClassDecl
);
2991 if (!ClassDecl
->hasUserDeclaredDestructor()) {
2992 ++ASTContext::NumImplicitDestructors
;
2994 // If we have a dynamic class, then the destructor may be virtual, so we
2995 // have to declare the destructor immediately. This ensures that, e.g., it
2996 // shows up in the right place in the vtable and that we diagnose problems
2997 // with the implicit exception specification.
2998 if (ClassDecl
->isDynamicClass())
2999 DeclareImplicitDestructor(ClassDecl
);
3003 void Sema::ActOnReenterTemplateScope(Scope
*S
, Decl
*D
) {
3007 TemplateParameterList
*Params
= 0;
3008 if (TemplateDecl
*Template
= dyn_cast
<TemplateDecl
>(D
))
3009 Params
= Template
->getTemplateParameters();
3010 else if (ClassTemplatePartialSpecializationDecl
*PartialSpec
3011 = dyn_cast
<ClassTemplatePartialSpecializationDecl
>(D
))
3012 Params
= PartialSpec
->getTemplateParameters();
3016 for (TemplateParameterList::iterator Param
= Params
->begin(),
3017 ParamEnd
= Params
->end();
3018 Param
!= ParamEnd
; ++Param
) {
3019 NamedDecl
*Named
= cast
<NamedDecl
>(*Param
);
3020 if (Named
->getDeclName()) {
3022 IdResolver
.AddDecl(Named
);
3027 void Sema::ActOnStartDelayedMemberDeclarations(Scope
*S
, Decl
*RecordD
) {
3028 if (!RecordD
) return;
3029 AdjustDeclIfTemplate(RecordD
);
3030 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(RecordD
);
3031 PushDeclContext(S
, Record
);
3034 void Sema::ActOnFinishDelayedMemberDeclarations(Scope
*S
, Decl
*RecordD
) {
3035 if (!RecordD
) return;
3039 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
3040 /// parsing a top-level (non-nested) C++ class, and we are now
3041 /// parsing those parts of the given Method declaration that could
3042 /// not be parsed earlier (C++ [class.mem]p2), such as default
3043 /// arguments. This action should enter the scope of the given
3044 /// Method declaration as if we had just parsed the qualified method
3045 /// name. However, it should not bring the parameters into scope;
3046 /// that will be performed by ActOnDelayedCXXMethodParameter.
3047 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope
*S
, Decl
*MethodD
) {
3050 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
3051 /// C++ method declaration. We're (re-)introducing the given
3052 /// function parameter into scope for use in parsing later parts of
3053 /// the method declaration. For example, we could see an
3054 /// ActOnParamDefaultArgument event for this parameter.
3055 void Sema::ActOnDelayedCXXMethodParameter(Scope
*S
, Decl
*ParamD
) {
3059 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(ParamD
);
3061 // If this parameter has an unparsed default argument, clear it out
3062 // to make way for the parsed default argument.
3063 if (Param
->hasUnparsedDefaultArg())
3064 Param
->setDefaultArg(0);
3067 if (Param
->getDeclName())
3068 IdResolver
.AddDecl(Param
);
3071 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
3072 /// processing the delayed method declaration for Method. The method
3073 /// declaration is now considered finished. There may be a separate
3074 /// ActOnStartOfFunctionDef action later (not necessarily
3075 /// immediately!) for this method, if it was also defined inside the
3077 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope
*S
, Decl
*MethodD
) {
3081 AdjustDeclIfTemplate(MethodD
);
3083 FunctionDecl
*Method
= cast
<FunctionDecl
>(MethodD
);
3085 // Now that we have our default arguments, check the constructor
3086 // again. It could produce additional diagnostics or affect whether
3087 // the class has implicitly-declared destructors, among other
3089 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Method
))
3090 CheckConstructor(Constructor
);
3092 // Check the default arguments, which we may have added.
3093 if (!Method
->isInvalidDecl())
3094 CheckCXXDefaultArguments(Method
);
3097 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
3098 /// the well-formedness of the constructor declarator @p D with type @p
3099 /// R. If there are any errors in the declarator, this routine will
3100 /// emit diagnostics and set the invalid bit to true. In any case, the type
3101 /// will be updated to reflect a well-formed type for the constructor and
3103 QualType
Sema::CheckConstructorDeclarator(Declarator
&D
, QualType R
,
3105 bool isVirtual
= D
.getDeclSpec().isVirtualSpecified();
3107 // C++ [class.ctor]p3:
3108 // A constructor shall not be virtual (10.3) or static (9.4). A
3109 // constructor can be invoked for a const, volatile or const
3110 // volatile object. A constructor shall not be declared const,
3111 // volatile, or const volatile (9.3.2).
3113 if (!D
.isInvalidType())
3114 Diag(D
.getIdentifierLoc(), diag::err_constructor_cannot_be
)
3115 << "virtual" << SourceRange(D
.getDeclSpec().getVirtualSpecLoc())
3116 << SourceRange(D
.getIdentifierLoc());
3119 if (SC
== SC_Static
) {
3120 if (!D
.isInvalidType())
3121 Diag(D
.getIdentifierLoc(), diag::err_constructor_cannot_be
)
3122 << "static" << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
3123 << SourceRange(D
.getIdentifierLoc());
3128 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
3129 if (FTI
.TypeQuals
!= 0) {
3130 if (FTI
.TypeQuals
& Qualifiers::Const
)
3131 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_constructor
)
3132 << "const" << SourceRange(D
.getIdentifierLoc());
3133 if (FTI
.TypeQuals
& Qualifiers::Volatile
)
3134 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_constructor
)
3135 << "volatile" << SourceRange(D
.getIdentifierLoc());
3136 if (FTI
.TypeQuals
& Qualifiers::Restrict
)
3137 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_constructor
)
3138 << "restrict" << SourceRange(D
.getIdentifierLoc());
3142 // C++0x [class.ctor]p4:
3143 // A constructor shall not be declared with a ref-qualifier.
3144 if (FTI
.hasRefQualifier()) {
3145 Diag(FTI
.getRefQualifierLoc(), diag::err_ref_qualifier_constructor
)
3146 << FTI
.RefQualifierIsLValueRef
3147 << FixItHint::CreateRemoval(FTI
.getRefQualifierLoc());
3151 // Rebuild the function type "R" without any type qualifiers (in
3152 // case any of the errors above fired) and with "void" as the
3153 // return type, since constructors don't have return types.
3154 const FunctionProtoType
*Proto
= R
->getAs
<FunctionProtoType
>();
3155 if (Proto
->getResultType() == Context
.VoidTy
&& !D
.isInvalidType())
3158 FunctionProtoType::ExtProtoInfo EPI
= Proto
->getExtProtoInfo();
3160 EPI
.RefQualifier
= RQ_None
;
3162 return Context
.getFunctionType(Context
.VoidTy
, Proto
->arg_type_begin(),
3163 Proto
->getNumArgs(), EPI
);
3166 /// CheckConstructor - Checks a fully-formed constructor for
3167 /// well-formedness, issuing any diagnostics required. Returns true if
3168 /// the constructor declarator is invalid.
3169 void Sema::CheckConstructor(CXXConstructorDecl
*Constructor
) {
3170 CXXRecordDecl
*ClassDecl
3171 = dyn_cast
<CXXRecordDecl
>(Constructor
->getDeclContext());
3173 return Constructor
->setInvalidDecl();
3175 // C++ [class.copy]p3:
3176 // A declaration of a constructor for a class X is ill-formed if
3177 // its first parameter is of type (optionally cv-qualified) X and
3178 // either there are no other parameters or else all other
3179 // parameters have default arguments.
3180 if (!Constructor
->isInvalidDecl() &&
3181 ((Constructor
->getNumParams() == 1) ||
3182 (Constructor
->getNumParams() > 1 &&
3183 Constructor
->getParamDecl(1)->hasDefaultArg())) &&
3184 Constructor
->getTemplateSpecializationKind()
3185 != TSK_ImplicitInstantiation
) {
3186 QualType ParamType
= Constructor
->getParamDecl(0)->getType();
3187 QualType ClassTy
= Context
.getTagDeclType(ClassDecl
);
3188 if (Context
.getCanonicalType(ParamType
).getUnqualifiedType() == ClassTy
) {
3189 SourceLocation ParamLoc
= Constructor
->getParamDecl(0)->getLocation();
3190 const char *ConstRef
3191 = Constructor
->getParamDecl(0)->getIdentifier() ? "const &"
3193 Diag(ParamLoc
, diag::err_constructor_byvalue_arg
)
3194 << FixItHint::CreateInsertion(ParamLoc
, ConstRef
);
3196 // FIXME: Rather that making the constructor invalid, we should endeavor
3198 Constructor
->setInvalidDecl();
3203 /// CheckDestructor - Checks a fully-formed destructor definition for
3204 /// well-formedness, issuing any diagnostics required. Returns true
3206 bool Sema::CheckDestructor(CXXDestructorDecl
*Destructor
) {
3207 CXXRecordDecl
*RD
= Destructor
->getParent();
3209 if (Destructor
->isVirtual()) {
3212 if (!Destructor
->isImplicit())
3213 Loc
= Destructor
->getLocation();
3215 Loc
= RD
->getLocation();
3217 // If we have a virtual destructor, look up the deallocation function
3218 FunctionDecl
*OperatorDelete
= 0;
3219 DeclarationName Name
=
3220 Context
.DeclarationNames
.getCXXOperatorName(OO_Delete
);
3221 if (FindDeallocationFunction(Loc
, RD
, Name
, OperatorDelete
))
3224 MarkDeclarationReferenced(Loc
, OperatorDelete
);
3226 Destructor
->setOperatorDelete(OperatorDelete
);
3233 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo
&FTI
) {
3234 return (FTI
.NumArgs
== 1 && !FTI
.isVariadic
&& FTI
.ArgInfo
[0].Ident
== 0 &&
3235 FTI
.ArgInfo
[0].Param
&&
3236 cast
<ParmVarDecl
>(FTI
.ArgInfo
[0].Param
)->getType()->isVoidType());
3239 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
3240 /// the well-formednes of the destructor declarator @p D with type @p
3241 /// R. If there are any errors in the declarator, this routine will
3242 /// emit diagnostics and set the declarator to invalid. Even if this happens,
3243 /// will be updated to reflect a well-formed type for the destructor and
3245 QualType
Sema::CheckDestructorDeclarator(Declarator
&D
, QualType R
,
3247 // C++ [class.dtor]p1:
3248 // [...] A typedef-name that names a class is a class-name
3249 // (7.1.3); however, a typedef-name that names a class shall not
3250 // be used as the identifier in the declarator for a destructor
3252 QualType DeclaratorType
= GetTypeFromParser(D
.getName().DestructorName
);
3253 if (isa
<TypedefType
>(DeclaratorType
))
3254 Diag(D
.getIdentifierLoc(), diag::err_destructor_typedef_name
)
3257 // C++ [class.dtor]p2:
3258 // A destructor is used to destroy objects of its class type. A
3259 // destructor takes no parameters, and no return type can be
3260 // specified for it (not even void). The address of a destructor
3261 // shall not be taken. A destructor shall not be static. A
3262 // destructor can be invoked for a const, volatile or const
3263 // volatile object. A destructor shall not be declared const,
3264 // volatile or const volatile (9.3.2).
3265 if (SC
== SC_Static
) {
3266 if (!D
.isInvalidType())
3267 Diag(D
.getIdentifierLoc(), diag::err_destructor_cannot_be
)
3268 << "static" << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
3269 << SourceRange(D
.getIdentifierLoc())
3270 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
3274 if (D
.getDeclSpec().hasTypeSpecifier() && !D
.isInvalidType()) {
3275 // Destructors don't have return types, but the parser will
3276 // happily parse something like:
3282 // The return type will be eliminated later.
3283 Diag(D
.getIdentifierLoc(), diag::err_destructor_return_type
)
3284 << SourceRange(D
.getDeclSpec().getTypeSpecTypeLoc())
3285 << SourceRange(D
.getIdentifierLoc());
3288 DeclaratorChunk::FunctionTypeInfo
&FTI
= D
.getFunctionTypeInfo();
3289 if (FTI
.TypeQuals
!= 0 && !D
.isInvalidType()) {
3290 if (FTI
.TypeQuals
& Qualifiers::Const
)
3291 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_destructor
)
3292 << "const" << SourceRange(D
.getIdentifierLoc());
3293 if (FTI
.TypeQuals
& Qualifiers::Volatile
)
3294 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_destructor
)
3295 << "volatile" << SourceRange(D
.getIdentifierLoc());
3296 if (FTI
.TypeQuals
& Qualifiers::Restrict
)
3297 Diag(D
.getIdentifierLoc(), diag::err_invalid_qualified_destructor
)
3298 << "restrict" << SourceRange(D
.getIdentifierLoc());
3302 // C++0x [class.dtor]p2:
3303 // A destructor shall not be declared with a ref-qualifier.
3304 if (FTI
.hasRefQualifier()) {
3305 Diag(FTI
.getRefQualifierLoc(), diag::err_ref_qualifier_destructor
)
3306 << FTI
.RefQualifierIsLValueRef
3307 << FixItHint::CreateRemoval(FTI
.getRefQualifierLoc());
3311 // Make sure we don't have any parameters.
3312 if (FTI
.NumArgs
> 0 && !FTIHasSingleVoidArgument(FTI
)) {
3313 Diag(D
.getIdentifierLoc(), diag::err_destructor_with_params
);
3315 // Delete the parameters.
3320 // Make sure the destructor isn't variadic.
3321 if (FTI
.isVariadic
) {
3322 Diag(D
.getIdentifierLoc(), diag::err_destructor_variadic
);
3326 // Rebuild the function type "R" without any type qualifiers or
3327 // parameters (in case any of the errors above fired) and with
3328 // "void" as the return type, since destructors don't have return
3330 if (!D
.isInvalidType())
3333 const FunctionProtoType
*Proto
= R
->getAs
<FunctionProtoType
>();
3334 FunctionProtoType::ExtProtoInfo EPI
= Proto
->getExtProtoInfo();
3335 EPI
.Variadic
= false;
3337 EPI
.RefQualifier
= RQ_None
;
3338 return Context
.getFunctionType(Context
.VoidTy
, 0, 0, EPI
);
3341 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
3342 /// well-formednes of the conversion function declarator @p D with
3343 /// type @p R. If there are any errors in the declarator, this routine
3344 /// will emit diagnostics and return true. Otherwise, it will return
3345 /// false. Either way, the type @p R will be updated to reflect a
3346 /// well-formed type for the conversion operator.
3347 void Sema::CheckConversionDeclarator(Declarator
&D
, QualType
&R
,
3349 // C++ [class.conv.fct]p1:
3350 // Neither parameter types nor return type can be specified. The
3351 // type of a conversion function (8.3.5) is "function taking no
3352 // parameter returning conversion-type-id."
3353 if (SC
== SC_Static
) {
3354 if (!D
.isInvalidType())
3355 Diag(D
.getIdentifierLoc(), diag::err_conv_function_not_member
)
3356 << "static" << SourceRange(D
.getDeclSpec().getStorageClassSpecLoc())
3357 << SourceRange(D
.getIdentifierLoc());
3362 QualType ConvType
= GetTypeFromParser(D
.getName().ConversionFunctionId
);
3364 if (D
.getDeclSpec().hasTypeSpecifier() && !D
.isInvalidType()) {
3365 // Conversion functions don't have return types, but the parser will
3366 // happily parse something like:
3369 // float operator bool();
3372 // The return type will be changed later anyway.
3373 Diag(D
.getIdentifierLoc(), diag::err_conv_function_return_type
)
3374 << SourceRange(D
.getDeclSpec().getTypeSpecTypeLoc())
3375 << SourceRange(D
.getIdentifierLoc());
3379 const FunctionProtoType
*Proto
= R
->getAs
<FunctionProtoType
>();
3381 // Make sure we don't have any parameters.
3382 if (Proto
->getNumArgs() > 0) {
3383 Diag(D
.getIdentifierLoc(), diag::err_conv_function_with_params
);
3385 // Delete the parameters.
3386 D
.getFunctionTypeInfo().freeArgs();
3388 } else if (Proto
->isVariadic()) {
3389 Diag(D
.getIdentifierLoc(), diag::err_conv_function_variadic
);
3393 // Diagnose "&operator bool()" and other such nonsense. This
3394 // is actually a gcc extension which we don't support.
3395 if (Proto
->getResultType() != ConvType
) {
3396 Diag(D
.getIdentifierLoc(), diag::err_conv_function_with_complex_decl
)
3397 << Proto
->getResultType();
3399 ConvType
= Proto
->getResultType();
3402 // C++ [class.conv.fct]p4:
3403 // The conversion-type-id shall not represent a function type nor
3405 if (ConvType
->isArrayType()) {
3406 Diag(D
.getIdentifierLoc(), diag::err_conv_function_to_array
);
3407 ConvType
= Context
.getPointerType(ConvType
);
3409 } else if (ConvType
->isFunctionType()) {
3410 Diag(D
.getIdentifierLoc(), diag::err_conv_function_to_function
);
3411 ConvType
= Context
.getPointerType(ConvType
);
3415 // Rebuild the function type "R" without any parameters (in case any
3416 // of the errors above fired) and with the conversion type as the
3418 if (D
.isInvalidType())
3419 R
= Context
.getFunctionType(ConvType
, 0, 0, Proto
->getExtProtoInfo());
3421 // C++0x explicit conversion operators.
3422 if (D
.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x
)
3423 Diag(D
.getDeclSpec().getExplicitSpecLoc(),
3424 diag::warn_explicit_conversion_functions
)
3425 << SourceRange(D
.getDeclSpec().getExplicitSpecLoc());
3428 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
3429 /// the declaration of the given C++ conversion function. This routine
3430 /// is responsible for recording the conversion function in the C++
3431 /// class, if possible.
3432 Decl
*Sema::ActOnConversionDeclarator(CXXConversionDecl
*Conversion
) {
3433 assert(Conversion
&& "Expected to receive a conversion function declaration");
3435 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(Conversion
->getDeclContext());
3437 // Make sure we aren't redeclaring the conversion function.
3438 QualType ConvType
= Context
.getCanonicalType(Conversion
->getConversionType());
3440 // C++ [class.conv.fct]p1:
3441 // [...] A conversion function is never used to convert a
3442 // (possibly cv-qualified) object to the (possibly cv-qualified)
3443 // same object type (or a reference to it), to a (possibly
3444 // cv-qualified) base class of that type (or a reference to it),
3445 // or to (possibly cv-qualified) void.
3446 // FIXME: Suppress this warning if the conversion function ends up being a
3447 // virtual function that overrides a virtual function in a base class.
3449 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
3450 if (const ReferenceType
*ConvTypeRef
= ConvType
->getAs
<ReferenceType
>())
3451 ConvType
= ConvTypeRef
->getPointeeType();
3452 if (Conversion
->getTemplateSpecializationKind() != TSK_Undeclared
&&
3453 Conversion
->getTemplateSpecializationKind() != TSK_ExplicitSpecialization
)
3454 /* Suppress diagnostics for instantiations. */;
3455 else if (ConvType
->isRecordType()) {
3456 ConvType
= Context
.getCanonicalType(ConvType
).getUnqualifiedType();
3457 if (ConvType
== ClassType
)
3458 Diag(Conversion
->getLocation(), diag::warn_conv_to_self_not_used
)
3460 else if (IsDerivedFrom(ClassType
, ConvType
))
3461 Diag(Conversion
->getLocation(), diag::warn_conv_to_base_not_used
)
3462 << ClassType
<< ConvType
;
3463 } else if (ConvType
->isVoidType()) {
3464 Diag(Conversion
->getLocation(), diag::warn_conv_to_void_not_used
)
3465 << ClassType
<< ConvType
;
3468 if (FunctionTemplateDecl
*ConversionTemplate
3469 = Conversion
->getDescribedFunctionTemplate())
3470 return ConversionTemplate
;
3475 //===----------------------------------------------------------------------===//
3476 // Namespace Handling
3477 //===----------------------------------------------------------------------===//
3481 /// ActOnStartNamespaceDef - This is called at the start of a namespace
3483 Decl
*Sema::ActOnStartNamespaceDef(Scope
*NamespcScope
,
3484 SourceLocation InlineLoc
,
3485 SourceLocation IdentLoc
,
3487 SourceLocation LBrace
,
3488 AttributeList
*AttrList
) {
3489 // anonymous namespace starts at its left brace
3490 NamespaceDecl
*Namespc
= NamespaceDecl::Create(Context
, CurContext
,
3491 (II
? IdentLoc
: LBrace
) , II
);
3492 Namespc
->setLBracLoc(LBrace
);
3493 Namespc
->setInline(InlineLoc
.isValid());
3495 Scope
*DeclRegionScope
= NamespcScope
->getParent();
3497 ProcessDeclAttributeList(DeclRegionScope
, Namespc
, AttrList
);
3499 if (const VisibilityAttr
*Attr
= Namespc
->getAttr
<VisibilityAttr
>())
3500 PushNamespaceVisibilityAttr(Attr
);
3503 // C++ [namespace.def]p2:
3504 // The identifier in an original-namespace-definition shall not
3505 // have been previously defined in the declarative region in
3506 // which the original-namespace-definition appears. The
3507 // identifier in an original-namespace-definition is the name of
3508 // the namespace. Subsequently in that declarative region, it is
3509 // treated as an original-namespace-name.
3511 // Since namespace names are unique in their scope, and we don't
3512 // look through using directives, just
3513 DeclContext::lookup_result R
= CurContext
->getRedeclContext()->lookup(II
);
3514 NamedDecl
*PrevDecl
= R
.first
== R
.second
? 0 : *R
.first
;
3516 if (NamespaceDecl
*OrigNS
= dyn_cast_or_null
<NamespaceDecl
>(PrevDecl
)) {
3517 // This is an extended namespace definition.
3518 if (Namespc
->isInline() != OrigNS
->isInline()) {
3519 // inline-ness must match
3520 Diag(Namespc
->getLocation(), diag::err_inline_namespace_mismatch
)
3521 << Namespc
->isInline();
3522 Diag(OrigNS
->getLocation(), diag::note_previous_definition
);
3523 Namespc
->setInvalidDecl();
3524 // Recover by ignoring the new namespace's inline status.
3525 Namespc
->setInline(OrigNS
->isInline());
3528 // Attach this namespace decl to the chain of extended namespace
3530 OrigNS
->setNextNamespace(Namespc
);
3531 Namespc
->setOriginalNamespace(OrigNS
->getOriginalNamespace());
3533 // Remove the previous declaration from the scope.
3534 if (DeclRegionScope
->isDeclScope(OrigNS
)) {
3535 IdResolver
.RemoveDecl(OrigNS
);
3536 DeclRegionScope
->RemoveDecl(OrigNS
);
3538 } else if (PrevDecl
) {
3539 // This is an invalid name redefinition.
3540 Diag(Namespc
->getLocation(), diag::err_redefinition_different_kind
)
3541 << Namespc
->getDeclName();
3542 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
3543 Namespc
->setInvalidDecl();
3544 // Continue on to push Namespc as current DeclContext and return it.
3545 } else if (II
->isStr("std") &&
3546 CurContext
->getRedeclContext()->isTranslationUnit()) {
3547 // This is the first "real" definition of the namespace "std", so update
3548 // our cache of the "std" namespace to point at this definition.
3549 if (NamespaceDecl
*StdNS
= getStdNamespace()) {
3550 // We had already defined a dummy namespace "std". Link this new
3551 // namespace definition to the dummy namespace "std".
3552 StdNS
->setNextNamespace(Namespc
);
3553 StdNS
->setLocation(IdentLoc
);
3554 Namespc
->setOriginalNamespace(StdNS
->getOriginalNamespace());
3557 // Make our StdNamespace cache point at the first real definition of the
3559 StdNamespace
= Namespc
;
3562 PushOnScopeChains(Namespc
, DeclRegionScope
);
3564 // Anonymous namespaces.
3565 assert(Namespc
->isAnonymousNamespace());
3567 // Link the anonymous namespace into its parent.
3568 NamespaceDecl
*PrevDecl
;
3569 DeclContext
*Parent
= CurContext
->getRedeclContext();
3570 if (TranslationUnitDecl
*TU
= dyn_cast
<TranslationUnitDecl
>(Parent
)) {
3571 PrevDecl
= TU
->getAnonymousNamespace();
3572 TU
->setAnonymousNamespace(Namespc
);
3574 NamespaceDecl
*ND
= cast
<NamespaceDecl
>(Parent
);
3575 PrevDecl
= ND
->getAnonymousNamespace();
3576 ND
->setAnonymousNamespace(Namespc
);
3579 // Link the anonymous namespace with its previous declaration.
3581 assert(PrevDecl
->isAnonymousNamespace());
3582 assert(!PrevDecl
->getNextNamespace());
3583 Namespc
->setOriginalNamespace(PrevDecl
->getOriginalNamespace());
3584 PrevDecl
->setNextNamespace(Namespc
);
3586 if (Namespc
->isInline() != PrevDecl
->isInline()) {
3587 // inline-ness must match
3588 Diag(Namespc
->getLocation(), diag::err_inline_namespace_mismatch
)
3589 << Namespc
->isInline();
3590 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
3591 Namespc
->setInvalidDecl();
3592 // Recover by ignoring the new namespace's inline status.
3593 Namespc
->setInline(PrevDecl
->isInline());
3597 CurContext
->addDecl(Namespc
);
3599 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
3600 // behaves as if it were replaced by
3601 // namespace unique { /* empty body */ }
3602 // using namespace unique;
3603 // namespace unique { namespace-body }
3604 // where all occurrences of 'unique' in a translation unit are
3605 // replaced by the same identifier and this identifier differs
3606 // from all other identifiers in the entire program.
3608 // We just create the namespace with an empty name and then add an
3609 // implicit using declaration, just like the standard suggests.
3611 // CodeGen enforces the "universally unique" aspect by giving all
3612 // declarations semantically contained within an anonymous
3613 // namespace internal linkage.
3616 UsingDirectiveDecl
* UD
3617 = UsingDirectiveDecl::Create(Context
, CurContext
,
3618 /* 'using' */ LBrace
,
3619 /* 'namespace' */ SourceLocation(),
3620 /* qualifier */ SourceRange(),
3622 /* identifier */ SourceLocation(),
3624 /* Ancestor */ CurContext
);
3626 CurContext
->addDecl(UD
);
3630 // Although we could have an invalid decl (i.e. the namespace name is a
3631 // redefinition), push it as current DeclContext and try to continue parsing.
3632 // FIXME: We should be able to push Namespc here, so that the each DeclContext
3633 // for the namespace has the declarations that showed up in that particular
3634 // namespace definition.
3635 PushDeclContext(NamespcScope
, Namespc
);
3639 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
3640 /// is a namespace alias, returns the namespace it points to.
3641 static inline NamespaceDecl
*getNamespaceDecl(NamedDecl
*D
) {
3642 if (NamespaceAliasDecl
*AD
= dyn_cast_or_null
<NamespaceAliasDecl
>(D
))
3643 return AD
->getNamespace();
3644 return dyn_cast_or_null
<NamespaceDecl
>(D
);
3647 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
3648 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
3649 void Sema::ActOnFinishNamespaceDef(Decl
*Dcl
, SourceLocation RBrace
) {
3650 NamespaceDecl
*Namespc
= dyn_cast_or_null
<NamespaceDecl
>(Dcl
);
3651 assert(Namespc
&& "Invalid parameter, expected NamespaceDecl");
3652 Namespc
->setRBracLoc(RBrace
);
3654 if (Namespc
->hasAttr
<VisibilityAttr
>())
3655 PopPragmaVisibility();
3658 CXXRecordDecl
*Sema::getStdBadAlloc() const {
3659 return cast_or_null
<CXXRecordDecl
>(
3660 StdBadAlloc
.get(Context
.getExternalSource()));
3663 NamespaceDecl
*Sema::getStdNamespace() const {
3664 return cast_or_null
<NamespaceDecl
>(
3665 StdNamespace
.get(Context
.getExternalSource()));
3668 /// \brief Retrieve the special "std" namespace, which may require us to
3669 /// implicitly define the namespace.
3670 NamespaceDecl
*Sema::getOrCreateStdNamespace() {
3671 if (!StdNamespace
) {
3672 // The "std" namespace has not yet been defined, so build one implicitly.
3673 StdNamespace
= NamespaceDecl::Create(Context
,
3674 Context
.getTranslationUnitDecl(),
3676 &PP
.getIdentifierTable().get("std"));
3677 getStdNamespace()->setImplicit(true);
3680 return getStdNamespace();
3683 Decl
*Sema::ActOnUsingDirective(Scope
*S
,
3684 SourceLocation UsingLoc
,
3685 SourceLocation NamespcLoc
,
3687 SourceLocation IdentLoc
,
3688 IdentifierInfo
*NamespcName
,
3689 AttributeList
*AttrList
) {
3690 assert(!SS
.isInvalid() && "Invalid CXXScopeSpec.");
3691 assert(NamespcName
&& "Invalid NamespcName.");
3692 assert(IdentLoc
.isValid() && "Invalid NamespceName location.");
3694 // This can only happen along a recovery path.
3695 while (S
->getFlags() & Scope::TemplateParamScope
)
3697 assert(S
->getFlags() & Scope::DeclScope
&& "Invalid Scope.");
3699 UsingDirectiveDecl
*UDir
= 0;
3700 NestedNameSpecifier
*Qualifier
= 0;
3702 Qualifier
= static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
3704 // Lookup namespace name.
3705 LookupResult
R(*this, NamespcName
, IdentLoc
, LookupNamespaceName
);
3706 LookupParsedName(R
, S
, &SS
);
3707 if (R
.isAmbiguous())
3711 // Allow "using namespace std;" or "using namespace ::std;" even if
3712 // "std" hasn't been defined yet, for GCC compatibility.
3713 if ((!Qualifier
|| Qualifier
->getKind() == NestedNameSpecifier::Global
) &&
3714 NamespcName
->isStr("std")) {
3715 Diag(IdentLoc
, diag::ext_using_undefined_std
);
3716 R
.addDecl(getOrCreateStdNamespace());
3719 // Otherwise, attempt typo correction.
3720 else if (DeclarationName Corrected
= CorrectTypo(R
, S
, &SS
, 0, false,
3721 CTC_NoKeywords
, 0)) {
3722 if (R
.getAsSingle
<NamespaceDecl
>() ||
3723 R
.getAsSingle
<NamespaceAliasDecl
>()) {
3724 if (DeclContext
*DC
= computeDeclContext(SS
, false))
3725 Diag(IdentLoc
, diag::err_using_directive_member_suggest
)
3726 << NamespcName
<< DC
<< Corrected
<< SS
.getRange()
3727 << FixItHint::CreateReplacement(IdentLoc
, Corrected
.getAsString());
3729 Diag(IdentLoc
, diag::err_using_directive_suggest
)
3730 << NamespcName
<< Corrected
3731 << FixItHint::CreateReplacement(IdentLoc
, Corrected
.getAsString());
3732 Diag(R
.getFoundDecl()->getLocation(), diag::note_namespace_defined_here
)
3735 NamespcName
= Corrected
.getAsIdentifierInfo();
3738 R
.setLookupName(NamespcName
);
3744 NamedDecl
*Named
= R
.getFoundDecl();
3745 assert((isa
<NamespaceDecl
>(Named
) || isa
<NamespaceAliasDecl
>(Named
))
3746 && "expected namespace decl");
3747 // C++ [namespace.udir]p1:
3748 // A using-directive specifies that the names in the nominated
3749 // namespace can be used in the scope in which the
3750 // using-directive appears after the using-directive. During
3751 // unqualified name lookup (3.4.1), the names appear as if they
3752 // were declared in the nearest enclosing namespace which
3753 // contains both the using-directive and the nominated
3754 // namespace. [Note: in this context, "contains" means "contains
3755 // directly or indirectly". ]
3757 // Find enclosing context containing both using-directive and
3758 // nominated namespace.
3759 NamespaceDecl
*NS
= getNamespaceDecl(Named
);
3760 DeclContext
*CommonAncestor
= cast
<DeclContext
>(NS
);
3761 while (CommonAncestor
&& !CommonAncestor
->Encloses(CurContext
))
3762 CommonAncestor
= CommonAncestor
->getParent();
3764 UDir
= UsingDirectiveDecl::Create(Context
, CurContext
, UsingLoc
, NamespcLoc
,
3766 (NestedNameSpecifier
*)SS
.getScopeRep(),
3767 IdentLoc
, Named
, CommonAncestor
);
3768 PushUsingDirective(S
, UDir
);
3770 Diag(IdentLoc
, diag::err_expected_namespace_name
) << SS
.getRange();
3773 // FIXME: We ignore attributes for now.
3777 void Sema::PushUsingDirective(Scope
*S
, UsingDirectiveDecl
*UDir
) {
3778 // If scope has associated entity, then using directive is at namespace
3779 // or translation unit scope. We add UsingDirectiveDecls, into
3780 // it's lookup structure.
3781 if (DeclContext
*Ctx
= static_cast<DeclContext
*>(S
->getEntity()))
3784 // Otherwise it is block-sope. using-directives will affect lookup
3785 // only to the end of scope.
3786 S
->PushUsingDirective(UDir
);
3790 Decl
*Sema::ActOnUsingDeclaration(Scope
*S
,
3792 bool HasUsingKeyword
,
3793 SourceLocation UsingLoc
,
3795 UnqualifiedId
&Name
,
3796 AttributeList
*AttrList
,
3798 SourceLocation TypenameLoc
) {
3799 assert(S
->getFlags() & Scope::DeclScope
&& "Invalid Scope.");
3801 switch (Name
.getKind()) {
3802 case UnqualifiedId::IK_Identifier
:
3803 case UnqualifiedId::IK_OperatorFunctionId
:
3804 case UnqualifiedId::IK_LiteralOperatorId
:
3805 case UnqualifiedId::IK_ConversionFunctionId
:
3808 case UnqualifiedId::IK_ConstructorName
:
3809 case UnqualifiedId::IK_ConstructorTemplateId
:
3810 // C++0x inherited constructors.
3811 if (getLangOptions().CPlusPlus0x
) break;
3813 Diag(Name
.getSourceRange().getBegin(), diag::err_using_decl_constructor
)
3817 case UnqualifiedId::IK_DestructorName
:
3818 Diag(Name
.getSourceRange().getBegin(), diag::err_using_decl_destructor
)
3822 case UnqualifiedId::IK_TemplateId
:
3823 Diag(Name
.getSourceRange().getBegin(), diag::err_using_decl_template_id
)
3824 << SourceRange(Name
.TemplateId
->LAngleLoc
, Name
.TemplateId
->RAngleLoc
);
3828 DeclarationNameInfo TargetNameInfo
= GetNameFromUnqualifiedId(Name
);
3829 DeclarationName TargetName
= TargetNameInfo
.getName();
3833 // Warn about using declarations.
3834 // TODO: store that the declaration was written without 'using' and
3835 // talk about access decls instead of using decls in the
3837 if (!HasUsingKeyword
) {
3838 UsingLoc
= Name
.getSourceRange().getBegin();
3840 Diag(UsingLoc
, diag::warn_access_decl_deprecated
)
3841 << FixItHint::CreateInsertion(SS
.getRange().getBegin(), "using ");
3844 if (DiagnoseUnexpandedParameterPack(SS
, UPPC_UsingDeclaration
) ||
3845 DiagnoseUnexpandedParameterPack(TargetNameInfo
, UPPC_UsingDeclaration
))
3848 NamedDecl
*UD
= BuildUsingDeclaration(S
, AS
, UsingLoc
, SS
,
3849 TargetNameInfo
, AttrList
,
3850 /* IsInstantiation */ false,
3851 IsTypeName
, TypenameLoc
);
3853 PushOnScopeChains(UD
, S
, /*AddToContext*/ false);
3858 /// \brief Determine whether a using declaration considers the given
3859 /// declarations as "equivalent", e.g., if they are redeclarations of
3860 /// the same entity or are both typedefs of the same type.
3862 IsEquivalentForUsingDecl(ASTContext
&Context
, NamedDecl
*D1
, NamedDecl
*D2
,
3863 bool &SuppressRedeclaration
) {
3864 if (D1
->getCanonicalDecl() == D2
->getCanonicalDecl()) {
3865 SuppressRedeclaration
= false;
3869 if (TypedefDecl
*TD1
= dyn_cast
<TypedefDecl
>(D1
))
3870 if (TypedefDecl
*TD2
= dyn_cast
<TypedefDecl
>(D2
)) {
3871 SuppressRedeclaration
= true;
3872 return Context
.hasSameType(TD1
->getUnderlyingType(),
3873 TD2
->getUnderlyingType());
3880 /// Determines whether to create a using shadow decl for a particular
3881 /// decl, given the set of decls existing prior to this using lookup.
3882 bool Sema::CheckUsingShadowDecl(UsingDecl
*Using
, NamedDecl
*Orig
,
3883 const LookupResult
&Previous
) {
3884 // Diagnose finding a decl which is not from a base class of the
3885 // current class. We do this now because there are cases where this
3886 // function will silently decide not to build a shadow decl, which
3887 // will pre-empt further diagnostics.
3889 // We don't need to do this in C++0x because we do the check once on
3892 // FIXME: diagnose the following if we care enough:
3893 // struct A { int foo; };
3894 // struct B : A { using A::foo; };
3895 // template <class T> struct C : A {};
3896 // template <class T> struct D : C<T> { using B::foo; } // <---
3897 // This is invalid (during instantiation) in C++03 because B::foo
3898 // resolves to the using decl in B, which is not a base class of D<T>.
3899 // We can't diagnose it immediately because C<T> is an unknown
3900 // specialization. The UsingShadowDecl in D<T> then points directly
3901 // to A::foo, which will look well-formed when we instantiate.
3902 // The right solution is to not collapse the shadow-decl chain.
3903 if (!getLangOptions().CPlusPlus0x
&& CurContext
->isRecord()) {
3904 DeclContext
*OrigDC
= Orig
->getDeclContext();
3906 // Handle enums and anonymous structs.
3907 if (isa
<EnumDecl
>(OrigDC
)) OrigDC
= OrigDC
->getParent();
3908 CXXRecordDecl
*OrigRec
= cast
<CXXRecordDecl
>(OrigDC
);
3909 while (OrigRec
->isAnonymousStructOrUnion())
3910 OrigRec
= cast
<CXXRecordDecl
>(OrigRec
->getDeclContext());
3912 if (cast
<CXXRecordDecl
>(CurContext
)->isProvablyNotDerivedFrom(OrigRec
)) {
3913 if (OrigDC
== CurContext
) {
3914 Diag(Using
->getLocation(),
3915 diag::err_using_decl_nested_name_specifier_is_current_class
)
3916 << Using
->getNestedNameRange();
3917 Diag(Orig
->getLocation(), diag::note_using_decl_target
);
3921 Diag(Using
->getNestedNameRange().getBegin(),
3922 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
3923 << Using
->getTargetNestedNameDecl()
3924 << cast
<CXXRecordDecl
>(CurContext
)
3925 << Using
->getNestedNameRange();
3926 Diag(Orig
->getLocation(), diag::note_using_decl_target
);
3931 if (Previous
.empty()) return false;
3933 NamedDecl
*Target
= Orig
;
3934 if (isa
<UsingShadowDecl
>(Target
))
3935 Target
= cast
<UsingShadowDecl
>(Target
)->getTargetDecl();
3937 // If the target happens to be one of the previous declarations, we
3938 // don't have a conflict.
3940 // FIXME: but we might be increasing its access, in which case we
3941 // should redeclare it.
3942 NamedDecl
*NonTag
= 0, *Tag
= 0;
3943 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
3945 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
3947 if (IsEquivalentForUsingDecl(Context
, D
, Target
, Result
))
3950 (isa
<TagDecl
>(D
) ? Tag
: NonTag
) = D
;
3953 if (Target
->isFunctionOrFunctionTemplate()) {
3955 if (isa
<FunctionTemplateDecl
>(Target
))
3956 FD
= cast
<FunctionTemplateDecl
>(Target
)->getTemplatedDecl();
3958 FD
= cast
<FunctionDecl
>(Target
);
3960 NamedDecl
*OldDecl
= 0;
3961 switch (CheckOverload(0, FD
, Previous
, OldDecl
, /*IsForUsingDecl*/ true)) {
3965 case Ovl_NonFunction
:
3966 Diag(Using
->getLocation(), diag::err_using_decl_conflict
);
3969 // We found a decl with the exact signature.
3971 // If we're in a record, we want to hide the target, so we
3972 // return true (without a diagnostic) to tell the caller not to
3973 // build a shadow decl.
3974 if (CurContext
->isRecord())
3977 // If we're not in a record, this is an error.
3978 Diag(Using
->getLocation(), diag::err_using_decl_conflict
);
3982 Diag(Target
->getLocation(), diag::note_using_decl_target
);
3983 Diag(OldDecl
->getLocation(), diag::note_using_decl_conflict
);
3987 // Target is not a function.
3989 if (isa
<TagDecl
>(Target
)) {
3990 // No conflict between a tag and a non-tag.
3991 if (!Tag
) return false;
3993 Diag(Using
->getLocation(), diag::err_using_decl_conflict
);
3994 Diag(Target
->getLocation(), diag::note_using_decl_target
);
3995 Diag(Tag
->getLocation(), diag::note_using_decl_conflict
);
3999 // No conflict between a tag and a non-tag.
4000 if (!NonTag
) return false;
4002 Diag(Using
->getLocation(), diag::err_using_decl_conflict
);
4003 Diag(Target
->getLocation(), diag::note_using_decl_target
);
4004 Diag(NonTag
->getLocation(), diag::note_using_decl_conflict
);
4008 /// Builds a shadow declaration corresponding to a 'using' declaration.
4009 UsingShadowDecl
*Sema::BuildUsingShadowDecl(Scope
*S
,
4013 // If we resolved to another shadow declaration, just coalesce them.
4014 NamedDecl
*Target
= Orig
;
4015 if (isa
<UsingShadowDecl
>(Target
)) {
4016 Target
= cast
<UsingShadowDecl
>(Target
)->getTargetDecl();
4017 assert(!isa
<UsingShadowDecl
>(Target
) && "nested shadow declaration");
4020 UsingShadowDecl
*Shadow
4021 = UsingShadowDecl::Create(Context
, CurContext
,
4022 UD
->getLocation(), UD
, Target
);
4023 UD
->addShadowDecl(Shadow
);
4025 Shadow
->setAccess(UD
->getAccess());
4026 if (Orig
->isInvalidDecl() || UD
->isInvalidDecl())
4027 Shadow
->setInvalidDecl();
4030 PushOnScopeChains(Shadow
, S
);
4032 CurContext
->addDecl(Shadow
);
4038 /// Hides a using shadow declaration. This is required by the current
4039 /// using-decl implementation when a resolvable using declaration in a
4040 /// class is followed by a declaration which would hide or override
4041 /// one or more of the using decl's targets; for example:
4043 /// struct Base { void foo(int); };
4044 /// struct Derived : Base {
4045 /// using Base::foo;
4049 /// The governing language is C++03 [namespace.udecl]p12:
4051 /// When a using-declaration brings names from a base class into a
4052 /// derived class scope, member functions in the derived class
4053 /// override and/or hide member functions with the same name and
4054 /// parameter types in a base class (rather than conflicting).
4056 /// There are two ways to implement this:
4057 /// (1) optimistically create shadow decls when they're not hidden
4058 /// by existing declarations, or
4059 /// (2) don't create any shadow decls (or at least don't make them
4060 /// visible) until we've fully parsed/instantiated the class.
4061 /// The problem with (1) is that we might have to retroactively remove
4062 /// a shadow decl, which requires several O(n) operations because the
4063 /// decl structures are (very reasonably) not designed for removal.
4064 /// (2) avoids this but is very fiddly and phase-dependent.
4065 void Sema::HideUsingShadowDecl(Scope
*S
, UsingShadowDecl
*Shadow
) {
4066 if (Shadow
->getDeclName().getNameKind() ==
4067 DeclarationName::CXXConversionFunctionName
)
4068 cast
<CXXRecordDecl
>(Shadow
->getDeclContext())->removeConversion(Shadow
);
4070 // Remove it from the DeclContext...
4071 Shadow
->getDeclContext()->removeDecl(Shadow
);
4073 // ...and the scope, if applicable...
4075 S
->RemoveDecl(Shadow
);
4076 IdResolver
.RemoveDecl(Shadow
);
4079 // ...and the using decl.
4080 Shadow
->getUsingDecl()->removeShadowDecl(Shadow
);
4082 // TODO: complain somehow if Shadow was used. It shouldn't
4083 // be possible for this to happen, because...?
4086 /// Builds a using declaration.
4088 /// \param IsInstantiation - Whether this call arises from an
4089 /// instantiation of an unresolved using declaration. We treat
4090 /// the lookup differently for these declarations.
4091 NamedDecl
*Sema::BuildUsingDeclaration(Scope
*S
, AccessSpecifier AS
,
4092 SourceLocation UsingLoc
,
4094 const DeclarationNameInfo
&NameInfo
,
4095 AttributeList
*AttrList
,
4096 bool IsInstantiation
,
4098 SourceLocation TypenameLoc
) {
4099 assert(!SS
.isInvalid() && "Invalid CXXScopeSpec.");
4100 SourceLocation IdentLoc
= NameInfo
.getLoc();
4101 assert(IdentLoc
.isValid() && "Invalid TargetName location.");
4103 // FIXME: We ignore attributes for now.
4106 Diag(IdentLoc
, diag::err_using_requires_qualname
);
4110 // Do the redeclaration lookup in the current scope.
4111 LookupResult
Previous(*this, NameInfo
, LookupUsingDeclName
,
4113 Previous
.setHideTags(false);
4115 LookupName(Previous
, S
);
4117 // It is really dumb that we have to do this.
4118 LookupResult::Filter F
= Previous
.makeFilter();
4119 while (F
.hasNext()) {
4120 NamedDecl
*D
= F
.next();
4121 if (!isDeclInScope(D
, CurContext
, S
))
4126 assert(IsInstantiation
&& "no scope in non-instantiation");
4127 assert(CurContext
->isRecord() && "scope not record in instantiation");
4128 LookupQualifiedName(Previous
, CurContext
);
4131 NestedNameSpecifier
*NNS
= SS
.getScopeRep();
4133 // Check for invalid redeclarations.
4134 if (CheckUsingDeclRedeclaration(UsingLoc
, IsTypeName
, SS
, IdentLoc
, Previous
))
4137 // Check for bad qualifiers.
4138 if (CheckUsingDeclQualifier(UsingLoc
, SS
, IdentLoc
))
4141 DeclContext
*LookupContext
= computeDeclContext(SS
);
4143 if (!LookupContext
) {
4145 // FIXME: not all declaration name kinds are legal here
4146 D
= UnresolvedUsingTypenameDecl::Create(Context
, CurContext
,
4147 UsingLoc
, TypenameLoc
,
4149 IdentLoc
, NameInfo
.getName());
4151 D
= UnresolvedUsingValueDecl::Create(Context
, CurContext
,
4152 UsingLoc
, SS
.getRange(),
4156 D
= UsingDecl::Create(Context
, CurContext
,
4157 SS
.getRange(), UsingLoc
, NNS
, NameInfo
,
4161 CurContext
->addDecl(D
);
4163 if (!LookupContext
) return D
;
4164 UsingDecl
*UD
= cast
<UsingDecl
>(D
);
4166 if (RequireCompleteDeclContext(SS
, LookupContext
)) {
4167 UD
->setInvalidDecl();
4171 // Constructor inheriting using decls get special treatment.
4172 if (NameInfo
.getName().getNameKind() == DeclarationName::CXXConstructorName
) {
4173 if (CheckInheritedConstructorUsingDecl(UD
))
4174 UD
->setInvalidDecl();
4178 // Otherwise, look up the target name.
4180 LookupResult
R(*this, NameInfo
, LookupOrdinaryName
);
4182 // Unlike most lookups, we don't always want to hide tag
4183 // declarations: tag names are visible through the using declaration
4184 // even if hidden by ordinary names, *except* in a dependent context
4185 // where it's important for the sanity of two-phase lookup.
4186 if (!IsInstantiation
)
4187 R
.setHideTags(false);
4189 LookupQualifiedName(R
, LookupContext
);
4192 Diag(IdentLoc
, diag::err_no_member
)
4193 << NameInfo
.getName() << LookupContext
<< SS
.getRange();
4194 UD
->setInvalidDecl();
4198 if (R
.isAmbiguous()) {
4199 UD
->setInvalidDecl();
4204 // If we asked for a typename and got a non-type decl, error out.
4205 if (!R
.getAsSingle
<TypeDecl
>()) {
4206 Diag(IdentLoc
, diag::err_using_typename_non_type
);
4207 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
)
4208 Diag((*I
)->getUnderlyingDecl()->getLocation(),
4209 diag::note_using_decl_target
);
4210 UD
->setInvalidDecl();
4214 // If we asked for a non-typename and we got a type, error out,
4215 // but only if this is an instantiation of an unresolved using
4216 // decl. Otherwise just silently find the type name.
4217 if (IsInstantiation
&& R
.getAsSingle
<TypeDecl
>()) {
4218 Diag(IdentLoc
, diag::err_using_dependent_value_is_type
);
4219 Diag(R
.getFoundDecl()->getLocation(), diag::note_using_decl_target
);
4220 UD
->setInvalidDecl();
4225 // C++0x N2914 [namespace.udecl]p6:
4226 // A using-declaration shall not name a namespace.
4227 if (R
.getAsSingle
<NamespaceDecl
>()) {
4228 Diag(IdentLoc
, diag::err_using_decl_can_not_refer_to_namespace
)
4230 UD
->setInvalidDecl();
4234 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
) {
4235 if (!CheckUsingShadowDecl(UD
, *I
, Previous
))
4236 BuildUsingShadowDecl(S
, UD
, *I
);
4242 /// Additional checks for a using declaration referring to a constructor name.
4243 bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl
*UD
) {
4244 if (UD
->isTypeName()) {
4245 // FIXME: Cannot specify typename when specifying constructor
4249 const Type
*SourceType
= UD
->getTargetNestedNameDecl()->getAsType();
4250 assert(SourceType
&&
4251 "Using decl naming constructor doesn't have type in scope spec.");
4252 CXXRecordDecl
*TargetClass
= cast
<CXXRecordDecl
>(CurContext
);
4254 // Check whether the named type is a direct base class.
4255 CanQualType CanonicalSourceType
= SourceType
->getCanonicalTypeUnqualified();
4256 CXXRecordDecl::base_class_iterator BaseIt
, BaseE
;
4257 for (BaseIt
= TargetClass
->bases_begin(), BaseE
= TargetClass
->bases_end();
4258 BaseIt
!= BaseE
; ++BaseIt
) {
4259 CanQualType BaseType
= BaseIt
->getType()->getCanonicalTypeUnqualified();
4260 if (CanonicalSourceType
== BaseType
)
4264 if (BaseIt
== BaseE
) {
4265 // Did not find SourceType in the bases.
4266 Diag(UD
->getUsingLocation(),
4267 diag::err_using_decl_constructor_not_in_direct_base
)
4268 << UD
->getNameInfo().getSourceRange()
4269 << QualType(SourceType
, 0) << TargetClass
;
4273 BaseIt
->setInheritConstructors();
4278 /// Checks that the given using declaration is not an invalid
4279 /// redeclaration. Note that this is checking only for the using decl
4280 /// itself, not for any ill-formedness among the UsingShadowDecls.
4281 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc
,
4283 const CXXScopeSpec
&SS
,
4284 SourceLocation NameLoc
,
4285 const LookupResult
&Prev
) {
4286 // C++03 [namespace.udecl]p8:
4287 // C++0x [namespace.udecl]p10:
4288 // A using-declaration is a declaration and can therefore be used
4289 // repeatedly where (and only where) multiple declarations are
4292 // That's in non-member contexts.
4293 if (!CurContext
->getRedeclContext()->isRecord())
4296 NestedNameSpecifier
*Qual
4297 = static_cast<NestedNameSpecifier
*>(SS
.getScopeRep());
4299 for (LookupResult::iterator I
= Prev
.begin(), E
= Prev
.end(); I
!= E
; ++I
) {
4303 NestedNameSpecifier
*DQual
;
4304 if (UsingDecl
*UD
= dyn_cast
<UsingDecl
>(D
)) {
4305 DTypename
= UD
->isTypeName();
4306 DQual
= UD
->getTargetNestedNameDecl();
4307 } else if (UnresolvedUsingValueDecl
*UD
4308 = dyn_cast
<UnresolvedUsingValueDecl
>(D
)) {
4310 DQual
= UD
->getTargetNestedNameSpecifier();
4311 } else if (UnresolvedUsingTypenameDecl
*UD
4312 = dyn_cast
<UnresolvedUsingTypenameDecl
>(D
)) {
4314 DQual
= UD
->getTargetNestedNameSpecifier();
4317 // using decls differ if one says 'typename' and the other doesn't.
4318 // FIXME: non-dependent using decls?
4319 if (isTypeName
!= DTypename
) continue;
4321 // using decls differ if they name different scopes (but note that
4322 // template instantiation can cause this check to trigger when it
4323 // didn't before instantiation).
4324 if (Context
.getCanonicalNestedNameSpecifier(Qual
) !=
4325 Context
.getCanonicalNestedNameSpecifier(DQual
))
4328 Diag(NameLoc
, diag::err_using_decl_redeclaration
) << SS
.getRange();
4329 Diag(D
->getLocation(), diag::note_using_decl
) << 1;
4337 /// Checks that the given nested-name qualifier used in a using decl
4338 /// in the current context is appropriately related to the current
4339 /// scope. If an error is found, diagnoses it and returns true.
4340 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc
,
4341 const CXXScopeSpec
&SS
,
4342 SourceLocation NameLoc
) {
4343 DeclContext
*NamedContext
= computeDeclContext(SS
);
4345 if (!CurContext
->isRecord()) {
4346 // C++03 [namespace.udecl]p3:
4347 // C++0x [namespace.udecl]p8:
4348 // A using-declaration for a class member shall be a member-declaration.
4350 // If we weren't able to compute a valid scope, it must be a
4351 // dependent class scope.
4352 if (!NamedContext
|| NamedContext
->isRecord()) {
4353 Diag(NameLoc
, diag::err_using_decl_can_not_refer_to_class_member
)
4358 // Otherwise, everything is known to be fine.
4362 // The current scope is a record.
4364 // If the named context is dependent, we can't decide much.
4365 if (!NamedContext
) {
4366 // FIXME: in C++0x, we can diagnose if we can prove that the
4367 // nested-name-specifier does not refer to a base class, which is
4368 // still possible in some cases.
4370 // Otherwise we have to conservatively report that things might be
4375 if (!NamedContext
->isRecord()) {
4376 // Ideally this would point at the last name in the specifier,
4377 // but we don't have that level of source info.
4378 Diag(SS
.getRange().getBegin(),
4379 diag::err_using_decl_nested_name_specifier_is_not_class
)
4380 << (NestedNameSpecifier
*) SS
.getScopeRep() << SS
.getRange();
4384 if (!NamedContext
->isDependentContext() &&
4385 RequireCompleteDeclContext(const_cast<CXXScopeSpec
&>(SS
), NamedContext
))
4388 if (getLangOptions().CPlusPlus0x
) {
4389 // C++0x [namespace.udecl]p3:
4390 // In a using-declaration used as a member-declaration, the
4391 // nested-name-specifier shall name a base class of the class
4394 if (cast
<CXXRecordDecl
>(CurContext
)->isProvablyNotDerivedFrom(
4395 cast
<CXXRecordDecl
>(NamedContext
))) {
4396 if (CurContext
== NamedContext
) {
4398 diag::err_using_decl_nested_name_specifier_is_current_class
)
4403 Diag(SS
.getRange().getBegin(),
4404 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
4405 << (NestedNameSpecifier
*) SS
.getScopeRep()
4406 << cast
<CXXRecordDecl
>(CurContext
)
4414 // C++03 [namespace.udecl]p4:
4415 // A using-declaration used as a member-declaration shall refer
4416 // to a member of a base class of the class being defined [etc.].
4418 // Salient point: SS doesn't have to name a base class as long as
4419 // lookup only finds members from base classes. Therefore we can
4420 // diagnose here only if we can prove that that can't happen,
4421 // i.e. if the class hierarchies provably don't intersect.
4423 // TODO: it would be nice if "definitely valid" results were cached
4424 // in the UsingDecl and UsingShadowDecl so that these checks didn't
4425 // need to be repeated.
4428 llvm::DenseSet
<const CXXRecordDecl
*> Bases
;
4430 static bool collect(const CXXRecordDecl
*Base
, void *OpaqueData
) {
4431 UserData
*Data
= reinterpret_cast<UserData
*>(OpaqueData
);
4432 Data
->Bases
.insert(Base
);
4436 bool hasDependentBases(const CXXRecordDecl
*Class
) {
4437 return !Class
->forallBases(collect
, this);
4440 /// Returns true if the base is dependent or is one of the
4441 /// accumulated base classes.
4442 static bool doesNotContain(const CXXRecordDecl
*Base
, void *OpaqueData
) {
4443 UserData
*Data
= reinterpret_cast<UserData
*>(OpaqueData
);
4444 return !Data
->Bases
.count(Base
);
4447 bool mightShareBases(const CXXRecordDecl
*Class
) {
4448 return Bases
.count(Class
) || !Class
->forallBases(doesNotContain
, this);
4454 // Returns false if we find a dependent base.
4455 if (Data
.hasDependentBases(cast
<CXXRecordDecl
>(CurContext
)))
4458 // Returns false if the class has a dependent base or if it or one
4459 // of its bases is present in the base set of the current context.
4460 if (Data
.mightShareBases(cast
<CXXRecordDecl
>(NamedContext
)))
4463 Diag(SS
.getRange().getBegin(),
4464 diag::err_using_decl_nested_name_specifier_is_not_base_class
)
4465 << (NestedNameSpecifier
*) SS
.getScopeRep()
4466 << cast
<CXXRecordDecl
>(CurContext
)
4472 Decl
*Sema::ActOnNamespaceAliasDef(Scope
*S
,
4473 SourceLocation NamespaceLoc
,
4474 SourceLocation AliasLoc
,
4475 IdentifierInfo
*Alias
,
4477 SourceLocation IdentLoc
,
4478 IdentifierInfo
*Ident
) {
4480 // Lookup the namespace name.
4481 LookupResult
R(*this, Ident
, IdentLoc
, LookupNamespaceName
);
4482 LookupParsedName(R
, S
, &SS
);
4484 // Check if we have a previous declaration with the same name.
4486 = LookupSingleName(S
, Alias
, AliasLoc
, LookupOrdinaryName
,
4488 if (PrevDecl
&& !isDeclInScope(PrevDecl
, CurContext
, S
))
4492 if (NamespaceAliasDecl
*AD
= dyn_cast
<NamespaceAliasDecl
>(PrevDecl
)) {
4493 // We already have an alias with the same name that points to the same
4494 // namespace, so don't create a new one.
4495 // FIXME: At some point, we'll want to create the (redundant)
4496 // declaration to maintain better source information.
4497 if (!R
.isAmbiguous() && !R
.empty() &&
4498 AD
->getNamespace()->Equals(getNamespaceDecl(R
.getFoundDecl())))
4502 unsigned DiagID
= isa
<NamespaceDecl
>(PrevDecl
) ? diag::err_redefinition
:
4503 diag::err_redefinition_different_kind
;
4504 Diag(AliasLoc
, DiagID
) << Alias
;
4505 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
4509 if (R
.isAmbiguous())
4513 if (DeclarationName Corrected
= CorrectTypo(R
, S
, &SS
, 0, false,
4514 CTC_NoKeywords
, 0)) {
4515 if (R
.getAsSingle
<NamespaceDecl
>() ||
4516 R
.getAsSingle
<NamespaceAliasDecl
>()) {
4517 if (DeclContext
*DC
= computeDeclContext(SS
, false))
4518 Diag(IdentLoc
, diag::err_using_directive_member_suggest
)
4519 << Ident
<< DC
<< Corrected
<< SS
.getRange()
4520 << FixItHint::CreateReplacement(IdentLoc
, Corrected
.getAsString());
4522 Diag(IdentLoc
, diag::err_using_directive_suggest
)
4523 << Ident
<< Corrected
4524 << FixItHint::CreateReplacement(IdentLoc
, Corrected
.getAsString());
4526 Diag(R
.getFoundDecl()->getLocation(), diag::note_namespace_defined_here
)
4529 Ident
= Corrected
.getAsIdentifierInfo();
4532 R
.setLookupName(Ident
);
4537 Diag(NamespaceLoc
, diag::err_expected_namespace_name
) << SS
.getRange();
4542 NamespaceAliasDecl
*AliasDecl
=
4543 NamespaceAliasDecl::Create(Context
, CurContext
, NamespaceLoc
, AliasLoc
,
4544 Alias
, SS
.getRange(),
4545 (NestedNameSpecifier
*)SS
.getScopeRep(),
4546 IdentLoc
, R
.getFoundDecl());
4548 PushOnScopeChains(AliasDecl
, S
);
4553 /// \brief Scoped object used to handle the state changes required in Sema
4554 /// to implicitly define the body of a C++ member function;
4555 class ImplicitlyDefinedFunctionScope
{
4557 Sema::ContextRAII SavedContext
;
4560 ImplicitlyDefinedFunctionScope(Sema
&S
, CXXMethodDecl
*Method
)
4561 : S(S
), SavedContext(S
, Method
)
4563 S
.PushFunctionScope();
4564 S
.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated
);
4567 ~ImplicitlyDefinedFunctionScope() {
4568 S
.PopExpressionEvaluationContext();
4569 S
.PopFunctionOrBlockScope();
4574 static CXXConstructorDecl
*getDefaultConstructorUnsafe(Sema
&Self
,
4576 ASTContext
&Context
= Self
.Context
;
4577 QualType ClassType
= Context
.getTypeDeclType(D
);
4578 DeclarationName ConstructorName
4579 = Context
.DeclarationNames
.getCXXConstructorName(
4580 Context
.getCanonicalType(ClassType
.getUnqualifiedType()));
4582 DeclContext::lookup_const_iterator Con
, ConEnd
;
4583 for (llvm::tie(Con
, ConEnd
) = D
->lookup(ConstructorName
);
4584 Con
!= ConEnd
; ++Con
) {
4585 // FIXME: In C++0x, a constructor template can be a default constructor.
4586 if (isa
<FunctionTemplateDecl
>(*Con
))
4589 CXXConstructorDecl
*Constructor
= cast
<CXXConstructorDecl
>(*Con
);
4590 if (Constructor
->isDefaultConstructor())
4596 CXXConstructorDecl
*Sema::DeclareImplicitDefaultConstructor(
4597 CXXRecordDecl
*ClassDecl
) {
4598 // C++ [class.ctor]p5:
4599 // A default constructor for a class X is a constructor of class X
4600 // that can be called without an argument. If there is no
4601 // user-declared constructor for class X, a default constructor is
4602 // implicitly declared. An implicitly-declared default constructor
4603 // is an inline public member of its class.
4604 assert(!ClassDecl
->hasUserDeclaredConstructor() &&
4605 "Should not build implicit default constructor!");
4607 // C++ [except.spec]p14:
4608 // An implicitly declared special member function (Clause 12) shall have an
4609 // exception-specification. [...]
4610 ImplicitExceptionSpecification
ExceptSpec(Context
);
4612 // Direct base-class destructors.
4613 for (CXXRecordDecl::base_class_iterator B
= ClassDecl
->bases_begin(),
4614 BEnd
= ClassDecl
->bases_end();
4616 if (B
->isVirtual()) // Handled below.
4619 if (const RecordType
*BaseType
= B
->getType()->getAs
<RecordType
>()) {
4620 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(BaseType
->getDecl());
4621 if (!BaseClassDecl
->hasDeclaredDefaultConstructor())
4622 ExceptSpec
.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl
));
4623 else if (CXXConstructorDecl
*Constructor
4624 = getDefaultConstructorUnsafe(*this, BaseClassDecl
))
4625 ExceptSpec
.CalledDecl(Constructor
);
4629 // Virtual base-class destructors.
4630 for (CXXRecordDecl::base_class_iterator B
= ClassDecl
->vbases_begin(),
4631 BEnd
= ClassDecl
->vbases_end();
4633 if (const RecordType
*BaseType
= B
->getType()->getAs
<RecordType
>()) {
4634 CXXRecordDecl
*BaseClassDecl
= cast
<CXXRecordDecl
>(BaseType
->getDecl());
4635 if (!BaseClassDecl
->hasDeclaredDefaultConstructor())
4636 ExceptSpec
.CalledDecl(DeclareImplicitDefaultConstructor(BaseClassDecl
));
4637 else if (CXXConstructorDecl
*Constructor
4638 = getDefaultConstructorUnsafe(*this, BaseClassDecl
))
4639 ExceptSpec
.CalledDecl(Constructor
);
4643 // Field destructors.
4644 for (RecordDecl::field_iterator F
= ClassDecl
->field_begin(),
4645 FEnd
= ClassDecl
->field_end();
4647 if (const RecordType
*RecordTy
4648 = Context
.getBaseElementType(F
->getType())->getAs
<RecordType
>()) {
4649 CXXRecordDecl
*FieldClassDecl
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
4650 if (!FieldClassDecl
->hasDeclaredDefaultConstructor())
4651 ExceptSpec
.CalledDecl(
4652 DeclareImplicitDefaultConstructor(FieldClassDecl
));
4653 else if (CXXConstructorDecl
*Constructor
4654 = getDefaultConstructorUnsafe(*this, FieldClassDecl
))
4655 ExceptSpec
.CalledDecl(Constructor
);
4659 FunctionProtoType::ExtProtoInfo EPI
;
4660 EPI
.HasExceptionSpec
= ExceptSpec
.hasExceptionSpecification();
4661 EPI
.HasAnyExceptionSpec
= ExceptSpec
.hasAnyExceptionSpecification();
4662 EPI
.NumExceptions
= ExceptSpec
.size();
4663 EPI
.Exceptions
= ExceptSpec
.data();
4665 // Create the actual constructor declaration.
4666 CanQualType ClassType
4667 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
4668 DeclarationName Name
4669 = Context
.DeclarationNames
.getCXXConstructorName(ClassType
);
4670 DeclarationNameInfo
NameInfo(Name
, ClassDecl
->getLocation());
4671 CXXConstructorDecl
*DefaultCon
4672 = CXXConstructorDecl::Create(Context
, ClassDecl
, NameInfo
,
4673 Context
.getFunctionType(Context
.VoidTy
,
4676 /*isExplicit=*/false,
4678 /*isImplicitlyDeclared=*/true);
4679 DefaultCon
->setAccess(AS_public
);
4680 DefaultCon
->setImplicit();
4681 DefaultCon
->setTrivial(ClassDecl
->hasTrivialConstructor());
4683 // Note that we have declared this constructor.
4684 ++ASTContext::NumImplicitDefaultConstructorsDeclared
;
4686 if (Scope
*S
= getScopeForContext(ClassDecl
))
4687 PushOnScopeChains(DefaultCon
, S
, false);
4688 ClassDecl
->addDecl(DefaultCon
);
4693 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation
,
4694 CXXConstructorDecl
*Constructor
) {
4695 assert((Constructor
->isImplicit() && Constructor
->isDefaultConstructor() &&
4696 !Constructor
->isUsed(false)) &&
4697 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
4699 CXXRecordDecl
*ClassDecl
= Constructor
->getParent();
4700 assert(ClassDecl
&& "DefineImplicitDefaultConstructor - invalid constructor");
4702 ImplicitlyDefinedFunctionScope
Scope(*this, Constructor
);
4703 DiagnosticErrorTrap
Trap(Diags
);
4704 if (SetCtorInitializers(Constructor
, 0, 0, /*AnyErrors=*/false) ||
4705 Trap
.hasErrorOccurred()) {
4706 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
4707 << CXXConstructor
<< Context
.getTagDeclType(ClassDecl
);
4708 Constructor
->setInvalidDecl();
4712 SourceLocation Loc
= Constructor
->getLocation();
4713 Constructor
->setBody(new (Context
) CompoundStmt(Context
, 0, 0, Loc
, Loc
));
4715 Constructor
->setUsed();
4716 MarkVTableUsed(CurrentLocation
, ClassDecl
);
4719 void Sema::DeclareInheritedConstructors(CXXRecordDecl
*ClassDecl
) {
4720 // We start with an initial pass over the base classes to collect those that
4721 // inherit constructors from. If there are none, we can forgo all further
4723 typedef llvm::SmallVector
<const RecordType
*, 4> BasesVector
;
4724 BasesVector BasesToInheritFrom
;
4725 for (CXXRecordDecl::base_class_iterator BaseIt
= ClassDecl
->bases_begin(),
4726 BaseE
= ClassDecl
->bases_end();
4727 BaseIt
!= BaseE
; ++BaseIt
) {
4728 if (BaseIt
->getInheritConstructors()) {
4729 QualType Base
= BaseIt
->getType();
4730 if (Base
->isDependentType()) {
4731 // If we inherit constructors from anything that is dependent, just
4732 // abort processing altogether. We'll get another chance for the
4736 BasesToInheritFrom
.push_back(Base
->castAs
<RecordType
>());
4739 if (BasesToInheritFrom
.empty())
4742 // Now collect the constructors that we already have in the current class.
4743 // Those take precedence over inherited constructors.
4744 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
4745 // unless there is a user-declared constructor with the same signature in
4746 // the class where the using-declaration appears.
4747 llvm::SmallSet
<const Type
*, 8> ExistingConstructors
;
4748 for (CXXRecordDecl::ctor_iterator CtorIt
= ClassDecl
->ctor_begin(),
4749 CtorE
= ClassDecl
->ctor_end();
4750 CtorIt
!= CtorE
; ++CtorIt
) {
4751 ExistingConstructors
.insert(
4752 Context
.getCanonicalType(CtorIt
->getType()).getTypePtr());
4755 Scope
*S
= getScopeForContext(ClassDecl
);
4756 DeclarationName CreatedCtorName
=
4757 Context
.DeclarationNames
.getCXXConstructorName(
4758 ClassDecl
->getTypeForDecl()->getCanonicalTypeUnqualified());
4760 // Now comes the true work.
4761 // First, we keep a map from constructor types to the base that introduced
4762 // them. Needed for finding conflicting constructors. We also keep the
4763 // actually inserted declarations in there, for pretty diagnostics.
4764 typedef std::pair
<CanQualType
, CXXConstructorDecl
*> ConstructorInfo
;
4765 typedef llvm::DenseMap
<const Type
*, ConstructorInfo
> ConstructorToSourceMap
;
4766 ConstructorToSourceMap InheritedConstructors
;
4767 for (BasesVector::iterator BaseIt
= BasesToInheritFrom
.begin(),
4768 BaseE
= BasesToInheritFrom
.end();
4769 BaseIt
!= BaseE
; ++BaseIt
) {
4770 const RecordType
*Base
= *BaseIt
;
4771 CanQualType CanonicalBase
= Base
->getCanonicalTypeUnqualified();
4772 CXXRecordDecl
*BaseDecl
= cast
<CXXRecordDecl
>(Base
->getDecl());
4773 for (CXXRecordDecl::ctor_iterator CtorIt
= BaseDecl
->ctor_begin(),
4774 CtorE
= BaseDecl
->ctor_end();
4775 CtorIt
!= CtorE
; ++CtorIt
) {
4776 // Find the using declaration for inheriting this base's constructors.
4777 DeclarationName Name
=
4778 Context
.DeclarationNames
.getCXXConstructorName(CanonicalBase
);
4779 UsingDecl
*UD
= dyn_cast_or_null
<UsingDecl
>(
4780 LookupSingleName(S
, Name
,SourceLocation(), LookupUsingDeclName
));
4781 SourceLocation UsingLoc
= UD
? UD
->getLocation() :
4782 ClassDecl
->getLocation();
4784 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
4785 // from the class X named in the using-declaration consists of actual
4786 // constructors and notional constructors that result from the
4787 // transformation of defaulted parameters as follows:
4788 // - all non-template default constructors of X, and
4789 // - for each non-template constructor of X that has at least one
4790 // parameter with a default argument, the set of constructors that
4791 // results from omitting any ellipsis parameter specification and
4792 // successively omitting parameters with a default argument from the
4793 // end of the parameter-type-list.
4794 CXXConstructorDecl
*BaseCtor
= *CtorIt
;
4795 bool CanBeCopyOrMove
= BaseCtor
->isCopyOrMoveConstructor();
4796 const FunctionProtoType
*BaseCtorType
=
4797 BaseCtor
->getType()->getAs
<FunctionProtoType
>();
4799 for (unsigned params
= BaseCtor
->getMinRequiredArguments(),
4800 maxParams
= BaseCtor
->getNumParams();
4801 params
<= maxParams
; ++params
) {
4802 // Skip default constructors. They're never inherited.
4805 // Skip copy and move constructors for the same reason.
4806 if (CanBeCopyOrMove
&& params
== 1)
4809 // Build up a function type for this particular constructor.
4810 // FIXME: The working paper does not consider that the exception spec
4811 // for the inheriting constructor might be larger than that of the
4812 // source. This code doesn't yet, either.
4813 const Type
*NewCtorType
;
4814 if (params
== maxParams
)
4815 NewCtorType
= BaseCtorType
;
4817 llvm::SmallVector
<QualType
, 16> Args
;
4818 for (unsigned i
= 0; i
< params
; ++i
) {
4819 Args
.push_back(BaseCtorType
->getArgType(i
));
4821 FunctionProtoType::ExtProtoInfo ExtInfo
=
4822 BaseCtorType
->getExtProtoInfo();
4823 ExtInfo
.Variadic
= false;
4824 NewCtorType
= Context
.getFunctionType(BaseCtorType
->getResultType(),
4825 Args
.data(), params
, ExtInfo
)
4828 const Type
*CanonicalNewCtorType
=
4829 Context
.getCanonicalType(NewCtorType
);
4831 // Now that we have the type, first check if the class already has a
4832 // constructor with this signature.
4833 if (ExistingConstructors
.count(CanonicalNewCtorType
))
4836 // Then we check if we have already declared an inherited constructor
4837 // with this signature.
4838 std::pair
<ConstructorToSourceMap::iterator
, bool> result
=
4839 InheritedConstructors
.insert(std::make_pair(
4840 CanonicalNewCtorType
,
4841 std::make_pair(CanonicalBase
, (CXXConstructorDecl
*)0)));
4842 if (!result
.second
) {
4843 // Already in the map. If it came from a different class, that's an
4844 // error. Not if it's from the same.
4845 CanQualType PreviousBase
= result
.first
->second
.first
;
4846 if (CanonicalBase
!= PreviousBase
) {
4847 const CXXConstructorDecl
*PrevCtor
= result
.first
->second
.second
;
4848 const CXXConstructorDecl
*PrevBaseCtor
=
4849 PrevCtor
->getInheritedConstructor();
4850 assert(PrevBaseCtor
&& "Conflicting constructor was not inherited");
4852 Diag(UsingLoc
, diag::err_using_decl_constructor_conflict
);
4853 Diag(BaseCtor
->getLocation(),
4854 diag::note_using_decl_constructor_conflict_current_ctor
);
4855 Diag(PrevBaseCtor
->getLocation(),
4856 diag::note_using_decl_constructor_conflict_previous_ctor
);
4857 Diag(PrevCtor
->getLocation(),
4858 diag::note_using_decl_constructor_conflict_previous_using
);
4863 // OK, we're there, now add the constructor.
4864 // C++0x [class.inhctor]p8: [...] that would be performed by a
4865 // user-writtern inline constructor [...]
4866 DeclarationNameInfo
DNI(CreatedCtorName
, UsingLoc
);
4867 CXXConstructorDecl
*NewCtor
= CXXConstructorDecl::Create(
4868 Context
, ClassDecl
, DNI
, QualType(NewCtorType
, 0), /*TInfo=*/0,
4869 BaseCtor
->isExplicit(), /*Inline=*/true,
4870 /*ImplicitlyDeclared=*/true);
4871 NewCtor
->setAccess(BaseCtor
->getAccess());
4873 // Build up the parameter decls and add them.
4874 llvm::SmallVector
<ParmVarDecl
*, 16> ParamDecls
;
4875 for (unsigned i
= 0; i
< params
; ++i
) {
4876 ParamDecls
.push_back(ParmVarDecl::Create(Context
, NewCtor
, UsingLoc
,
4877 /*IdentifierInfo=*/0,
4878 BaseCtorType
->getArgType(i
),
4879 /*TInfo=*/0, SC_None
,
4880 SC_None
, /*DefaultArg=*/0));
4882 NewCtor
->setParams(ParamDecls
.data(), ParamDecls
.size());
4883 NewCtor
->setInheritedConstructor(BaseCtor
);
4885 PushOnScopeChains(NewCtor
, S
, false);
4886 ClassDecl
->addDecl(NewCtor
);
4887 result
.first
->second
.second
= NewCtor
;
4893 CXXDestructorDecl
*Sema::DeclareImplicitDestructor(CXXRecordDecl
*ClassDecl
) {
4894 // C++ [class.dtor]p2:
4895 // If a class has no user-declared destructor, a destructor is
4896 // declared implicitly. An implicitly-declared destructor is an
4897 // inline public member of its class.
4899 // C++ [except.spec]p14:
4900 // An implicitly declared special member function (Clause 12) shall have
4901 // an exception-specification.
4902 ImplicitExceptionSpecification
ExceptSpec(Context
);
4904 // Direct base-class destructors.
4905 for (CXXRecordDecl::base_class_iterator B
= ClassDecl
->bases_begin(),
4906 BEnd
= ClassDecl
->bases_end();
4908 if (B
->isVirtual()) // Handled below.
4911 if (const RecordType
*BaseType
= B
->getType()->getAs
<RecordType
>())
4912 ExceptSpec
.CalledDecl(
4913 LookupDestructor(cast
<CXXRecordDecl
>(BaseType
->getDecl())));
4916 // Virtual base-class destructors.
4917 for (CXXRecordDecl::base_class_iterator B
= ClassDecl
->vbases_begin(),
4918 BEnd
= ClassDecl
->vbases_end();
4920 if (const RecordType
*BaseType
= B
->getType()->getAs
<RecordType
>())
4921 ExceptSpec
.CalledDecl(
4922 LookupDestructor(cast
<CXXRecordDecl
>(BaseType
->getDecl())));
4925 // Field destructors.
4926 for (RecordDecl::field_iterator F
= ClassDecl
->field_begin(),
4927 FEnd
= ClassDecl
->field_end();
4929 if (const RecordType
*RecordTy
4930 = Context
.getBaseElementType(F
->getType())->getAs
<RecordType
>())
4931 ExceptSpec
.CalledDecl(
4932 LookupDestructor(cast
<CXXRecordDecl
>(RecordTy
->getDecl())));
4935 // Create the actual destructor declaration.
4936 FunctionProtoType::ExtProtoInfo EPI
;
4937 EPI
.HasExceptionSpec
= ExceptSpec
.hasExceptionSpecification();
4938 EPI
.HasAnyExceptionSpec
= ExceptSpec
.hasAnyExceptionSpecification();
4939 EPI
.NumExceptions
= ExceptSpec
.size();
4940 EPI
.Exceptions
= ExceptSpec
.data();
4941 QualType Ty
= Context
.getFunctionType(Context
.VoidTy
, 0, 0, EPI
);
4943 CanQualType ClassType
4944 = Context
.getCanonicalType(Context
.getTypeDeclType(ClassDecl
));
4945 DeclarationName Name
4946 = Context
.DeclarationNames
.getCXXDestructorName(ClassType
);
4947 DeclarationNameInfo
NameInfo(Name
, ClassDecl
->getLocation());
4948 CXXDestructorDecl
*Destructor
4949 = CXXDestructorDecl::Create(Context
, ClassDecl
, NameInfo
, Ty
, 0,
4951 /*isImplicitlyDeclared=*/true);
4952 Destructor
->setAccess(AS_public
);
4953 Destructor
->setImplicit();
4954 Destructor
->setTrivial(ClassDecl
->hasTrivialDestructor());
4956 // Note that we have declared this destructor.
4957 ++ASTContext::NumImplicitDestructorsDeclared
;
4959 // Introduce this destructor into its scope.
4960 if (Scope
*S
= getScopeForContext(ClassDecl
))
4961 PushOnScopeChains(Destructor
, S
, false);
4962 ClassDecl
->addDecl(Destructor
);
4964 // This could be uniqued if it ever proves significant.
4965 Destructor
->setTypeSourceInfo(Context
.getTrivialTypeSourceInfo(Ty
));
4967 AddOverriddenMethods(ClassDecl
, Destructor
);
4972 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation
,
4973 CXXDestructorDecl
*Destructor
) {
4974 assert((Destructor
->isImplicit() && !Destructor
->isUsed(false)) &&
4975 "DefineImplicitDestructor - call it for implicit default dtor");
4976 CXXRecordDecl
*ClassDecl
= Destructor
->getParent();
4977 assert(ClassDecl
&& "DefineImplicitDestructor - invalid destructor");
4979 if (Destructor
->isInvalidDecl())
4982 ImplicitlyDefinedFunctionScope
Scope(*this, Destructor
);
4984 DiagnosticErrorTrap
Trap(Diags
);
4985 MarkBaseAndMemberDestructorsReferenced(Destructor
->getLocation(),
4986 Destructor
->getParent());
4988 if (CheckDestructor(Destructor
) || Trap
.hasErrorOccurred()) {
4989 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
4990 << CXXDestructor
<< Context
.getTagDeclType(ClassDecl
);
4992 Destructor
->setInvalidDecl();
4996 SourceLocation Loc
= Destructor
->getLocation();
4997 Destructor
->setBody(new (Context
) CompoundStmt(Context
, 0, 0, Loc
, Loc
));
4999 Destructor
->setUsed();
5000 MarkVTableUsed(CurrentLocation
, ClassDecl
);
5003 /// \brief Builds a statement that copies the given entity from \p From to
5006 /// This routine is used to copy the members of a class with an
5007 /// implicitly-declared copy assignment operator. When the entities being
5008 /// copied are arrays, this routine builds for loops to copy them.
5010 /// \param S The Sema object used for type-checking.
5012 /// \param Loc The location where the implicit copy is being generated.
5014 /// \param T The type of the expressions being copied. Both expressions must
5017 /// \param To The expression we are copying to.
5019 /// \param From The expression we are copying from.
5021 /// \param CopyingBaseSubobject Whether we're copying a base subobject.
5022 /// Otherwise, it's a non-static member subobject.
5024 /// \param Depth Internal parameter recording the depth of the recursion.
5026 /// \returns A statement or a loop that copies the expressions.
5028 BuildSingleCopyAssign(Sema
&S
, SourceLocation Loc
, QualType T
,
5029 Expr
*To
, Expr
*From
,
5030 bool CopyingBaseSubobject
, unsigned Depth
= 0) {
5031 // C++0x [class.copy]p30:
5032 // Each subobject is assigned in the manner appropriate to its type:
5034 // - if the subobject is of class type, the copy assignment operator
5035 // for the class is used (as if by explicit qualification; that is,
5036 // ignoring any possible virtual overriding functions in more derived
5038 if (const RecordType
*RecordTy
= T
->getAs
<RecordType
>()) {
5039 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
5041 // Look for operator=.
5042 DeclarationName Name
5043 = S
.Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
5044 LookupResult
OpLookup(S
, Name
, Loc
, Sema::LookupOrdinaryName
);
5045 S
.LookupQualifiedName(OpLookup
, ClassDecl
, false);
5047 // Filter out any result that isn't a copy-assignment operator.
5048 LookupResult::Filter F
= OpLookup
.makeFilter();
5049 while (F
.hasNext()) {
5050 NamedDecl
*D
= F
.next();
5051 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
))
5052 if (Method
->isCopyAssignmentOperator())
5059 // Suppress the protected check (C++ [class.protected]) for each of the
5060 // assignment operators we found. This strange dance is required when
5061 // we're assigning via a base classes's copy-assignment operator. To
5062 // ensure that we're getting the right base class subobject (without
5063 // ambiguities), we need to cast "this" to that subobject type; to
5064 // ensure that we don't go through the virtual call mechanism, we need
5065 // to qualify the operator= name with the base class (see below). However,
5066 // this means that if the base class has a protected copy assignment
5067 // operator, the protected member access check will fail. So, we
5068 // rewrite "protected" access to "public" access in this case, since we
5069 // know by construction that we're calling from a derived class.
5070 if (CopyingBaseSubobject
) {
5071 for (LookupResult::iterator L
= OpLookup
.begin(), LEnd
= OpLookup
.end();
5073 if (L
.getAccess() == AS_protected
)
5074 L
.setAccess(AS_public
);
5078 // Create the nested-name-specifier that will be used to qualify the
5079 // reference to operator=; this is required to suppress the virtual
5083 SS
.setScopeRep(NestedNameSpecifier::Create(S
.Context
, 0, false,
5086 // Create the reference to operator=.
5087 ExprResult OpEqualRef
5088 = S
.BuildMemberReferenceExpr(To
, T
, Loc
, /*isArrow=*/false, SS
,
5089 /*FirstQualifierInScope=*/0, OpLookup
,
5091 /*SuppressQualifierCheck=*/true);
5092 if (OpEqualRef
.isInvalid())
5095 // Build the call to the assignment operator.
5097 ExprResult Call
= S
.BuildCallToMemberFunction(/*Scope=*/0,
5098 OpEqualRef
.takeAs
<Expr
>(),
5099 Loc
, &From
, 1, Loc
);
5100 if (Call
.isInvalid())
5103 return S
.Owned(Call
.takeAs
<Stmt
>());
5106 // - if the subobject is of scalar type, the built-in assignment
5107 // operator is used.
5108 const ConstantArrayType
*ArrayTy
= S
.Context
.getAsConstantArrayType(T
);
5110 ExprResult Assignment
= S
.CreateBuiltinBinOp(Loc
, BO_Assign
, To
, From
);
5111 if (Assignment
.isInvalid())
5114 return S
.Owned(Assignment
.takeAs
<Stmt
>());
5117 // - if the subobject is an array, each element is assigned, in the
5118 // manner appropriate to the element type;
5120 // Construct a loop over the array bounds, e.g.,
5122 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
5124 // that will copy each of the array elements.
5125 QualType SizeType
= S
.Context
.getSizeType();
5127 // Create the iteration variable.
5128 IdentifierInfo
*IterationVarName
= 0;
5130 llvm::SmallString
<8> Str
;
5131 llvm::raw_svector_ostream
OS(Str
);
5132 OS
<< "__i" << Depth
;
5133 IterationVarName
= &S
.Context
.Idents
.get(OS
.str());
5135 VarDecl
*IterationVar
= VarDecl::Create(S
.Context
, S
.CurContext
, Loc
,
5136 IterationVarName
, SizeType
,
5137 S
.Context
.getTrivialTypeSourceInfo(SizeType
, Loc
),
5140 // Initialize the iteration variable to zero.
5141 llvm::APInt
Zero(S
.Context
.getTypeSize(SizeType
), 0);
5142 IterationVar
->setInit(IntegerLiteral::Create(S
.Context
, Zero
, SizeType
, Loc
));
5144 // Create a reference to the iteration variable; we'll use this several
5145 // times throughout.
5146 Expr
*IterationVarRef
5147 = S
.BuildDeclRefExpr(IterationVar
, SizeType
, VK_RValue
, Loc
).take();
5148 assert(IterationVarRef
&& "Reference to invented variable cannot fail!");
5150 // Create the DeclStmt that holds the iteration variable.
5151 Stmt
*InitStmt
= new (S
.Context
) DeclStmt(DeclGroupRef(IterationVar
),Loc
,Loc
);
5153 // Create the comparison against the array bound.
5155 = ArrayTy
->getSize().zextOrTrunc(S
.Context
.getTypeSize(SizeType
));
5157 = new (S
.Context
) BinaryOperator(IterationVarRef
,
5158 IntegerLiteral::Create(S
.Context
, Upper
, SizeType
, Loc
),
5159 BO_NE
, S
.Context
.BoolTy
,
5160 VK_RValue
, OK_Ordinary
, Loc
);
5162 // Create the pre-increment of the iteration variable.
5164 = new (S
.Context
) UnaryOperator(IterationVarRef
, UO_PreInc
, SizeType
,
5165 VK_LValue
, OK_Ordinary
, Loc
);
5167 // Subscript the "from" and "to" expressions with the iteration variable.
5168 From
= AssertSuccess(S
.CreateBuiltinArraySubscriptExpr(From
, Loc
,
5169 IterationVarRef
, Loc
));
5170 To
= AssertSuccess(S
.CreateBuiltinArraySubscriptExpr(To
, Loc
,
5171 IterationVarRef
, Loc
));
5173 // Build the copy for an individual element of the array.
5174 StmtResult Copy
= BuildSingleCopyAssign(S
, Loc
, ArrayTy
->getElementType(),
5175 To
, From
, CopyingBaseSubobject
,
5177 if (Copy
.isInvalid())
5180 // Construct the loop that copies all elements of this array.
5181 return S
.ActOnForStmt(Loc
, Loc
, InitStmt
,
5182 S
.MakeFullExpr(Comparison
),
5183 0, S
.MakeFullExpr(Increment
),
5187 /// \brief Determine whether the given class has a copy assignment operator
5188 /// that accepts a const-qualified argument.
5189 static bool hasConstCopyAssignment(Sema
&S
, const CXXRecordDecl
*CClass
) {
5190 CXXRecordDecl
*Class
= const_cast<CXXRecordDecl
*>(CClass
);
5192 if (!Class
->hasDeclaredCopyAssignment())
5193 S
.DeclareImplicitCopyAssignment(Class
);
5195 QualType ClassType
= S
.Context
.getCanonicalType(S
.Context
.getTypeDeclType(Class
));
5196 DeclarationName OpName
5197 = S
.Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
5199 DeclContext::lookup_const_iterator Op
, OpEnd
;
5200 for (llvm::tie(Op
, OpEnd
) = Class
->lookup(OpName
); Op
!= OpEnd
; ++Op
) {
5201 // C++ [class.copy]p9:
5202 // A user-declared copy assignment operator is a non-static non-template
5203 // member function of class X with exactly one parameter of type X, X&,
5204 // const X&, volatile X& or const volatile X&.
5205 const CXXMethodDecl
* Method
= dyn_cast
<CXXMethodDecl
>(*Op
);
5209 if (Method
->isStatic())
5211 if (Method
->getPrimaryTemplate())
5213 const FunctionProtoType
*FnType
=
5214 Method
->getType()->getAs
<FunctionProtoType
>();
5215 assert(FnType
&& "Overloaded operator has no prototype.");
5216 // Don't assert on this; an invalid decl might have been left in the AST.
5217 if (FnType
->getNumArgs() != 1 || FnType
->isVariadic())
5219 bool AcceptsConst
= true;
5220 QualType ArgType
= FnType
->getArgType(0);
5221 if (const LValueReferenceType
*Ref
= ArgType
->getAs
<LValueReferenceType
>()){
5222 ArgType
= Ref
->getPointeeType();
5223 // Is it a non-const lvalue reference?
5224 if (!ArgType
.isConstQualified())
5225 AcceptsConst
= false;
5227 if (!S
.Context
.hasSameUnqualifiedType(ArgType
, ClassType
))
5230 // We have a single argument of type cv X or cv X&, i.e. we've found the
5231 // copy assignment operator. Return whether it accepts const arguments.
5232 return AcceptsConst
;
5234 assert(Class
->isInvalidDecl() &&
5235 "No copy assignment operator declared in valid code.");
5239 CXXMethodDecl
*Sema::DeclareImplicitCopyAssignment(CXXRecordDecl
*ClassDecl
) {
5240 // Note: The following rules are largely analoguous to the copy
5241 // constructor rules. Note that virtual bases are not taken into account
5242 // for determining the argument type of the operator. Note also that
5243 // operators taking an object instead of a reference are allowed.
5246 // C++ [class.copy]p10:
5247 // If the class definition does not explicitly declare a copy
5248 // assignment operator, one is declared implicitly.
5249 // The implicitly-defined copy assignment operator for a class X
5250 // will have the form
5252 // X& X::operator=(const X&)
5255 bool HasConstCopyAssignment
= true;
5257 // -- each direct base class B of X has a copy assignment operator
5258 // whose parameter is of type const B&, const volatile B& or B,
5260 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
5261 BaseEnd
= ClassDecl
->bases_end();
5262 HasConstCopyAssignment
&& Base
!= BaseEnd
; ++Base
) {
5263 assert(!Base
->getType()->isDependentType() &&
5264 "Cannot generate implicit members for class with dependent bases.");
5265 const CXXRecordDecl
*BaseClassDecl
5266 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
5267 HasConstCopyAssignment
= hasConstCopyAssignment(*this, BaseClassDecl
);
5270 // -- for all the nonstatic data members of X that are of a class
5271 // type M (or array thereof), each such class type has a copy
5272 // assignment operator whose parameter is of type const M&,
5273 // const volatile M& or M.
5274 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
5275 FieldEnd
= ClassDecl
->field_end();
5276 HasConstCopyAssignment
&& Field
!= FieldEnd
;
5278 QualType FieldType
= Context
.getBaseElementType((*Field
)->getType());
5279 if (const RecordType
*FieldClassType
= FieldType
->getAs
<RecordType
>()) {
5280 const CXXRecordDecl
*FieldClassDecl
5281 = cast
<CXXRecordDecl
>(FieldClassType
->getDecl());
5282 HasConstCopyAssignment
= hasConstCopyAssignment(*this, FieldClassDecl
);
5286 // Otherwise, the implicitly declared copy assignment operator will
5289 // X& X::operator=(X&)
5290 QualType ArgType
= Context
.getTypeDeclType(ClassDecl
);
5291 QualType RetType
= Context
.getLValueReferenceType(ArgType
);
5292 if (HasConstCopyAssignment
)
5293 ArgType
= ArgType
.withConst();
5294 ArgType
= Context
.getLValueReferenceType(ArgType
);
5296 // C++ [except.spec]p14:
5297 // An implicitly declared special member function (Clause 12) shall have an
5298 // exception-specification. [...]
5299 ImplicitExceptionSpecification
ExceptSpec(Context
);
5300 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
5301 BaseEnd
= ClassDecl
->bases_end();
5302 Base
!= BaseEnd
; ++Base
) {
5303 CXXRecordDecl
*BaseClassDecl
5304 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
5306 if (!BaseClassDecl
->hasDeclaredCopyAssignment())
5307 DeclareImplicitCopyAssignment(BaseClassDecl
);
5309 if (CXXMethodDecl
*CopyAssign
5310 = BaseClassDecl
->getCopyAssignmentOperator(HasConstCopyAssignment
))
5311 ExceptSpec
.CalledDecl(CopyAssign
);
5313 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
5314 FieldEnd
= ClassDecl
->field_end();
5317 QualType FieldType
= Context
.getBaseElementType((*Field
)->getType());
5318 if (const RecordType
*FieldClassType
= FieldType
->getAs
<RecordType
>()) {
5319 CXXRecordDecl
*FieldClassDecl
5320 = cast
<CXXRecordDecl
>(FieldClassType
->getDecl());
5322 if (!FieldClassDecl
->hasDeclaredCopyAssignment())
5323 DeclareImplicitCopyAssignment(FieldClassDecl
);
5325 if (CXXMethodDecl
*CopyAssign
5326 = FieldClassDecl
->getCopyAssignmentOperator(HasConstCopyAssignment
))
5327 ExceptSpec
.CalledDecl(CopyAssign
);
5331 // An implicitly-declared copy assignment operator is an inline public
5332 // member of its class.
5333 FunctionProtoType::ExtProtoInfo EPI
;
5334 EPI
.HasExceptionSpec
= ExceptSpec
.hasExceptionSpecification();
5335 EPI
.HasAnyExceptionSpec
= ExceptSpec
.hasAnyExceptionSpecification();
5336 EPI
.NumExceptions
= ExceptSpec
.size();
5337 EPI
.Exceptions
= ExceptSpec
.data();
5338 DeclarationName Name
= Context
.DeclarationNames
.getCXXOperatorName(OO_Equal
);
5339 DeclarationNameInfo
NameInfo(Name
, ClassDecl
->getLocation());
5340 CXXMethodDecl
*CopyAssignment
5341 = CXXMethodDecl::Create(Context
, ClassDecl
, NameInfo
,
5342 Context
.getFunctionType(RetType
, &ArgType
, 1, EPI
),
5343 /*TInfo=*/0, /*isStatic=*/false,
5344 /*StorageClassAsWritten=*/SC_None
,
5346 CopyAssignment
->setAccess(AS_public
);
5347 CopyAssignment
->setImplicit();
5348 CopyAssignment
->setTrivial(ClassDecl
->hasTrivialCopyAssignment());
5350 // Add the parameter to the operator.
5351 ParmVarDecl
*FromParam
= ParmVarDecl::Create(Context
, CopyAssignment
,
5352 ClassDecl
->getLocation(),
5354 ArgType
, /*TInfo=*/0,
5357 CopyAssignment
->setParams(&FromParam
, 1);
5359 // Note that we have added this copy-assignment operator.
5360 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared
;
5362 if (Scope
*S
= getScopeForContext(ClassDecl
))
5363 PushOnScopeChains(CopyAssignment
, S
, false);
5364 ClassDecl
->addDecl(CopyAssignment
);
5366 AddOverriddenMethods(ClassDecl
, CopyAssignment
);
5367 return CopyAssignment
;
5370 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation
,
5371 CXXMethodDecl
*CopyAssignOperator
) {
5372 assert((CopyAssignOperator
->isImplicit() &&
5373 CopyAssignOperator
->isOverloadedOperator() &&
5374 CopyAssignOperator
->getOverloadedOperator() == OO_Equal
&&
5375 !CopyAssignOperator
->isUsed(false)) &&
5376 "DefineImplicitCopyAssignment called for wrong function");
5378 CXXRecordDecl
*ClassDecl
= CopyAssignOperator
->getParent();
5380 if (ClassDecl
->isInvalidDecl() || CopyAssignOperator
->isInvalidDecl()) {
5381 CopyAssignOperator
->setInvalidDecl();
5385 CopyAssignOperator
->setUsed();
5387 ImplicitlyDefinedFunctionScope
Scope(*this, CopyAssignOperator
);
5388 DiagnosticErrorTrap
Trap(Diags
);
5390 // C++0x [class.copy]p30:
5391 // The implicitly-defined or explicitly-defaulted copy assignment operator
5392 // for a non-union class X performs memberwise copy assignment of its
5393 // subobjects. The direct base classes of X are assigned first, in the
5394 // order of their declaration in the base-specifier-list, and then the
5395 // immediate non-static data members of X are assigned, in the order in
5396 // which they were declared in the class definition.
5398 // The statements that form the synthesized function body.
5399 ASTOwningVector
<Stmt
*> Statements(*this);
5401 // The parameter for the "other" object, which we are copying from.
5402 ParmVarDecl
*Other
= CopyAssignOperator
->getParamDecl(0);
5403 Qualifiers OtherQuals
= Other
->getType().getQualifiers();
5404 QualType OtherRefType
= Other
->getType();
5405 if (const LValueReferenceType
*OtherRef
5406 = OtherRefType
->getAs
<LValueReferenceType
>()) {
5407 OtherRefType
= OtherRef
->getPointeeType();
5408 OtherQuals
= OtherRefType
.getQualifiers();
5411 // Our location for everything implicitly-generated.
5412 SourceLocation Loc
= CopyAssignOperator
->getLocation();
5414 // Construct a reference to the "other" object. We'll be using this
5415 // throughout the generated ASTs.
5416 Expr
*OtherRef
= BuildDeclRefExpr(Other
, OtherRefType
, VK_LValue
, Loc
).take();
5417 assert(OtherRef
&& "Reference to parameter cannot fail!");
5419 // Construct the "this" pointer. We'll be using this throughout the generated
5421 Expr
*This
= ActOnCXXThis(Loc
).takeAs
<Expr
>();
5422 assert(This
&& "Reference to this cannot fail!");
5424 // Assign base classes.
5425 bool Invalid
= false;
5426 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
5427 E
= ClassDecl
->bases_end(); Base
!= E
; ++Base
) {
5428 // Form the assignment:
5429 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
5430 QualType BaseType
= Base
->getType().getUnqualifiedType();
5431 if (!BaseType
->isRecordType()) {
5436 CXXCastPath BasePath
;
5437 BasePath
.push_back(Base
);
5439 // Construct the "from" expression, which is an implicit cast to the
5440 // appropriately-qualified base type.
5441 Expr
*From
= OtherRef
;
5442 ImpCastExprToType(From
, Context
.getQualifiedType(BaseType
, OtherQuals
),
5443 CK_UncheckedDerivedToBase
,
5444 VK_LValue
, &BasePath
);
5446 // Dereference "this".
5447 ExprResult To
= CreateBuiltinUnaryOp(Loc
, UO_Deref
, This
);
5449 // Implicitly cast "this" to the appropriately-qualified base type.
5450 Expr
*ToE
= To
.takeAs
<Expr
>();
5451 ImpCastExprToType(ToE
,
5452 Context
.getCVRQualifiedType(BaseType
,
5453 CopyAssignOperator
->getTypeQualifiers()),
5454 CK_UncheckedDerivedToBase
,
5455 VK_LValue
, &BasePath
);
5459 StmtResult Copy
= BuildSingleCopyAssign(*this, Loc
, BaseType
,
5461 /*CopyingBaseSubobject=*/true);
5462 if (Copy
.isInvalid()) {
5463 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5464 << CXXCopyAssignment
<< Context
.getTagDeclType(ClassDecl
);
5465 CopyAssignOperator
->setInvalidDecl();
5469 // Success! Record the copy.
5470 Statements
.push_back(Copy
.takeAs
<Expr
>());
5473 // \brief Reference to the __builtin_memcpy function.
5474 Expr
*BuiltinMemCpyRef
= 0;
5475 // \brief Reference to the __builtin_objc_memmove_collectable function.
5476 Expr
*CollectableMemCpyRef
= 0;
5478 // Assign non-static members.
5479 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
5480 FieldEnd
= ClassDecl
->field_end();
5481 Field
!= FieldEnd
; ++Field
) {
5482 // Check for members of reference type; we can't copy those.
5483 if (Field
->getType()->isReferenceType()) {
5484 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
5485 << Context
.getTagDeclType(ClassDecl
) << 0 << Field
->getDeclName();
5486 Diag(Field
->getLocation(), diag::note_declared_at
);
5487 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5488 << CXXCopyAssignment
<< Context
.getTagDeclType(ClassDecl
);
5493 // Check for members of const-qualified, non-class type.
5494 QualType BaseType
= Context
.getBaseElementType(Field
->getType());
5495 if (!BaseType
->getAs
<RecordType
>() && BaseType
.isConstQualified()) {
5496 Diag(ClassDecl
->getLocation(), diag::err_uninitialized_member_for_assign
)
5497 << Context
.getTagDeclType(ClassDecl
) << 1 << Field
->getDeclName();
5498 Diag(Field
->getLocation(), diag::note_declared_at
);
5499 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5500 << CXXCopyAssignment
<< Context
.getTagDeclType(ClassDecl
);
5505 QualType FieldType
= Field
->getType().getNonReferenceType();
5506 if (FieldType
->isIncompleteArrayType()) {
5507 assert(ClassDecl
->hasFlexibleArrayMember() &&
5508 "Incomplete array type is not valid");
5512 // Build references to the field in the object we're copying from and to.
5513 CXXScopeSpec SS
; // Intentionally empty
5514 LookupResult
MemberLookup(*this, Field
->getDeclName(), Loc
,
5516 MemberLookup
.addDecl(*Field
);
5517 MemberLookup
.resolveKind();
5518 ExprResult From
= BuildMemberReferenceExpr(OtherRef
, OtherRefType
,
5519 Loc
, /*IsArrow=*/false,
5520 SS
, 0, MemberLookup
, 0);
5521 ExprResult To
= BuildMemberReferenceExpr(This
, This
->getType(),
5522 Loc
, /*IsArrow=*/true,
5523 SS
, 0, MemberLookup
, 0);
5524 assert(!From
.isInvalid() && "Implicit field reference cannot fail");
5525 assert(!To
.isInvalid() && "Implicit field reference cannot fail");
5527 // If the field should be copied with __builtin_memcpy rather than via
5528 // explicit assignments, do so. This optimization only applies for arrays
5529 // of scalars and arrays of class type with trivial copy-assignment
5531 if (FieldType
->isArrayType() &&
5532 (!BaseType
->isRecordType() ||
5533 cast
<CXXRecordDecl
>(BaseType
->getAs
<RecordType
>()->getDecl())
5534 ->hasTrivialCopyAssignment())) {
5535 // Compute the size of the memory buffer to be copied.
5536 QualType SizeType
= Context
.getSizeType();
5537 llvm::APInt
Size(Context
.getTypeSize(SizeType
),
5538 Context
.getTypeSizeInChars(BaseType
).getQuantity());
5539 for (const ConstantArrayType
*Array
5540 = Context
.getAsConstantArrayType(FieldType
);
5542 Array
= Context
.getAsConstantArrayType(Array
->getElementType())) {
5543 llvm::APInt ArraySize
5544 = Array
->getSize().zextOrTrunc(Size
.getBitWidth());
5548 // Take the address of the field references for "from" and "to".
5549 From
= CreateBuiltinUnaryOp(Loc
, UO_AddrOf
, From
.get());
5550 To
= CreateBuiltinUnaryOp(Loc
, UO_AddrOf
, To
.get());
5552 bool NeedsCollectableMemCpy
=
5553 (BaseType
->isRecordType() &&
5554 BaseType
->getAs
<RecordType
>()->getDecl()->hasObjectMember());
5556 if (NeedsCollectableMemCpy
) {
5557 if (!CollectableMemCpyRef
) {
5558 // Create a reference to the __builtin_objc_memmove_collectable function.
5559 LookupResult
R(*this,
5560 &Context
.Idents
.get("__builtin_objc_memmove_collectable"),
5561 Loc
, LookupOrdinaryName
);
5562 LookupName(R
, TUScope
, true);
5564 FunctionDecl
*CollectableMemCpy
= R
.getAsSingle
<FunctionDecl
>();
5565 if (!CollectableMemCpy
) {
5566 // Something went horribly wrong earlier, and we will have
5567 // complained about it.
5572 CollectableMemCpyRef
= BuildDeclRefExpr(CollectableMemCpy
,
5573 CollectableMemCpy
->getType(),
5574 VK_LValue
, Loc
, 0).take();
5575 assert(CollectableMemCpyRef
&& "Builtin reference cannot fail");
5578 // Create a reference to the __builtin_memcpy builtin function.
5579 else if (!BuiltinMemCpyRef
) {
5580 LookupResult
R(*this, &Context
.Idents
.get("__builtin_memcpy"), Loc
,
5581 LookupOrdinaryName
);
5582 LookupName(R
, TUScope
, true);
5584 FunctionDecl
*BuiltinMemCpy
= R
.getAsSingle
<FunctionDecl
>();
5585 if (!BuiltinMemCpy
) {
5586 // Something went horribly wrong earlier, and we will have complained
5592 BuiltinMemCpyRef
= BuildDeclRefExpr(BuiltinMemCpy
,
5593 BuiltinMemCpy
->getType(),
5594 VK_LValue
, Loc
, 0).take();
5595 assert(BuiltinMemCpyRef
&& "Builtin reference cannot fail");
5598 ASTOwningVector
<Expr
*> CallArgs(*this);
5599 CallArgs
.push_back(To
.takeAs
<Expr
>());
5600 CallArgs
.push_back(From
.takeAs
<Expr
>());
5601 CallArgs
.push_back(IntegerLiteral::Create(Context
, Size
, SizeType
, Loc
));
5602 ExprResult Call
= ExprError();
5603 if (NeedsCollectableMemCpy
)
5604 Call
= ActOnCallExpr(/*Scope=*/0,
5605 CollectableMemCpyRef
,
5606 Loc
, move_arg(CallArgs
),
5609 Call
= ActOnCallExpr(/*Scope=*/0,
5611 Loc
, move_arg(CallArgs
),
5614 assert(!Call
.isInvalid() && "Call to __builtin_memcpy cannot fail!");
5615 Statements
.push_back(Call
.takeAs
<Expr
>());
5619 // Build the copy of this field.
5620 StmtResult Copy
= BuildSingleCopyAssign(*this, Loc
, FieldType
,
5621 To
.get(), From
.get(),
5622 /*CopyingBaseSubobject=*/false);
5623 if (Copy
.isInvalid()) {
5624 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5625 << CXXCopyAssignment
<< Context
.getTagDeclType(ClassDecl
);
5626 CopyAssignOperator
->setInvalidDecl();
5630 // Success! Record the copy.
5631 Statements
.push_back(Copy
.takeAs
<Stmt
>());
5635 // Add a "return *this;"
5636 ExprResult ThisObj
= CreateBuiltinUnaryOp(Loc
, UO_Deref
, This
);
5638 StmtResult Return
= ActOnReturnStmt(Loc
, ThisObj
.get());
5639 if (Return
.isInvalid())
5642 Statements
.push_back(Return
.takeAs
<Stmt
>());
5644 if (Trap
.hasErrorOccurred()) {
5645 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5646 << CXXCopyAssignment
<< Context
.getTagDeclType(ClassDecl
);
5653 CopyAssignOperator
->setInvalidDecl();
5657 StmtResult Body
= ActOnCompoundStmt(Loc
, Loc
, move_arg(Statements
),
5658 /*isStmtExpr=*/false);
5659 assert(!Body
.isInvalid() && "Compound statement creation cannot fail");
5660 CopyAssignOperator
->setBody(Body
.takeAs
<Stmt
>());
5663 CXXConstructorDecl
*Sema::DeclareImplicitCopyConstructor(
5664 CXXRecordDecl
*ClassDecl
) {
5665 // C++ [class.copy]p4:
5666 // If the class definition does not explicitly declare a copy
5667 // constructor, one is declared implicitly.
5669 // C++ [class.copy]p5:
5670 // The implicitly-declared copy constructor for a class X will
5676 bool HasConstCopyConstructor
= true;
5678 // -- each direct or virtual base class B of X has a copy
5679 // constructor whose first parameter is of type const B& or
5680 // const volatile B&, and
5681 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
5682 BaseEnd
= ClassDecl
->bases_end();
5683 HasConstCopyConstructor
&& Base
!= BaseEnd
;
5685 // Virtual bases are handled below.
5686 if (Base
->isVirtual())
5689 CXXRecordDecl
*BaseClassDecl
5690 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
5691 if (!BaseClassDecl
->hasDeclaredCopyConstructor())
5692 DeclareImplicitCopyConstructor(BaseClassDecl
);
5694 HasConstCopyConstructor
5695 = BaseClassDecl
->hasConstCopyConstructor(Context
);
5698 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->vbases_begin(),
5699 BaseEnd
= ClassDecl
->vbases_end();
5700 HasConstCopyConstructor
&& Base
!= BaseEnd
;
5702 CXXRecordDecl
*BaseClassDecl
5703 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
5704 if (!BaseClassDecl
->hasDeclaredCopyConstructor())
5705 DeclareImplicitCopyConstructor(BaseClassDecl
);
5707 HasConstCopyConstructor
5708 = BaseClassDecl
->hasConstCopyConstructor(Context
);
5711 // -- for all the nonstatic data members of X that are of a
5712 // class type M (or array thereof), each such class type
5713 // has a copy constructor whose first parameter is of type
5714 // const M& or const volatile M&.
5715 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
5716 FieldEnd
= ClassDecl
->field_end();
5717 HasConstCopyConstructor
&& Field
!= FieldEnd
;
5719 QualType FieldType
= Context
.getBaseElementType((*Field
)->getType());
5720 if (const RecordType
*FieldClassType
= FieldType
->getAs
<RecordType
>()) {
5721 CXXRecordDecl
*FieldClassDecl
5722 = cast
<CXXRecordDecl
>(FieldClassType
->getDecl());
5723 if (!FieldClassDecl
->hasDeclaredCopyConstructor())
5724 DeclareImplicitCopyConstructor(FieldClassDecl
);
5726 HasConstCopyConstructor
5727 = FieldClassDecl
->hasConstCopyConstructor(Context
);
5731 // Otherwise, the implicitly declared copy constructor will have
5735 QualType ClassType
= Context
.getTypeDeclType(ClassDecl
);
5736 QualType ArgType
= ClassType
;
5737 if (HasConstCopyConstructor
)
5738 ArgType
= ArgType
.withConst();
5739 ArgType
= Context
.getLValueReferenceType(ArgType
);
5741 // C++ [except.spec]p14:
5742 // An implicitly declared special member function (Clause 12) shall have an
5743 // exception-specification. [...]
5744 ImplicitExceptionSpecification
ExceptSpec(Context
);
5745 unsigned Quals
= HasConstCopyConstructor
? Qualifiers::Const
: 0;
5746 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->bases_begin(),
5747 BaseEnd
= ClassDecl
->bases_end();
5750 // Virtual bases are handled below.
5751 if (Base
->isVirtual())
5754 CXXRecordDecl
*BaseClassDecl
5755 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
5756 if (!BaseClassDecl
->hasDeclaredCopyConstructor())
5757 DeclareImplicitCopyConstructor(BaseClassDecl
);
5759 if (CXXConstructorDecl
*CopyConstructor
5760 = BaseClassDecl
->getCopyConstructor(Context
, Quals
))
5761 ExceptSpec
.CalledDecl(CopyConstructor
);
5763 for (CXXRecordDecl::base_class_iterator Base
= ClassDecl
->vbases_begin(),
5764 BaseEnd
= ClassDecl
->vbases_end();
5767 CXXRecordDecl
*BaseClassDecl
5768 = cast
<CXXRecordDecl
>(Base
->getType()->getAs
<RecordType
>()->getDecl());
5769 if (!BaseClassDecl
->hasDeclaredCopyConstructor())
5770 DeclareImplicitCopyConstructor(BaseClassDecl
);
5772 if (CXXConstructorDecl
*CopyConstructor
5773 = BaseClassDecl
->getCopyConstructor(Context
, Quals
))
5774 ExceptSpec
.CalledDecl(CopyConstructor
);
5776 for (CXXRecordDecl::field_iterator Field
= ClassDecl
->field_begin(),
5777 FieldEnd
= ClassDecl
->field_end();
5780 QualType FieldType
= Context
.getBaseElementType((*Field
)->getType());
5781 if (const RecordType
*FieldClassType
= FieldType
->getAs
<RecordType
>()) {
5782 CXXRecordDecl
*FieldClassDecl
5783 = cast
<CXXRecordDecl
>(FieldClassType
->getDecl());
5784 if (!FieldClassDecl
->hasDeclaredCopyConstructor())
5785 DeclareImplicitCopyConstructor(FieldClassDecl
);
5787 if (CXXConstructorDecl
*CopyConstructor
5788 = FieldClassDecl
->getCopyConstructor(Context
, Quals
))
5789 ExceptSpec
.CalledDecl(CopyConstructor
);
5793 // An implicitly-declared copy constructor is an inline public
5794 // member of its class.
5795 FunctionProtoType::ExtProtoInfo EPI
;
5796 EPI
.HasExceptionSpec
= ExceptSpec
.hasExceptionSpecification();
5797 EPI
.HasAnyExceptionSpec
= ExceptSpec
.hasAnyExceptionSpecification();
5798 EPI
.NumExceptions
= ExceptSpec
.size();
5799 EPI
.Exceptions
= ExceptSpec
.data();
5800 DeclarationName Name
5801 = Context
.DeclarationNames
.getCXXConstructorName(
5802 Context
.getCanonicalType(ClassType
));
5803 DeclarationNameInfo
NameInfo(Name
, ClassDecl
->getLocation());
5804 CXXConstructorDecl
*CopyConstructor
5805 = CXXConstructorDecl::Create(Context
, ClassDecl
, NameInfo
,
5806 Context
.getFunctionType(Context
.VoidTy
,
5809 /*isExplicit=*/false,
5811 /*isImplicitlyDeclared=*/true);
5812 CopyConstructor
->setAccess(AS_public
);
5813 CopyConstructor
->setTrivial(ClassDecl
->hasTrivialCopyConstructor());
5815 // Note that we have declared this constructor.
5816 ++ASTContext::NumImplicitCopyConstructorsDeclared
;
5818 // Add the parameter to the constructor.
5819 ParmVarDecl
*FromParam
= ParmVarDecl::Create(Context
, CopyConstructor
,
5820 ClassDecl
->getLocation(),
5821 /*IdentifierInfo=*/0,
5822 ArgType
, /*TInfo=*/0,
5825 CopyConstructor
->setParams(&FromParam
, 1);
5826 if (Scope
*S
= getScopeForContext(ClassDecl
))
5827 PushOnScopeChains(CopyConstructor
, S
, false);
5828 ClassDecl
->addDecl(CopyConstructor
);
5830 return CopyConstructor
;
5833 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation
,
5834 CXXConstructorDecl
*CopyConstructor
,
5835 unsigned TypeQuals
) {
5836 assert((CopyConstructor
->isImplicit() &&
5837 CopyConstructor
->isCopyConstructor(TypeQuals
) &&
5838 !CopyConstructor
->isUsed(false)) &&
5839 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
5841 CXXRecordDecl
*ClassDecl
= CopyConstructor
->getParent();
5842 assert(ClassDecl
&& "DefineImplicitCopyConstructor - invalid constructor");
5844 ImplicitlyDefinedFunctionScope
Scope(*this, CopyConstructor
);
5845 DiagnosticErrorTrap
Trap(Diags
);
5847 if (SetCtorInitializers(CopyConstructor
, 0, 0, /*AnyErrors=*/false) ||
5848 Trap
.hasErrorOccurred()) {
5849 Diag(CurrentLocation
, diag::note_member_synthesized_at
)
5850 << CXXCopyConstructor
<< Context
.getTagDeclType(ClassDecl
);
5851 CopyConstructor
->setInvalidDecl();
5853 CopyConstructor
->setBody(ActOnCompoundStmt(CopyConstructor
->getLocation(),
5854 CopyConstructor
->getLocation(),
5855 MultiStmtArg(*this, 0, 0),
5856 /*isStmtExpr=*/false)
5860 CopyConstructor
->setUsed();
5864 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc
, QualType DeclInitType
,
5865 CXXConstructorDecl
*Constructor
,
5866 MultiExprArg ExprArgs
,
5867 bool RequiresZeroInit
,
5868 unsigned ConstructKind
,
5869 SourceRange ParenRange
) {
5870 bool Elidable
= false;
5872 // C++0x [class.copy]p34:
5873 // When certain criteria are met, an implementation is allowed to
5874 // omit the copy/move construction of a class object, even if the
5875 // copy/move constructor and/or destructor for the object have
5876 // side effects. [...]
5877 // - when a temporary class object that has not been bound to a
5878 // reference (12.2) would be copied/moved to a class object
5879 // with the same cv-unqualified type, the copy/move operation
5880 // can be omitted by constructing the temporary object
5881 // directly into the target of the omitted copy/move
5882 if (ConstructKind
== CXXConstructExpr::CK_Complete
&&
5883 Constructor
->isCopyOrMoveConstructor() && ExprArgs
.size() >= 1) {
5884 Expr
*SubExpr
= ((Expr
**)ExprArgs
.get())[0];
5885 Elidable
= SubExpr
->isTemporaryObject(Context
, Constructor
->getParent());
5888 return BuildCXXConstructExpr(ConstructLoc
, DeclInitType
, Constructor
,
5889 Elidable
, move(ExprArgs
), RequiresZeroInit
,
5890 ConstructKind
, ParenRange
);
5893 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5894 /// including handling of its default argument expressions.
5896 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc
, QualType DeclInitType
,
5897 CXXConstructorDecl
*Constructor
, bool Elidable
,
5898 MultiExprArg ExprArgs
,
5899 bool RequiresZeroInit
,
5900 unsigned ConstructKind
,
5901 SourceRange ParenRange
) {
5902 unsigned NumExprs
= ExprArgs
.size();
5903 Expr
**Exprs
= (Expr
**)ExprArgs
.release();
5905 MarkDeclarationReferenced(ConstructLoc
, Constructor
);
5906 return Owned(CXXConstructExpr::Create(Context
, DeclInitType
, ConstructLoc
,
5907 Constructor
, Elidable
, Exprs
, NumExprs
,
5909 static_cast<CXXConstructExpr::ConstructionKind
>(ConstructKind
),
5913 bool Sema::InitializeVarWithConstructor(VarDecl
*VD
,
5914 CXXConstructorDecl
*Constructor
,
5915 MultiExprArg Exprs
) {
5916 // FIXME: Provide the correct paren SourceRange when available.
5917 ExprResult TempResult
=
5918 BuildCXXConstructExpr(VD
->getLocation(), VD
->getType(), Constructor
,
5919 move(Exprs
), false, CXXConstructExpr::CK_Complete
,
5921 if (TempResult
.isInvalid())
5924 Expr
*Temp
= TempResult
.takeAs
<Expr
>();
5925 CheckImplicitConversions(Temp
, VD
->getLocation());
5926 MarkDeclarationReferenced(VD
->getLocation(), Constructor
);
5927 Temp
= MaybeCreateExprWithCleanups(Temp
);
5933 void Sema::FinalizeVarWithDestructor(VarDecl
*VD
, const RecordType
*Record
) {
5934 CXXRecordDecl
*ClassDecl
= cast
<CXXRecordDecl
>(Record
->getDecl());
5935 if (!ClassDecl
->isInvalidDecl() && !VD
->isInvalidDecl() &&
5936 !ClassDecl
->hasTrivialDestructor() && !ClassDecl
->isDependentContext()) {
5937 CXXDestructorDecl
*Destructor
= LookupDestructor(ClassDecl
);
5938 MarkDeclarationReferenced(VD
->getLocation(), Destructor
);
5939 CheckDestructorAccess(VD
->getLocation(), Destructor
,
5940 PDiag(diag::err_access_dtor_var
)
5941 << VD
->getDeclName()
5944 // TODO: this should be re-enabled for static locals by !CXAAtExit
5945 if (!VD
->isInvalidDecl() && VD
->hasGlobalStorage() && !VD
->isStaticLocal())
5946 Diag(VD
->getLocation(), diag::warn_global_destructor
);
5950 /// AddCXXDirectInitializerToDecl - This action is called immediately after
5951 /// ActOnDeclarator, when a C++ direct initializer is present.
5952 /// e.g: "int x(1);"
5953 void Sema::AddCXXDirectInitializerToDecl(Decl
*RealDecl
,
5954 SourceLocation LParenLoc
,
5956 SourceLocation RParenLoc
) {
5957 assert(Exprs
.size() != 0 && Exprs
.get() && "missing expressions");
5959 // If there is no declaration, there was an error parsing it. Just ignore
5964 VarDecl
*VDecl
= dyn_cast
<VarDecl
>(RealDecl
);
5966 Diag(RealDecl
->getLocation(), diag::err_illegal_initializer
);
5967 RealDecl
->setInvalidDecl();
5971 // We will represent direct-initialization similarly to copy-initialization:
5972 // int x(1); -as-> int x = 1;
5973 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
5975 // Clients that want to distinguish between the two forms, can check for
5976 // direct initializer using VarDecl::hasCXXDirectInitializer().
5977 // A major benefit is that clients that don't particularly care about which
5978 // exactly form was it (like the CodeGen) can handle both cases without
5979 // special case code.
5982 // The form of initialization (using parentheses or '=') is generally
5983 // insignificant, but does matter when the entity being initialized has a
5986 if (!VDecl
->getType()->isDependentType() &&
5987 RequireCompleteType(VDecl
->getLocation(), VDecl
->getType(),
5988 diag::err_typecheck_decl_incomplete_type
)) {
5989 VDecl
->setInvalidDecl();
5993 // The variable can not have an abstract class type.
5994 if (RequireNonAbstractType(VDecl
->getLocation(), VDecl
->getType(),
5995 diag::err_abstract_type_in_decl
,
5996 AbstractVariableType
))
5997 VDecl
->setInvalidDecl();
6000 if ((Def
= VDecl
->getDefinition()) && Def
!= VDecl
) {
6001 Diag(VDecl
->getLocation(), diag::err_redefinition
)
6002 << VDecl
->getDeclName();
6003 Diag(Def
->getLocation(), diag::note_previous_definition
);
6004 VDecl
->setInvalidDecl();
6008 // C++ [class.static.data]p4
6009 // If a static data member is of const integral or const
6010 // enumeration type, its declaration in the class definition can
6011 // specify a constant-initializer which shall be an integral
6012 // constant expression (5.19). In that case, the member can appear
6013 // in integral constant expressions. The member shall still be
6014 // defined in a namespace scope if it is used in the program and the
6015 // namespace scope definition shall not contain an initializer.
6017 // We already performed a redefinition check above, but for static
6018 // data members we also need to check whether there was an in-class
6019 // declaration with an initializer.
6020 const VarDecl
* PrevInit
= 0;
6021 if (VDecl
->isStaticDataMember() && VDecl
->getAnyInitializer(PrevInit
)) {
6022 Diag(VDecl
->getLocation(), diag::err_redefinition
) << VDecl
->getDeclName();
6023 Diag(PrevInit
->getLocation(), diag::note_previous_definition
);
6027 bool IsDependent
= false;
6028 for (unsigned I
= 0, N
= Exprs
.size(); I
!= N
; ++I
) {
6029 if (DiagnoseUnexpandedParameterPack(Exprs
.get()[I
], UPPC_Expression
)) {
6030 VDecl
->setInvalidDecl();
6034 if (Exprs
.get()[I
]->isTypeDependent())
6038 // If either the declaration has a dependent type or if any of the
6039 // expressions is type-dependent, we represent the initialization
6040 // via a ParenListExpr for later use during template instantiation.
6041 if (VDecl
->getType()->isDependentType() || IsDependent
) {
6042 // Let clients know that initialization was done with a direct initializer.
6043 VDecl
->setCXXDirectInitializer(true);
6045 // Store the initialization expressions as a ParenListExpr.
6046 unsigned NumExprs
= Exprs
.size();
6047 VDecl
->setInit(new (Context
) ParenListExpr(Context
, LParenLoc
,
6048 (Expr
**)Exprs
.release(),
6049 NumExprs
, RParenLoc
));
6053 // Capture the variable that is being initialized and the style of
6055 InitializedEntity Entity
= InitializedEntity::InitializeVariable(VDecl
);
6057 // FIXME: Poor source location information.
6058 InitializationKind Kind
6059 = InitializationKind::CreateDirect(VDecl
->getLocation(),
6060 LParenLoc
, RParenLoc
);
6062 InitializationSequence
InitSeq(*this, Entity
, Kind
,
6063 Exprs
.get(), Exprs
.size());
6064 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, move(Exprs
));
6065 if (Result
.isInvalid()) {
6066 VDecl
->setInvalidDecl();
6070 CheckImplicitConversions(Result
.get(), LParenLoc
);
6072 Result
= MaybeCreateExprWithCleanups(Result
);
6073 VDecl
->setInit(Result
.takeAs
<Expr
>());
6074 VDecl
->setCXXDirectInitializer(true);
6076 CheckCompleteVariableDeclaration(VDecl
);
6079 /// \brief Given a constructor and the set of arguments provided for the
6080 /// constructor, convert the arguments and add any required default arguments
6081 /// to form a proper call to this constructor.
6083 /// \returns true if an error occurred, false otherwise.
6085 Sema::CompleteConstructorCall(CXXConstructorDecl
*Constructor
,
6086 MultiExprArg ArgsPtr
,
6088 ASTOwningVector
<Expr
*> &ConvertedArgs
) {
6089 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
6090 unsigned NumArgs
= ArgsPtr
.size();
6091 Expr
**Args
= (Expr
**)ArgsPtr
.get();
6093 const FunctionProtoType
*Proto
6094 = Constructor
->getType()->getAs
<FunctionProtoType
>();
6095 assert(Proto
&& "Constructor without a prototype?");
6096 unsigned NumArgsInProto
= Proto
->getNumArgs();
6098 // If too few arguments are available, we'll fill in the rest with defaults.
6099 if (NumArgs
< NumArgsInProto
)
6100 ConvertedArgs
.reserve(NumArgsInProto
);
6102 ConvertedArgs
.reserve(NumArgs
);
6104 VariadicCallType CallType
=
6105 Proto
->isVariadic() ? VariadicConstructor
: VariadicDoesNotApply
;
6106 llvm::SmallVector
<Expr
*, 8> AllArgs
;
6107 bool Invalid
= GatherArgumentsForCall(Loc
, Constructor
,
6108 Proto
, 0, Args
, NumArgs
, AllArgs
,
6110 for (unsigned i
=0, size
= AllArgs
.size(); i
< size
; i
++)
6111 ConvertedArgs
.push_back(AllArgs
[i
]);
6116 CheckOperatorNewDeleteDeclarationScope(Sema
&SemaRef
,
6117 const FunctionDecl
*FnDecl
) {
6118 const DeclContext
*DC
= FnDecl
->getDeclContext()->getRedeclContext();
6119 if (isa
<NamespaceDecl
>(DC
)) {
6120 return SemaRef
.Diag(FnDecl
->getLocation(),
6121 diag::err_operator_new_delete_declared_in_namespace
)
6122 << FnDecl
->getDeclName();
6125 if (isa
<TranslationUnitDecl
>(DC
) &&
6126 FnDecl
->getStorageClass() == SC_Static
) {
6127 return SemaRef
.Diag(FnDecl
->getLocation(),
6128 diag::err_operator_new_delete_declared_static
)
6129 << FnDecl
->getDeclName();
6136 CheckOperatorNewDeleteTypes(Sema
&SemaRef
, const FunctionDecl
*FnDecl
,
6137 CanQualType ExpectedResultType
,
6138 CanQualType ExpectedFirstParamType
,
6139 unsigned DependentParamTypeDiag
,
6140 unsigned InvalidParamTypeDiag
) {
6141 QualType ResultType
=
6142 FnDecl
->getType()->getAs
<FunctionType
>()->getResultType();
6144 // Check that the result type is not dependent.
6145 if (ResultType
->isDependentType())
6146 return SemaRef
.Diag(FnDecl
->getLocation(),
6147 diag::err_operator_new_delete_dependent_result_type
)
6148 << FnDecl
->getDeclName() << ExpectedResultType
;
6150 // Check that the result type is what we expect.
6151 if (SemaRef
.Context
.getCanonicalType(ResultType
) != ExpectedResultType
)
6152 return SemaRef
.Diag(FnDecl
->getLocation(),
6153 diag::err_operator_new_delete_invalid_result_type
)
6154 << FnDecl
->getDeclName() << ExpectedResultType
;
6156 // A function template must have at least 2 parameters.
6157 if (FnDecl
->getDescribedFunctionTemplate() && FnDecl
->getNumParams() < 2)
6158 return SemaRef
.Diag(FnDecl
->getLocation(),
6159 diag::err_operator_new_delete_template_too_few_parameters
)
6160 << FnDecl
->getDeclName();
6162 // The function decl must have at least 1 parameter.
6163 if (FnDecl
->getNumParams() == 0)
6164 return SemaRef
.Diag(FnDecl
->getLocation(),
6165 diag::err_operator_new_delete_too_few_parameters
)
6166 << FnDecl
->getDeclName();
6168 // Check the the first parameter type is not dependent.
6169 QualType FirstParamType
= FnDecl
->getParamDecl(0)->getType();
6170 if (FirstParamType
->isDependentType())
6171 return SemaRef
.Diag(FnDecl
->getLocation(), DependentParamTypeDiag
)
6172 << FnDecl
->getDeclName() << ExpectedFirstParamType
;
6174 // Check that the first parameter type is what we expect.
6175 if (SemaRef
.Context
.getCanonicalType(FirstParamType
).getUnqualifiedType() !=
6176 ExpectedFirstParamType
)
6177 return SemaRef
.Diag(FnDecl
->getLocation(), InvalidParamTypeDiag
)
6178 << FnDecl
->getDeclName() << ExpectedFirstParamType
;
6184 CheckOperatorNewDeclaration(Sema
&SemaRef
, const FunctionDecl
*FnDecl
) {
6185 // C++ [basic.stc.dynamic.allocation]p1:
6186 // A program is ill-formed if an allocation function is declared in a
6187 // namespace scope other than global scope or declared static in global
6189 if (CheckOperatorNewDeleteDeclarationScope(SemaRef
, FnDecl
))
6192 CanQualType SizeTy
=
6193 SemaRef
.Context
.getCanonicalType(SemaRef
.Context
.getSizeType());
6195 // C++ [basic.stc.dynamic.allocation]p1:
6196 // The return type shall be void*. The first parameter shall have type
6198 if (CheckOperatorNewDeleteTypes(SemaRef
, FnDecl
, SemaRef
.Context
.VoidPtrTy
,
6200 diag::err_operator_new_dependent_param_type
,
6201 diag::err_operator_new_param_type
))
6204 // C++ [basic.stc.dynamic.allocation]p1:
6205 // The first parameter shall not have an associated default argument.
6206 if (FnDecl
->getParamDecl(0)->hasDefaultArg())
6207 return SemaRef
.Diag(FnDecl
->getLocation(),
6208 diag::err_operator_new_default_arg
)
6209 << FnDecl
->getDeclName() << FnDecl
->getParamDecl(0)->getDefaultArgRange();
6215 CheckOperatorDeleteDeclaration(Sema
&SemaRef
, const FunctionDecl
*FnDecl
) {
6216 // C++ [basic.stc.dynamic.deallocation]p1:
6217 // A program is ill-formed if deallocation functions are declared in a
6218 // namespace scope other than global scope or declared static in global
6220 if (CheckOperatorNewDeleteDeclarationScope(SemaRef
, FnDecl
))
6223 // C++ [basic.stc.dynamic.deallocation]p2:
6224 // Each deallocation function shall return void and its first parameter
6226 if (CheckOperatorNewDeleteTypes(SemaRef
, FnDecl
, SemaRef
.Context
.VoidTy
,
6227 SemaRef
.Context
.VoidPtrTy
,
6228 diag::err_operator_delete_dependent_param_type
,
6229 diag::err_operator_delete_param_type
))
6235 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
6236 /// of this overloaded operator is well-formed. If so, returns false;
6237 /// otherwise, emits appropriate diagnostics and returns true.
6238 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl
*FnDecl
) {
6239 assert(FnDecl
&& FnDecl
->isOverloadedOperator() &&
6240 "Expected an overloaded operator declaration");
6242 OverloadedOperatorKind Op
= FnDecl
->getOverloadedOperator();
6244 // C++ [over.oper]p5:
6245 // The allocation and deallocation functions, operator new,
6246 // operator new[], operator delete and operator delete[], are
6247 // described completely in 3.7.3. The attributes and restrictions
6248 // found in the rest of this subclause do not apply to them unless
6249 // explicitly stated in 3.7.3.
6250 if (Op
== OO_Delete
|| Op
== OO_Array_Delete
)
6251 return CheckOperatorDeleteDeclaration(*this, FnDecl
);
6253 if (Op
== OO_New
|| Op
== OO_Array_New
)
6254 return CheckOperatorNewDeclaration(*this, FnDecl
);
6256 // C++ [over.oper]p6:
6257 // An operator function shall either be a non-static member
6258 // function or be a non-member function and have at least one
6259 // parameter whose type is a class, a reference to a class, an
6260 // enumeration, or a reference to an enumeration.
6261 if (CXXMethodDecl
*MethodDecl
= dyn_cast
<CXXMethodDecl
>(FnDecl
)) {
6262 if (MethodDecl
->isStatic())
6263 return Diag(FnDecl
->getLocation(),
6264 diag::err_operator_overload_static
) << FnDecl
->getDeclName();
6266 bool ClassOrEnumParam
= false;
6267 for (FunctionDecl::param_iterator Param
= FnDecl
->param_begin(),
6268 ParamEnd
= FnDecl
->param_end();
6269 Param
!= ParamEnd
; ++Param
) {
6270 QualType ParamType
= (*Param
)->getType().getNonReferenceType();
6271 if (ParamType
->isDependentType() || ParamType
->isRecordType() ||
6272 ParamType
->isEnumeralType()) {
6273 ClassOrEnumParam
= true;
6278 if (!ClassOrEnumParam
)
6279 return Diag(FnDecl
->getLocation(),
6280 diag::err_operator_overload_needs_class_or_enum
)
6281 << FnDecl
->getDeclName();
6284 // C++ [over.oper]p8:
6285 // An operator function cannot have default arguments (8.3.6),
6286 // except where explicitly stated below.
6288 // Only the function-call operator allows default arguments
6289 // (C++ [over.call]p1).
6290 if (Op
!= OO_Call
) {
6291 for (FunctionDecl::param_iterator Param
= FnDecl
->param_begin();
6292 Param
!= FnDecl
->param_end(); ++Param
) {
6293 if ((*Param
)->hasDefaultArg())
6294 return Diag((*Param
)->getLocation(),
6295 diag::err_operator_overload_default_arg
)
6296 << FnDecl
->getDeclName() << (*Param
)->getDefaultArgRange();
6300 static const bool OperatorUses
[NUM_OVERLOADED_OPERATORS
][3] = {
6301 { false, false, false }
6302 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
6303 , { Unary, Binary, MemberOnly }
6304 #include "clang/Basic/OperatorKinds.def"
6307 bool CanBeUnaryOperator
= OperatorUses
[Op
][0];
6308 bool CanBeBinaryOperator
= OperatorUses
[Op
][1];
6309 bool MustBeMemberOperator
= OperatorUses
[Op
][2];
6311 // C++ [over.oper]p8:
6312 // [...] Operator functions cannot have more or fewer parameters
6313 // than the number required for the corresponding operator, as
6314 // described in the rest of this subclause.
6315 unsigned NumParams
= FnDecl
->getNumParams()
6316 + (isa
<CXXMethodDecl
>(FnDecl
)? 1 : 0);
6317 if (Op
!= OO_Call
&&
6318 ((NumParams
== 1 && !CanBeUnaryOperator
) ||
6319 (NumParams
== 2 && !CanBeBinaryOperator
) ||
6320 (NumParams
< 1) || (NumParams
> 2))) {
6321 // We have the wrong number of parameters.
6323 if (CanBeUnaryOperator
&& CanBeBinaryOperator
) {
6324 ErrorKind
= 2; // 2 -> unary or binary.
6325 } else if (CanBeUnaryOperator
) {
6326 ErrorKind
= 0; // 0 -> unary
6328 assert(CanBeBinaryOperator
&&
6329 "All non-call overloaded operators are unary or binary!");
6330 ErrorKind
= 1; // 1 -> binary
6333 return Diag(FnDecl
->getLocation(), diag::err_operator_overload_must_be
)
6334 << FnDecl
->getDeclName() << NumParams
<< ErrorKind
;
6337 // Overloaded operators other than operator() cannot be variadic.
6338 if (Op
!= OO_Call
&&
6339 FnDecl
->getType()->getAs
<FunctionProtoType
>()->isVariadic()) {
6340 return Diag(FnDecl
->getLocation(), diag::err_operator_overload_variadic
)
6341 << FnDecl
->getDeclName();
6344 // Some operators must be non-static member functions.
6345 if (MustBeMemberOperator
&& !isa
<CXXMethodDecl
>(FnDecl
)) {
6346 return Diag(FnDecl
->getLocation(),
6347 diag::err_operator_overload_must_be_member
)
6348 << FnDecl
->getDeclName();
6351 // C++ [over.inc]p1:
6352 // The user-defined function called operator++ implements the
6353 // prefix and postfix ++ operator. If this function is a member
6354 // function with no parameters, or a non-member function with one
6355 // parameter of class or enumeration type, it defines the prefix
6356 // increment operator ++ for objects of that type. If the function
6357 // is a member function with one parameter (which shall be of type
6358 // int) or a non-member function with two parameters (the second
6359 // of which shall be of type int), it defines the postfix
6360 // increment operator ++ for objects of that type.
6361 if ((Op
== OO_PlusPlus
|| Op
== OO_MinusMinus
) && NumParams
== 2) {
6362 ParmVarDecl
*LastParam
= FnDecl
->getParamDecl(FnDecl
->getNumParams() - 1);
6363 bool ParamIsInt
= false;
6364 if (const BuiltinType
*BT
= LastParam
->getType()->getAs
<BuiltinType
>())
6365 ParamIsInt
= BT
->getKind() == BuiltinType::Int
;
6368 return Diag(LastParam
->getLocation(),
6369 diag::err_operator_overload_post_incdec_must_be_int
)
6370 << LastParam
->getType() << (Op
== OO_MinusMinus
);
6376 /// CheckLiteralOperatorDeclaration - Check whether the declaration
6377 /// of this literal operator function is well-formed. If so, returns
6378 /// false; otherwise, emits appropriate diagnostics and returns true.
6379 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl
*FnDecl
) {
6380 DeclContext
*DC
= FnDecl
->getDeclContext();
6381 Decl::Kind Kind
= DC
->getDeclKind();
6382 if (Kind
!= Decl::TranslationUnit
&& Kind
!= Decl::Namespace
&&
6383 Kind
!= Decl::LinkageSpec
) {
6384 Diag(FnDecl
->getLocation(), diag::err_literal_operator_outside_namespace
)
6385 << FnDecl
->getDeclName();
6391 // template <char...> type operator "" name() is the only valid template
6392 // signature, and the only valid signature with no parameters.
6393 if (FnDecl
->param_size() == 0) {
6394 if (FunctionTemplateDecl
*TpDecl
= FnDecl
->getDescribedFunctionTemplate()) {
6395 // Must have only one template parameter
6396 TemplateParameterList
*Params
= TpDecl
->getTemplateParameters();
6397 if (Params
->size() == 1) {
6398 NonTypeTemplateParmDecl
*PmDecl
=
6399 cast
<NonTypeTemplateParmDecl
>(Params
->getParam(0));
6401 // The template parameter must be a char parameter pack.
6402 if (PmDecl
&& PmDecl
->isTemplateParameterPack() &&
6403 Context
.hasSameType(PmDecl
->getType(), Context
.CharTy
))
6408 // Check the first parameter
6409 FunctionDecl::param_iterator Param
= FnDecl
->param_begin();
6411 QualType T
= (*Param
)->getType();
6413 // unsigned long long int, long double, and any character type are allowed
6414 // as the only parameters.
6415 if (Context
.hasSameType(T
, Context
.UnsignedLongLongTy
) ||
6416 Context
.hasSameType(T
, Context
.LongDoubleTy
) ||
6417 Context
.hasSameType(T
, Context
.CharTy
) ||
6418 Context
.hasSameType(T
, Context
.WCharTy
) ||
6419 Context
.hasSameType(T
, Context
.Char16Ty
) ||
6420 Context
.hasSameType(T
, Context
.Char32Ty
)) {
6421 if (++Param
== FnDecl
->param_end())
6423 goto FinishedParams
;
6426 // Otherwise it must be a pointer to const; let's strip those qualifiers.
6427 const PointerType
*PT
= T
->getAs
<PointerType
>();
6429 goto FinishedParams
;
6430 T
= PT
->getPointeeType();
6431 if (!T
.isConstQualified())
6432 goto FinishedParams
;
6433 T
= T
.getUnqualifiedType();
6435 // Move on to the second parameter;
6438 // If there is no second parameter, the first must be a const char *
6439 if (Param
== FnDecl
->param_end()) {
6440 if (Context
.hasSameType(T
, Context
.CharTy
))
6442 goto FinishedParams
;
6445 // const char *, const wchar_t*, const char16_t*, and const char32_t*
6446 // are allowed as the first parameter to a two-parameter function
6447 if (!(Context
.hasSameType(T
, Context
.CharTy
) ||
6448 Context
.hasSameType(T
, Context
.WCharTy
) ||
6449 Context
.hasSameType(T
, Context
.Char16Ty
) ||
6450 Context
.hasSameType(T
, Context
.Char32Ty
)))
6451 goto FinishedParams
;
6453 // The second and final parameter must be an std::size_t
6454 T
= (*Param
)->getType().getUnqualifiedType();
6455 if (Context
.hasSameType(T
, Context
.getSizeType()) &&
6456 ++Param
== FnDecl
->param_end())
6460 // FIXME: This diagnostic is absolutely terrible.
6463 Diag(FnDecl
->getLocation(), diag::err_literal_operator_params
)
6464 << FnDecl
->getDeclName();
6471 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
6472 /// linkage specification, including the language and (if present)
6473 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
6474 /// the location of the language string literal, which is provided
6475 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
6476 /// the '{' brace. Otherwise, this linkage specification does not
6477 /// have any braces.
6478 Decl
*Sema::ActOnStartLinkageSpecification(Scope
*S
, SourceLocation ExternLoc
,
6479 SourceLocation LangLoc
,
6480 llvm::StringRef Lang
,
6481 SourceLocation LBraceLoc
) {
6482 LinkageSpecDecl::LanguageIDs Language
;
6483 if (Lang
== "\"C\"")
6484 Language
= LinkageSpecDecl::lang_c
;
6485 else if (Lang
== "\"C++\"")
6486 Language
= LinkageSpecDecl::lang_cxx
;
6488 Diag(LangLoc
, diag::err_bad_language
);
6492 // FIXME: Add all the various semantics of linkage specifications
6494 LinkageSpecDecl
*D
= LinkageSpecDecl::Create(Context
, CurContext
,
6496 LBraceLoc
.isValid());
6497 CurContext
->addDecl(D
);
6498 PushDeclContext(S
, D
);
6502 /// ActOnFinishLinkageSpecification - Complete the definition of
6503 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
6504 /// valid, it's the position of the closing '}' brace in a linkage
6505 /// specification that uses braces.
6506 Decl
*Sema::ActOnFinishLinkageSpecification(Scope
*S
,
6508 SourceLocation RBraceLoc
) {
6514 /// \brief Perform semantic analysis for the variable declaration that
6515 /// occurs within a C++ catch clause, returning the newly-created
6517 VarDecl
*Sema::BuildExceptionDeclaration(Scope
*S
,
6518 TypeSourceInfo
*TInfo
,
6519 IdentifierInfo
*Name
,
6520 SourceLocation Loc
) {
6521 bool Invalid
= false;
6522 QualType ExDeclType
= TInfo
->getType();
6524 // Arrays and functions decay.
6525 if (ExDeclType
->isArrayType())
6526 ExDeclType
= Context
.getArrayDecayedType(ExDeclType
);
6527 else if (ExDeclType
->isFunctionType())
6528 ExDeclType
= Context
.getPointerType(ExDeclType
);
6530 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
6531 // The exception-declaration shall not denote a pointer or reference to an
6532 // incomplete type, other than [cv] void*.
6533 // N2844 forbids rvalue references.
6534 if (!ExDeclType
->isDependentType() && ExDeclType
->isRValueReferenceType()) {
6535 Diag(Loc
, diag::err_catch_rvalue_ref
);
6539 // GCC allows catching pointers and references to incomplete types
6540 // as an extension; so do we, but we warn by default.
6542 QualType BaseType
= ExDeclType
;
6543 int Mode
= 0; // 0 for direct type, 1 for pointer, 2 for reference
6544 unsigned DK
= diag::err_catch_incomplete
;
6545 bool IncompleteCatchIsInvalid
= true;
6546 if (const PointerType
*Ptr
= BaseType
->getAs
<PointerType
>()) {
6547 BaseType
= Ptr
->getPointeeType();
6549 DK
= diag::ext_catch_incomplete_ptr
;
6550 IncompleteCatchIsInvalid
= false;
6551 } else if (const ReferenceType
*Ref
= BaseType
->getAs
<ReferenceType
>()) {
6552 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
6553 BaseType
= Ref
->getPointeeType();
6555 DK
= diag::ext_catch_incomplete_ref
;
6556 IncompleteCatchIsInvalid
= false;
6558 if (!Invalid
&& (Mode
== 0 || !BaseType
->isVoidType()) &&
6559 !BaseType
->isDependentType() && RequireCompleteType(Loc
, BaseType
, DK
) &&
6560 IncompleteCatchIsInvalid
)
6563 if (!Invalid
&& !ExDeclType
->isDependentType() &&
6564 RequireNonAbstractType(Loc
, ExDeclType
,
6565 diag::err_abstract_type_in_decl
,
6566 AbstractVariableType
))
6569 // Only the non-fragile NeXT runtime currently supports C++ catches
6570 // of ObjC types, and no runtime supports catching ObjC types by value.
6571 if (!Invalid
&& getLangOptions().ObjC1
) {
6572 QualType T
= ExDeclType
;
6573 if (const ReferenceType
*RT
= T
->getAs
<ReferenceType
>())
6574 T
= RT
->getPointeeType();
6576 if (T
->isObjCObjectType()) {
6577 Diag(Loc
, diag::err_objc_object_catch
);
6579 } else if (T
->isObjCObjectPointerType()) {
6580 if (!getLangOptions().NeXTRuntime
) {
6581 Diag(Loc
, diag::err_objc_pointer_cxx_catch_gnu
);
6583 } else if (!getLangOptions().ObjCNonFragileABI
) {
6584 Diag(Loc
, diag::err_objc_pointer_cxx_catch_fragile
);
6590 VarDecl
*ExDecl
= VarDecl::Create(Context
, CurContext
, Loc
,
6591 Name
, ExDeclType
, TInfo
, SC_None
,
6593 ExDecl
->setExceptionVariable(true);
6596 if (const RecordType
*recordType
= ExDeclType
->getAs
<RecordType
>()) {
6597 // C++ [except.handle]p16:
6598 // The object declared in an exception-declaration or, if the
6599 // exception-declaration does not specify a name, a temporary (12.2) is
6600 // copy-initialized (8.5) from the exception object. [...]
6601 // The object is destroyed when the handler exits, after the destruction
6602 // of any automatic objects initialized within the handler.
6604 // We just pretend to initialize the object with itself, then make sure
6605 // it can be destroyed later.
6606 QualType initType
= ExDeclType
;
6608 InitializedEntity entity
=
6609 InitializedEntity::InitializeVariable(ExDecl
);
6610 InitializationKind initKind
=
6611 InitializationKind::CreateCopy(Loc
, SourceLocation());
6614 new (Context
) OpaqueValueExpr(Loc
, initType
, VK_LValue
, OK_Ordinary
);
6615 InitializationSequence
sequence(*this, entity
, initKind
, &opaqueValue
, 1);
6616 ExprResult result
= sequence
.Perform(*this, entity
, initKind
,
6617 MultiExprArg(&opaqueValue
, 1));
6618 if (result
.isInvalid())
6621 // If the constructor used was non-trivial, set this as the
6623 CXXConstructExpr
*construct
= cast
<CXXConstructExpr
>(result
.take());
6624 if (!construct
->getConstructor()->isTrivial()) {
6625 Expr
*init
= MaybeCreateExprWithCleanups(construct
);
6626 ExDecl
->setInit(init
);
6629 // And make sure it's destructable.
6630 FinalizeVarWithDestructor(ExDecl
, recordType
);
6636 ExDecl
->setInvalidDecl();
6641 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
6643 Decl
*Sema::ActOnExceptionDeclarator(Scope
*S
, Declarator
&D
) {
6644 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
6645 bool Invalid
= D
.isInvalidType();
6647 // Check for unexpanded parameter packs.
6648 if (TInfo
&& DiagnoseUnexpandedParameterPack(D
.getIdentifierLoc(), TInfo
,
6649 UPPC_ExceptionType
)) {
6650 TInfo
= Context
.getTrivialTypeSourceInfo(Context
.IntTy
,
6651 D
.getIdentifierLoc());
6655 IdentifierInfo
*II
= D
.getIdentifier();
6656 if (NamedDecl
*PrevDecl
= LookupSingleName(S
, II
, D
.getIdentifierLoc(),
6658 ForRedeclaration
)) {
6659 // The scope should be freshly made just for us. There is just no way
6660 // it contains any previous declaration.
6661 assert(!S
->isDeclScope(PrevDecl
));
6662 if (PrevDecl
->isTemplateParameter()) {
6663 // Maybe we will complain about the shadowed template parameter.
6664 DiagnoseTemplateParameterShadow(D
.getIdentifierLoc(), PrevDecl
);
6668 if (D
.getCXXScopeSpec().isSet() && !Invalid
) {
6669 Diag(D
.getIdentifierLoc(), diag::err_qualified_catch_declarator
)
6670 << D
.getCXXScopeSpec().getRange();
6674 VarDecl
*ExDecl
= BuildExceptionDeclaration(S
, TInfo
,
6676 D
.getIdentifierLoc());
6679 ExDecl
->setInvalidDecl();
6681 // Add the exception declaration into this scope.
6683 PushOnScopeChains(ExDecl
, S
);
6685 CurContext
->addDecl(ExDecl
);
6687 ProcessDeclAttributes(S
, ExDecl
, D
);
6691 Decl
*Sema::ActOnStaticAssertDeclaration(SourceLocation AssertLoc
,
6693 Expr
*AssertMessageExpr_
) {
6694 StringLiteral
*AssertMessage
= cast
<StringLiteral
>(AssertMessageExpr_
);
6696 if (!AssertExpr
->isTypeDependent() && !AssertExpr
->isValueDependent()) {
6697 llvm::APSInt
Value(32);
6698 if (!AssertExpr
->isIntegerConstantExpr(Value
, Context
)) {
6699 Diag(AssertLoc
, diag::err_static_assert_expression_is_not_constant
) <<
6700 AssertExpr
->getSourceRange();
6705 Diag(AssertLoc
, diag::err_static_assert_failed
)
6706 << AssertMessage
->getString() << AssertExpr
->getSourceRange();
6710 if (DiagnoseUnexpandedParameterPack(AssertExpr
, UPPC_StaticAssertExpression
))
6713 Decl
*Decl
= StaticAssertDecl::Create(Context
, CurContext
, AssertLoc
,
6714 AssertExpr
, AssertMessage
);
6716 CurContext
->addDecl(Decl
);
6720 /// \brief Perform semantic analysis of the given friend type declaration.
6722 /// \returns A friend declaration that.
6723 FriendDecl
*Sema::CheckFriendTypeDecl(SourceLocation FriendLoc
,
6724 TypeSourceInfo
*TSInfo
) {
6725 assert(TSInfo
&& "NULL TypeSourceInfo for friend type declaration");
6727 QualType T
= TSInfo
->getType();
6728 SourceRange TypeRange
= TSInfo
->getTypeLoc().getLocalSourceRange();
6730 if (!getLangOptions().CPlusPlus0x
) {
6731 // C++03 [class.friend]p2:
6732 // An elaborated-type-specifier shall be used in a friend declaration
6735 // * The class-key of the elaborated-type-specifier is required.
6736 if (!ActiveTemplateInstantiations
.empty()) {
6737 // Do not complain about the form of friend template types during
6738 // template instantiation; we will already have complained when the
6739 // template was declared.
6740 } else if (!T
->isElaboratedTypeSpecifier()) {
6741 // If we evaluated the type to a record type, suggest putting
6743 if (const RecordType
*RT
= T
->getAs
<RecordType
>()) {
6744 RecordDecl
*RD
= RT
->getDecl();
6746 std::string InsertionText
= std::string(" ") + RD
->getKindName();
6748 Diag(TypeRange
.getBegin(), diag::ext_unelaborated_friend_type
)
6749 << (unsigned) RD
->getTagKind()
6751 << FixItHint::CreateInsertion(PP
.getLocForEndOfToken(FriendLoc
),
6754 Diag(FriendLoc
, diag::ext_nonclass_type_friend
)
6756 << SourceRange(FriendLoc
, TypeRange
.getEnd());
6758 } else if (T
->getAs
<EnumType
>()) {
6759 Diag(FriendLoc
, diag::ext_enum_friend
)
6761 << SourceRange(FriendLoc
, TypeRange
.getEnd());
6765 // C++0x [class.friend]p3:
6766 // If the type specifier in a friend declaration designates a (possibly
6767 // cv-qualified) class type, that class is declared as a friend; otherwise,
6768 // the friend declaration is ignored.
6770 // FIXME: C++0x has some syntactic restrictions on friend type declarations
6771 // in [class.friend]p3 that we do not implement.
6773 return FriendDecl::Create(Context
, CurContext
, FriendLoc
, TSInfo
, FriendLoc
);
6776 /// Handle a friend tag declaration where the scope specifier was
6778 Decl
*Sema::ActOnTemplatedFriendTag(Scope
*S
, SourceLocation FriendLoc
,
6779 unsigned TagSpec
, SourceLocation TagLoc
,
6781 IdentifierInfo
*Name
, SourceLocation NameLoc
,
6782 AttributeList
*Attr
,
6783 MultiTemplateParamsArg TempParamLists
) {
6784 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
6786 bool isExplicitSpecialization
= false;
6787 unsigned NumMatchedTemplateParamLists
= TempParamLists
.size();
6788 bool Invalid
= false;
6790 if (TemplateParameterList
*TemplateParams
6791 = MatchTemplateParametersToScopeSpecifier(TagLoc
, SS
,
6792 TempParamLists
.get(),
6793 TempParamLists
.size(),
6795 isExplicitSpecialization
,
6797 --NumMatchedTemplateParamLists
;
6799 if (TemplateParams
->size() > 0) {
6800 // This is a declaration of a class template.
6804 return CheckClassTemplate(S
, TagSpec
, TUK_Friend
, TagLoc
,
6805 SS
, Name
, NameLoc
, Attr
,
6806 TemplateParams
, AS_public
).take();
6808 // The "template<>" header is extraneous.
6809 Diag(TemplateParams
->getTemplateLoc(), diag::err_template_tag_noparams
)
6810 << TypeWithKeyword::getTagTypeKindName(Kind
) << Name
;
6811 isExplicitSpecialization
= true;
6815 if (Invalid
) return 0;
6817 assert(SS
.isNotEmpty() && "valid templated tag with no SS and no direct?");
6819 bool isAllExplicitSpecializations
= true;
6820 for (unsigned I
= 0; I
!= NumMatchedTemplateParamLists
; ++I
) {
6821 if (TempParamLists
.get()[I
]->size()) {
6822 isAllExplicitSpecializations
= false;
6827 // FIXME: don't ignore attributes.
6829 // If it's explicit specializations all the way down, just forget
6830 // about the template header and build an appropriate non-templated
6831 // friend. TODO: for source fidelity, remember the headers.
6832 if (isAllExplicitSpecializations
) {
6833 ElaboratedTypeKeyword Keyword
6834 = TypeWithKeyword::getKeywordForTagTypeKind(Kind
);
6835 QualType T
= CheckTypenameType(Keyword
, SS
.getScopeRep(), *Name
,
6836 TagLoc
, SS
.getRange(), NameLoc
);
6840 TypeSourceInfo
*TSI
= Context
.CreateTypeSourceInfo(T
);
6841 if (isa
<DependentNameType
>(T
)) {
6842 DependentNameTypeLoc TL
= cast
<DependentNameTypeLoc
>(TSI
->getTypeLoc());
6843 TL
.setKeywordLoc(TagLoc
);
6844 TL
.setQualifierRange(SS
.getRange());
6845 TL
.setNameLoc(NameLoc
);
6847 ElaboratedTypeLoc TL
= cast
<ElaboratedTypeLoc
>(TSI
->getTypeLoc());
6848 TL
.setKeywordLoc(TagLoc
);
6849 TL
.setQualifierRange(SS
.getRange());
6850 cast
<TypeSpecTypeLoc
>(TL
.getNamedTypeLoc()).setNameLoc(NameLoc
);
6853 FriendDecl
*Friend
= FriendDecl::Create(Context
, CurContext
, NameLoc
,
6855 Friend
->setAccess(AS_public
);
6856 CurContext
->addDecl(Friend
);
6860 // Handle the case of a templated-scope friend class. e.g.
6861 // template <class T> class A<T>::B;
6862 // FIXME: we don't support these right now.
6863 ElaboratedTypeKeyword ETK
= TypeWithKeyword::getKeywordForTagTypeKind(Kind
);
6864 QualType T
= Context
.getDependentNameType(ETK
, SS
.getScopeRep(), Name
);
6865 TypeSourceInfo
*TSI
= Context
.CreateTypeSourceInfo(T
);
6866 DependentNameTypeLoc TL
= cast
<DependentNameTypeLoc
>(TSI
->getTypeLoc());
6867 TL
.setKeywordLoc(TagLoc
);
6868 TL
.setQualifierRange(SS
.getRange());
6869 TL
.setNameLoc(NameLoc
);
6871 FriendDecl
*Friend
= FriendDecl::Create(Context
, CurContext
, NameLoc
,
6873 Friend
->setAccess(AS_public
);
6874 Friend
->setUnsupportedFriend(true);
6875 CurContext
->addDecl(Friend
);
6880 /// Handle a friend type declaration. This works in tandem with
6883 /// Notes on friend class templates:
6885 /// We generally treat friend class declarations as if they were
6886 /// declaring a class. So, for example, the elaborated type specifier
6887 /// in a friend declaration is required to obey the restrictions of a
6888 /// class-head (i.e. no typedefs in the scope chain), template
6889 /// parameters are required to match up with simple template-ids, &c.
6890 /// However, unlike when declaring a template specialization, it's
6891 /// okay to refer to a template specialization without an empty
6892 /// template parameter declaration, e.g.
6893 /// friend class A<T>::B<unsigned>;
6894 /// We permit this as a special case; if there are any template
6895 /// parameters present at all, require proper matching, i.e.
6896 /// template <> template <class T> friend class A<int>::B;
6897 Decl
*Sema::ActOnFriendTypeDecl(Scope
*S
, const DeclSpec
&DS
,
6898 MultiTemplateParamsArg TempParams
) {
6899 SourceLocation Loc
= DS
.getSourceRange().getBegin();
6901 assert(DS
.isFriendSpecified());
6902 assert(DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
);
6904 // Try to convert the decl specifier to a type. This works for
6905 // friend templates because ActOnTag never produces a ClassTemplateDecl
6906 // for a TUK_Friend.
6907 Declarator
TheDeclarator(DS
, Declarator::MemberContext
);
6908 TypeSourceInfo
*TSI
= GetTypeForDeclarator(TheDeclarator
, S
);
6909 QualType T
= TSI
->getType();
6910 if (TheDeclarator
.isInvalidType())
6913 if (DiagnoseUnexpandedParameterPack(Loc
, TSI
, UPPC_FriendDeclaration
))
6916 // This is definitely an error in C++98. It's probably meant to
6917 // be forbidden in C++0x, too, but the specification is just
6920 // The problem is with declarations like the following:
6921 // template <T> friend A<T>::foo;
6922 // where deciding whether a class C is a friend or not now hinges
6923 // on whether there exists an instantiation of A that causes
6924 // 'foo' to equal C. There are restrictions on class-heads
6925 // (which we declare (by fiat) elaborated friend declarations to
6926 // be) that makes this tractable.
6928 // FIXME: handle "template <> friend class A<T>;", which
6929 // is possibly well-formed? Who even knows?
6930 if (TempParams
.size() && !T
->isElaboratedTypeSpecifier()) {
6931 Diag(Loc
, diag::err_tagless_friend_type_template
)
6932 << DS
.getSourceRange();
6936 // C++98 [class.friend]p1: A friend of a class is a function
6937 // or class that is not a member of the class . . .
6938 // This is fixed in DR77, which just barely didn't make the C++03
6939 // deadline. It's also a very silly restriction that seriously
6940 // affects inner classes and which nobody else seems to implement;
6941 // thus we never diagnose it, not even in -pedantic.
6943 // But note that we could warn about it: it's always useless to
6944 // friend one of your own members (it's not, however, worthless to
6945 // friend a member of an arbitrary specialization of your template).
6948 if (unsigned NumTempParamLists
= TempParams
.size())
6949 D
= FriendTemplateDecl::Create(Context
, CurContext
, Loc
,
6951 TempParams
.release(),
6953 DS
.getFriendSpecLoc());
6955 D
= CheckFriendTypeDecl(DS
.getFriendSpecLoc(), TSI
);
6960 D
->setAccess(AS_public
);
6961 CurContext
->addDecl(D
);
6966 Decl
*Sema::ActOnFriendFunctionDecl(Scope
*S
, Declarator
&D
, bool IsDefinition
,
6967 MultiTemplateParamsArg TemplateParams
) {
6968 const DeclSpec
&DS
= D
.getDeclSpec();
6970 assert(DS
.isFriendSpecified());
6971 assert(DS
.getStorageClassSpec() == DeclSpec::SCS_unspecified
);
6973 SourceLocation Loc
= D
.getIdentifierLoc();
6974 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
6975 QualType T
= TInfo
->getType();
6977 // C++ [class.friend]p1
6978 // A friend of a class is a function or class....
6979 // Note that this sees through typedefs, which is intended.
6980 // It *doesn't* see through dependent types, which is correct
6981 // according to [temp.arg.type]p3:
6982 // If a declaration acquires a function type through a
6983 // type dependent on a template-parameter and this causes
6984 // a declaration that does not use the syntactic form of a
6985 // function declarator to have a function type, the program
6987 if (!T
->isFunctionType()) {
6988 Diag(Loc
, diag::err_unexpected_friend
);
6990 // It might be worthwhile to try to recover by creating an
6991 // appropriate declaration.
6995 // C++ [namespace.memdef]p3
6996 // - If a friend declaration in a non-local class first declares a
6997 // class or function, the friend class or function is a member
6998 // of the innermost enclosing namespace.
6999 // - The name of the friend is not found by simple name lookup
7000 // until a matching declaration is provided in that namespace
7001 // scope (either before or after the class declaration granting
7003 // - If a friend function is called, its name may be found by the
7004 // name lookup that considers functions from namespaces and
7005 // classes associated with the types of the function arguments.
7006 // - When looking for a prior declaration of a class or a function
7007 // declared as a friend, scopes outside the innermost enclosing
7008 // namespace scope are not considered.
7010 CXXScopeSpec
&SS
= D
.getCXXScopeSpec();
7011 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
7012 DeclarationName Name
= NameInfo
.getName();
7015 // Check for unexpanded parameter packs.
7016 if (DiagnoseUnexpandedParameterPack(Loc
, TInfo
, UPPC_FriendDeclaration
) ||
7017 DiagnoseUnexpandedParameterPack(NameInfo
, UPPC_FriendDeclaration
) ||
7018 DiagnoseUnexpandedParameterPack(SS
, UPPC_FriendDeclaration
))
7021 // The context we found the declaration in, or in which we should
7022 // create the declaration.
7025 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
7028 // FIXME: there are different rules in local classes
7030 // There are four cases here.
7031 // - There's no scope specifier, in which case we just go to the
7032 // appropriate scope and look for a function or function template
7033 // there as appropriate.
7034 // Recover from invalid scope qualifiers as if they just weren't there.
7035 if (SS
.isInvalid() || !SS
.isSet()) {
7036 // C++0x [namespace.memdef]p3:
7037 // If the name in a friend declaration is neither qualified nor
7038 // a template-id and the declaration is a function or an
7039 // elaborated-type-specifier, the lookup to determine whether
7040 // the entity has been previously declared shall not consider
7041 // any scopes outside the innermost enclosing namespace.
7042 // C++0x [class.friend]p11:
7043 // If a friend declaration appears in a local class and the name
7044 // specified is an unqualified name, a prior declaration is
7045 // looked up without considering scopes that are outside the
7046 // innermost enclosing non-class scope. For a friend function
7047 // declaration, if there is no prior declaration, the program is
7049 bool isLocal
= cast
<CXXRecordDecl
>(CurContext
)->isLocalClass();
7050 bool isTemplateId
= D
.getName().getKind() == UnqualifiedId::IK_TemplateId
;
7052 // Find the appropriate context according to the above.
7055 // Skip class contexts. If someone can cite chapter and verse
7056 // for this behavior, that would be nice --- it's what GCC and
7057 // EDG do, and it seems like a reasonable intent, but the spec
7058 // really only says that checks for unqualified existing
7059 // declarations should stop at the nearest enclosing namespace,
7060 // not that they should only consider the nearest enclosing
7062 while (DC
->isRecord())
7063 DC
= DC
->getParent();
7065 LookupQualifiedName(Previous
, DC
);
7067 // TODO: decide what we think about using declarations.
7068 if (isLocal
|| !Previous
.empty())
7072 if (isa
<TranslationUnitDecl
>(DC
)) break;
7074 if (DC
->isFileContext()) break;
7076 DC
= DC
->getParent();
7079 // C++ [class.friend]p1: A friend of a class is a function or
7080 // class that is not a member of the class . . .
7081 // C++0x changes this for both friend types and functions.
7082 // Most C++ 98 compilers do seem to give an error here, so
7084 if (!Previous
.empty() && DC
->Equals(CurContext
)
7085 && !getLangOptions().CPlusPlus0x
)
7086 Diag(DS
.getFriendSpecLoc(), diag::err_friend_is_member
);
7088 DCScope
= getScopeForDeclContext(S
, DC
);
7090 // - There's a non-dependent scope specifier, in which case we
7091 // compute it and do a previous lookup there for a function
7092 // or function template.
7093 } else if (!SS
.getScopeRep()->isDependent()) {
7094 DC
= computeDeclContext(SS
);
7097 if (RequireCompleteDeclContext(SS
, DC
)) return 0;
7099 LookupQualifiedName(Previous
, DC
);
7101 // Ignore things found implicitly in the wrong scope.
7102 // TODO: better diagnostics for this case. Suggesting the right
7103 // qualified scope would be nice...
7104 LookupResult::Filter F
= Previous
.makeFilter();
7105 while (F
.hasNext()) {
7106 NamedDecl
*D
= F
.next();
7107 if (!DC
->InEnclosingNamespaceSetOf(
7108 D
->getDeclContext()->getRedeclContext()))
7113 if (Previous
.empty()) {
7115 Diag(Loc
, diag::err_qualified_friend_not_found
) << Name
<< T
;
7119 // C++ [class.friend]p1: A friend of a class is a function or
7120 // class that is not a member of the class . . .
7121 if (DC
->Equals(CurContext
))
7122 Diag(DS
.getFriendSpecLoc(), diag::err_friend_is_member
);
7124 // - There's a scope specifier that does not match any template
7125 // parameter lists, in which case we use some arbitrary context,
7126 // create a method or method template, and wait for instantiation.
7127 // - There's a scope specifier that does match some template
7128 // parameter lists, which we don't handle right now.
7131 assert(isa
<CXXRecordDecl
>(DC
) && "friend declaration not in class?");
7134 if (!DC
->isRecord()) {
7135 // This implies that it has to be an operator or function.
7136 if (D
.getName().getKind() == UnqualifiedId::IK_ConstructorName
||
7137 D
.getName().getKind() == UnqualifiedId::IK_DestructorName
||
7138 D
.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId
) {
7139 Diag(Loc
, diag::err_introducing_special_friend
) <<
7140 (D
.getName().getKind() == UnqualifiedId::IK_ConstructorName
? 0 :
7141 D
.getName().getKind() == UnqualifiedId::IK_DestructorName
? 1 : 2);
7146 bool Redeclaration
= false;
7147 NamedDecl
*ND
= ActOnFunctionDeclarator(DCScope
, D
, DC
, T
, TInfo
, Previous
,
7148 move(TemplateParams
),
7153 assert(ND
->getDeclContext() == DC
);
7154 assert(ND
->getLexicalDeclContext() == CurContext
);
7156 // Add the function declaration to the appropriate lookup tables,
7157 // adjusting the redeclarations list as necessary. We don't
7158 // want to do this yet if the friending class is dependent.
7160 // Also update the scope-based lookup if the target context's
7161 // lookup context is in lexical scope.
7162 if (!CurContext
->isDependentContext()) {
7163 DC
= DC
->getRedeclContext();
7164 DC
->makeDeclVisibleInContext(ND
, /* Recoverable=*/ false);
7165 if (Scope
*EnclosingScope
= getScopeForDeclContext(S
, DC
))
7166 PushOnScopeChains(ND
, EnclosingScope
, /*AddToContext=*/ false);
7169 FriendDecl
*FrD
= FriendDecl::Create(Context
, CurContext
,
7170 D
.getIdentifierLoc(), ND
,
7171 DS
.getFriendSpecLoc());
7172 FrD
->setAccess(AS_public
);
7173 CurContext
->addDecl(FrD
);
7175 if (ND
->isInvalidDecl())
7176 FrD
->setInvalidDecl();
7179 if (FunctionTemplateDecl
*FTD
= dyn_cast
<FunctionTemplateDecl
>(ND
))
7180 FD
= FTD
->getTemplatedDecl();
7182 FD
= cast
<FunctionDecl
>(ND
);
7184 // Mark templated-scope function declarations as unsupported.
7185 if (FD
->getNumTemplateParameterLists())
7186 FrD
->setUnsupportedFriend(true);
7192 void Sema::SetDeclDeleted(Decl
*Dcl
, SourceLocation DelLoc
) {
7193 AdjustDeclIfTemplate(Dcl
);
7195 FunctionDecl
*Fn
= dyn_cast
<FunctionDecl
>(Dcl
);
7197 Diag(DelLoc
, diag::err_deleted_non_function
);
7200 if (const FunctionDecl
*Prev
= Fn
->getPreviousDeclaration()) {
7201 Diag(DelLoc
, diag::err_deleted_decl_not_first
);
7202 Diag(Prev
->getLocation(), diag::note_previous_declaration
);
7203 // If the declaration wasn't the first, we delete the function anyway for
7209 static void SearchForReturnInStmt(Sema
&Self
, Stmt
*S
) {
7210 for (Stmt::child_range CI
= S
->children(); CI
; ++CI
) {
7211 Stmt
*SubStmt
= *CI
;
7214 if (isa
<ReturnStmt
>(SubStmt
))
7215 Self
.Diag(SubStmt
->getSourceRange().getBegin(),
7216 diag::err_return_in_constructor_handler
);
7217 if (!isa
<Expr
>(SubStmt
))
7218 SearchForReturnInStmt(Self
, SubStmt
);
7222 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt
*TryBlock
) {
7223 for (unsigned I
= 0, E
= TryBlock
->getNumHandlers(); I
!= E
; ++I
) {
7224 CXXCatchStmt
*Handler
= TryBlock
->getHandler(I
);
7225 SearchForReturnInStmt(*this, Handler
);
7229 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl
*New
,
7230 const CXXMethodDecl
*Old
) {
7231 QualType NewTy
= New
->getType()->getAs
<FunctionType
>()->getResultType();
7232 QualType OldTy
= Old
->getType()->getAs
<FunctionType
>()->getResultType();
7234 if (Context
.hasSameType(NewTy
, OldTy
) ||
7235 NewTy
->isDependentType() || OldTy
->isDependentType())
7238 // Check if the return types are covariant
7239 QualType NewClassTy
, OldClassTy
;
7241 /// Both types must be pointers or references to classes.
7242 if (const PointerType
*NewPT
= NewTy
->getAs
<PointerType
>()) {
7243 if (const PointerType
*OldPT
= OldTy
->getAs
<PointerType
>()) {
7244 NewClassTy
= NewPT
->getPointeeType();
7245 OldClassTy
= OldPT
->getPointeeType();
7247 } else if (const ReferenceType
*NewRT
= NewTy
->getAs
<ReferenceType
>()) {
7248 if (const ReferenceType
*OldRT
= OldTy
->getAs
<ReferenceType
>()) {
7249 if (NewRT
->getTypeClass() == OldRT
->getTypeClass()) {
7250 NewClassTy
= NewRT
->getPointeeType();
7251 OldClassTy
= OldRT
->getPointeeType();
7256 // The return types aren't either both pointers or references to a class type.
7257 if (NewClassTy
.isNull()) {
7258 Diag(New
->getLocation(),
7259 diag::err_different_return_type_for_overriding_virtual_function
)
7260 << New
->getDeclName() << NewTy
<< OldTy
;
7261 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
7266 // C++ [class.virtual]p6:
7267 // If the return type of D::f differs from the return type of B::f, the
7268 // class type in the return type of D::f shall be complete at the point of
7269 // declaration of D::f or shall be the class type D.
7270 if (const RecordType
*RT
= NewClassTy
->getAs
<RecordType
>()) {
7271 if (!RT
->isBeingDefined() &&
7272 RequireCompleteType(New
->getLocation(), NewClassTy
,
7273 PDiag(diag::err_covariant_return_incomplete
)
7274 << New
->getDeclName()))
7278 if (!Context
.hasSameUnqualifiedType(NewClassTy
, OldClassTy
)) {
7279 // Check if the new class derives from the old class.
7280 if (!IsDerivedFrom(NewClassTy
, OldClassTy
)) {
7281 Diag(New
->getLocation(),
7282 diag::err_covariant_return_not_derived
)
7283 << New
->getDeclName() << NewTy
<< OldTy
;
7284 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
7288 // Check if we the conversion from derived to base is valid.
7289 if (CheckDerivedToBaseConversion(NewClassTy
, OldClassTy
,
7290 diag::err_covariant_return_inaccessible_base
,
7291 diag::err_covariant_return_ambiguous_derived_to_base_conv
,
7292 // FIXME: Should this point to the return type?
7293 New
->getLocation(), SourceRange(), New
->getDeclName(), 0)) {
7294 // FIXME: this note won't trigger for delayed access control
7295 // diagnostics, and it's impossible to get an undelayed error
7296 // here from access control during the original parse because
7297 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
7298 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
7303 // The qualifiers of the return types must be the same.
7304 if (NewTy
.getLocalCVRQualifiers() != OldTy
.getLocalCVRQualifiers()) {
7305 Diag(New
->getLocation(),
7306 diag::err_covariant_return_type_different_qualifications
)
7307 << New
->getDeclName() << NewTy
<< OldTy
;
7308 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
7313 // The new class type must have the same or less qualifiers as the old type.
7314 if (NewClassTy
.isMoreQualifiedThan(OldClassTy
)) {
7315 Diag(New
->getLocation(),
7316 diag::err_covariant_return_type_class_type_more_qualified
)
7317 << New
->getDeclName() << NewTy
<< OldTy
;
7318 Diag(Old
->getLocation(), diag::note_overridden_virtual_function
);
7325 /// \brief Mark the given method pure.
7327 /// \param Method the method to be marked pure.
7329 /// \param InitRange the source range that covers the "0" initializer.
7330 bool Sema::CheckPureMethod(CXXMethodDecl
*Method
, SourceRange InitRange
) {
7331 if (Method
->isVirtual() || Method
->getParent()->isDependentContext()) {
7336 if (!Method
->isInvalidDecl())
7337 Diag(Method
->getLocation(), diag::err_non_virtual_pure
)
7338 << Method
->getDeclName() << InitRange
;
7342 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
7343 /// an initializer for the out-of-line declaration 'Dcl'. The scope
7344 /// is a fresh scope pushed for just this purpose.
7346 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
7347 /// static data member of class X, names should be looked up in the scope of
7349 void Sema::ActOnCXXEnterDeclInitializer(Scope
*S
, Decl
*D
) {
7350 // If there is no declaration, there was an error parsing it.
7353 // We should only get called for declarations with scope specifiers, like:
7355 assert(D
->isOutOfLine());
7356 EnterDeclaratorContext(S
, D
->getDeclContext());
7359 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
7360 /// initializer for the out-of-line declaration 'D'.
7361 void Sema::ActOnCXXExitDeclInitializer(Scope
*S
, Decl
*D
) {
7362 // If there is no declaration, there was an error parsing it.
7365 assert(D
->isOutOfLine());
7366 ExitDeclaratorContext(S
);
7369 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
7370 /// C++ if/switch/while/for statement.
7371 /// e.g: "if (int x = f()) {...}"
7372 DeclResult
Sema::ActOnCXXConditionDeclaration(Scope
*S
, Declarator
&D
) {
7374 // The declarator shall not specify a function or an array.
7375 // The type-specifier-seq shall not contain typedef and shall not declare a
7376 // new class or enumeration.
7377 assert(D
.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef
&&
7378 "Parser allowed 'typedef' as storage class of condition decl.");
7380 TagDecl
*OwnedTag
= 0;
7381 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
, &OwnedTag
);
7382 QualType Ty
= TInfo
->getType();
7384 if (Ty
->isFunctionType()) { // The declarator shall not specify a function...
7385 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
7386 // would be created and CXXConditionDeclExpr wants a VarDecl.
7387 Diag(D
.getIdentifierLoc(), diag::err_invalid_use_of_function_type
)
7388 << D
.getSourceRange();
7389 return DeclResult();
7390 } else if (OwnedTag
&& OwnedTag
->isDefinition()) {
7391 // The type-specifier-seq shall not declare a new class or enumeration.
7392 Diag(OwnedTag
->getLocation(), diag::err_type_defined_in_condition
);
7395 Decl
*Dcl
= ActOnDeclarator(S
, D
);
7397 return DeclResult();
7402 void Sema::MarkVTableUsed(SourceLocation Loc
, CXXRecordDecl
*Class
,
7403 bool DefinitionRequired
) {
7404 // Ignore any vtable uses in unevaluated operands or for classes that do
7405 // not have a vtable.
7406 if (!Class
->isDynamicClass() || Class
->isDependentContext() ||
7407 CurContext
->isDependentContext() ||
7408 ExprEvalContexts
.back().Context
== Unevaluated
)
7411 // Try to insert this class into the map.
7412 Class
= cast
<CXXRecordDecl
>(Class
->getCanonicalDecl());
7413 std::pair
<llvm::DenseMap
<CXXRecordDecl
*, bool>::iterator
, bool>
7414 Pos
= VTablesUsed
.insert(std::make_pair(Class
, DefinitionRequired
));
7416 // If we already had an entry, check to see if we are promoting this vtable
7417 // to required a definition. If so, we need to reappend to the VTableUses
7418 // list, since we may have already processed the first entry.
7419 if (DefinitionRequired
&& !Pos
.first
->second
) {
7420 Pos
.first
->second
= true;
7422 // Otherwise, we can early exit.
7427 // Local classes need to have their virtual members marked
7428 // immediately. For all other classes, we mark their virtual members
7429 // at the end of the translation unit.
7430 if (Class
->isLocalClass())
7431 MarkVirtualMembersReferenced(Loc
, Class
);
7433 VTableUses
.push_back(std::make_pair(Class
, Loc
));
7436 bool Sema::DefineUsedVTables() {
7437 if (VTableUses
.empty())
7440 // Note: The VTableUses vector could grow as a result of marking
7441 // the members of a class as "used", so we check the size each
7442 // time through the loop and prefer indices (with are stable) to
7443 // iterators (which are not).
7444 for (unsigned I
= 0; I
!= VTableUses
.size(); ++I
) {
7445 CXXRecordDecl
*Class
= VTableUses
[I
].first
->getDefinition();
7449 SourceLocation Loc
= VTableUses
[I
].second
;
7451 // If this class has a key function, but that key function is
7452 // defined in another translation unit, we don't need to emit the
7453 // vtable even though we're using it.
7454 const CXXMethodDecl
*KeyFunction
= Context
.getKeyFunction(Class
);
7455 if (KeyFunction
&& !KeyFunction
->hasBody()) {
7456 switch (KeyFunction
->getTemplateSpecializationKind()) {
7457 case TSK_Undeclared
:
7458 case TSK_ExplicitSpecialization
:
7459 case TSK_ExplicitInstantiationDeclaration
:
7460 // The key function is in another translation unit.
7463 case TSK_ExplicitInstantiationDefinition
:
7464 case TSK_ImplicitInstantiation
:
7465 // We will be instantiating the key function.
7468 } else if (!KeyFunction
) {
7469 // If we have a class with no key function that is the subject
7470 // of an explicit instantiation declaration, suppress the
7471 // vtable; it will live with the explicit instantiation
7473 bool IsExplicitInstantiationDeclaration
7474 = Class
->getTemplateSpecializationKind()
7475 == TSK_ExplicitInstantiationDeclaration
;
7476 for (TagDecl::redecl_iterator R
= Class
->redecls_begin(),
7477 REnd
= Class
->redecls_end();
7479 TemplateSpecializationKind TSK
7480 = cast
<CXXRecordDecl
>(*R
)->getTemplateSpecializationKind();
7481 if (TSK
== TSK_ExplicitInstantiationDeclaration
)
7482 IsExplicitInstantiationDeclaration
= true;
7483 else if (TSK
== TSK_ExplicitInstantiationDefinition
) {
7484 IsExplicitInstantiationDeclaration
= false;
7489 if (IsExplicitInstantiationDeclaration
)
7493 // Mark all of the virtual members of this class as referenced, so
7494 // that we can build a vtable. Then, tell the AST consumer that a
7495 // vtable for this class is required.
7496 MarkVirtualMembersReferenced(Loc
, Class
);
7497 CXXRecordDecl
*Canonical
= cast
<CXXRecordDecl
>(Class
->getCanonicalDecl());
7498 Consumer
.HandleVTable(Class
, VTablesUsed
[Canonical
]);
7500 // Optionally warn if we're emitting a weak vtable.
7501 if (Class
->getLinkage() == ExternalLinkage
&&
7502 Class
->getTemplateSpecializationKind() != TSK_ImplicitInstantiation
) {
7503 if (!KeyFunction
|| (KeyFunction
->hasBody() && KeyFunction
->isInlined()))
7504 Diag(Class
->getLocation(), diag::warn_weak_vtable
) << Class
;
7512 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc
,
7513 const CXXRecordDecl
*RD
) {
7514 for (CXXRecordDecl::method_iterator i
= RD
->method_begin(),
7515 e
= RD
->method_end(); i
!= e
; ++i
) {
7516 CXXMethodDecl
*MD
= *i
;
7518 // C++ [basic.def.odr]p2:
7519 // [...] A virtual member function is used if it is not pure. [...]
7520 if (MD
->isVirtual() && !MD
->isPure())
7521 MarkDeclarationReferenced(Loc
, MD
);
7524 // Only classes that have virtual bases need a VTT.
7525 if (RD
->getNumVBases() == 0)
7528 for (CXXRecordDecl::base_class_const_iterator i
= RD
->bases_begin(),
7529 e
= RD
->bases_end(); i
!= e
; ++i
) {
7530 const CXXRecordDecl
*Base
=
7531 cast
<CXXRecordDecl
>(i
->getType()->getAs
<RecordType
>()->getDecl());
7532 if (Base
->getNumVBases() == 0)
7534 MarkVirtualMembersReferenced(Loc
, Base
);
7538 /// SetIvarInitializers - This routine builds initialization ASTs for the
7539 /// Objective-C implementation whose ivars need be initialized.
7540 void Sema::SetIvarInitializers(ObjCImplementationDecl
*ObjCImplementation
) {
7541 if (!getLangOptions().CPlusPlus
)
7543 if (ObjCInterfaceDecl
*OID
= ObjCImplementation
->getClassInterface()) {
7544 llvm::SmallVector
<ObjCIvarDecl
*, 8> ivars
;
7545 CollectIvarsToConstructOrDestruct(OID
, ivars
);
7548 llvm::SmallVector
<CXXCtorInitializer
*, 32> AllToInit
;
7549 for (unsigned i
= 0; i
< ivars
.size(); i
++) {
7550 FieldDecl
*Field
= ivars
[i
];
7551 if (Field
->isInvalidDecl())
7554 CXXCtorInitializer
*Member
;
7555 InitializedEntity InitEntity
= InitializedEntity::InitializeMember(Field
);
7556 InitializationKind InitKind
=
7557 InitializationKind::CreateDefault(ObjCImplementation
->getLocation());
7559 InitializationSequence
InitSeq(*this, InitEntity
, InitKind
, 0, 0);
7560 ExprResult MemberInit
=
7561 InitSeq
.Perform(*this, InitEntity
, InitKind
, MultiExprArg());
7562 MemberInit
= MaybeCreateExprWithCleanups(MemberInit
);
7563 // Note, MemberInit could actually come back empty if no initialization
7564 // is required (e.g., because it would call a trivial default constructor)
7565 if (!MemberInit
.get() || MemberInit
.isInvalid())
7569 new (Context
) CXXCtorInitializer(Context
, Field
, SourceLocation(),
7571 MemberInit
.takeAs
<Expr
>(),
7573 AllToInit
.push_back(Member
);
7575 // Be sure that the destructor is accessible and is marked as referenced.
7576 if (const RecordType
*RecordTy
7577 = Context
.getBaseElementType(Field
->getType())
7578 ->getAs
<RecordType
>()) {
7579 CXXRecordDecl
*RD
= cast
<CXXRecordDecl
>(RecordTy
->getDecl());
7580 if (CXXDestructorDecl
*Destructor
= LookupDestructor(RD
)) {
7581 MarkDeclarationReferenced(Field
->getLocation(), Destructor
);
7582 CheckDestructorAccess(Field
->getLocation(), Destructor
,
7583 PDiag(diag::err_access_dtor_ivar
)
7584 << Context
.getBaseElementType(Field
->getType()));
7588 ObjCImplementation
->setIvarInitializers(Context
,
7589 AllToInit
.data(), AllToInit
.size());