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/ASTMutationListener.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/RecordLayout.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/AST/TypeOrdering.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/ParsedTemplate.h"
32 #include "clang/Basic/PartialDiagnostic.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/STLExtras.h"
39 using namespace clang;
41 //===----------------------------------------------------------------------===//
42 // CheckDefaultArgumentVisitor
43 //===----------------------------------------------------------------------===//
46 /// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
47 /// the default argument of a parameter to determine whether it
48 /// contains any ill-formed subexpressions. For example, this will
49 /// diagnose the use of local variables or parameters within the
50 /// default argument expression.
51 class CheckDefaultArgumentVisitor
52 : public StmtVisitor<CheckDefaultArgumentVisitor, bool> {
57 CheckDefaultArgumentVisitor(Expr *defarg, Sema *s)
58 : DefaultArg(defarg), S(s) {}
60 bool VisitExpr(Expr *Node);
61 bool VisitDeclRefExpr(DeclRefExpr *DRE);
62 bool VisitCXXThisExpr(CXXThisExpr *ThisE);
65 /// VisitExpr - Visit all of the children of this expression.
66 bool CheckDefaultArgumentVisitor::VisitExpr(Expr *Node) {
67 bool IsInvalid = false;
68 for (Stmt::child_range I = Node->children(); I; ++I)
69 IsInvalid |= Visit(*I);
73 /// VisitDeclRefExpr - Visit a reference to a declaration, to
74 /// determine whether this declaration can be used in the default
75 /// argument expression.
76 bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(DeclRefExpr *DRE) {
77 NamedDecl *Decl = DRE->getDecl();
78 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Decl)) {
79 // C++ [dcl.fct.default]p9
80 // Default arguments are evaluated each time the function is
81 // called. The order of evaluation of function arguments is
82 // unspecified. Consequently, parameters of a function shall not
83 // be used in default argument expressions, even if they are not
84 // evaluated. Parameters of a function declared before a default
85 // argument expression are in scope and can hide namespace and
86 // class member names.
87 return S->Diag(DRE->getSourceRange().getBegin(),
88 diag::err_param_default_argument_references_param)
89 << Param->getDeclName() << DefaultArg->getSourceRange();
90 } else if (VarDecl *VDecl = dyn_cast<VarDecl>(Decl)) {
91 // C++ [dcl.fct.default]p7
92 // Local variables shall not be used in default argument
94 if (VDecl->isLocalVarDecl())
95 return S->Diag(DRE->getSourceRange().getBegin(),
96 diag::err_param_default_argument_references_local)
97 << VDecl->getDeclName() << DefaultArg->getSourceRange();
103 /// VisitCXXThisExpr - Visit a C++ "this" expression.
104 bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(CXXThisExpr *ThisE) {
105 // C++ [dcl.fct.default]p8:
106 // The keyword this shall not be used in a default argument of a
108 return S->Diag(ThisE->getSourceRange().getBegin(),
109 diag::err_param_default_argument_references_this)
110 << ThisE->getSourceRange();
114 void Sema::ImplicitExceptionSpecification::CalledDecl(CXXMethodDecl *Method) {
115 assert(Context && "ImplicitExceptionSpecification without an ASTContext");
116 // If we have an MSAny or unknown spec already, don't bother.
117 if (!Method || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
120 const FunctionProtoType *Proto
121 = Method->getType()->getAs<FunctionProtoType>();
123 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
125 // If this function can throw any exceptions, make a note of that.
126 if (EST == EST_Delayed || EST == EST_MSAny || EST == EST_None) {
132 // FIXME: If the call to this decl is using any of its default arguments, we
133 // need to search them for potentially-throwing calls.
135 // If this function has a basic noexcept, it doesn't affect the outcome.
136 if (EST == EST_BasicNoexcept)
139 // If we have a throw-all spec at this point, ignore the function.
140 if (ComputedEST == EST_None)
143 // If we're still at noexcept(true) and there's a nothrow() callee,
144 // change to that specification.
145 if (EST == EST_DynamicNone) {
146 if (ComputedEST == EST_BasicNoexcept)
147 ComputedEST = EST_DynamicNone;
151 // Check out noexcept specs.
152 if (EST == EST_ComputedNoexcept) {
153 FunctionProtoType::NoexceptResult NR = Proto->getNoexceptSpec(*Context);
154 assert(NR != FunctionProtoType::NR_NoNoexcept &&
155 "Must have noexcept result for EST_ComputedNoexcept.");
156 assert(NR != FunctionProtoType::NR_Dependent &&
157 "Should not generate implicit declarations for dependent cases, "
158 "and don't know how to handle them anyway.");
160 // noexcept(false) -> no spec on the new function
161 if (NR == FunctionProtoType::NR_Throw) {
163 ComputedEST = EST_None;
165 // noexcept(true) won't change anything either.
169 assert(EST == EST_Dynamic && "EST case not considered earlier.");
170 assert(ComputedEST != EST_None &&
171 "Shouldn't collect exceptions when throw-all is guaranteed.");
172 ComputedEST = EST_Dynamic;
173 // Record the exceptions in this function's exception specification.
174 for (FunctionProtoType::exception_iterator E = Proto->exception_begin(),
175 EEnd = Proto->exception_end();
177 if (ExceptionsSeen.insert(Context->getCanonicalType(*E)))
178 Exceptions.push_back(*E);
181 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
182 if (!E || ComputedEST == EST_MSAny || ComputedEST == EST_Delayed)
187 // C++0x [except.spec]p14:
188 // [An] implicit exception-specification specifies the type-id T if and
189 // only if T is allowed by the exception-specification of a function directly
190 // invoked by f’s implicit definition; f shall allow all exceptions if any
191 // function it directly invokes allows all exceptions, and f shall allow no
192 // exceptions if every function it directly invokes allows no exceptions.
194 // Note in particular that if an implicit exception-specification is generated
195 // for a function containing a throw-expression, that specification can still
196 // be noexcept(true).
198 // Note also that 'directly invoked' is not defined in the standard, and there
199 // is no indication that we should only consider potentially-evaluated calls.
201 // Ultimately we should implement the intent of the standard: the exception
202 // specification should be the set of exceptions which can be thrown by the
203 // implicit definition. For now, we assume that any non-nothrow expression can
204 // throw any exception.
206 if (E->CanThrow(*Context))
207 ComputedEST = EST_None;
211 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
212 SourceLocation EqualLoc) {
213 if (RequireCompleteType(Param->getLocation(), Param->getType(),
214 diag::err_typecheck_decl_incomplete_type)) {
215 Param->setInvalidDecl();
219 // C++ [dcl.fct.default]p5
220 // A default argument expression is implicitly converted (clause
221 // 4) to the parameter type. The default argument expression has
222 // the same semantic constraints as the initializer expression in
223 // a declaration of a variable of the parameter type, using the
224 // copy-initialization semantics (8.5).
225 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
227 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
229 InitializationSequence InitSeq(*this, Entity, Kind, &Arg, 1);
230 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
231 MultiExprArg(*this, &Arg, 1));
232 if (Result.isInvalid())
234 Arg = Result.takeAs<Expr>();
236 CheckImplicitConversions(Arg, EqualLoc);
237 Arg = MaybeCreateExprWithCleanups(Arg);
239 // Okay: add the default argument to the parameter
240 Param->setDefaultArg(Arg);
242 // We have already instantiated this parameter; provide each of the
243 // instantiations with the uninstantiated default argument.
244 UnparsedDefaultArgInstantiationsMap::iterator InstPos
245 = UnparsedDefaultArgInstantiations.find(Param);
246 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
247 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
248 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
250 // We're done tracking this parameter's instantiations.
251 UnparsedDefaultArgInstantiations.erase(InstPos);
257 /// ActOnParamDefaultArgument - Check whether the default argument
258 /// provided for a function parameter is well-formed. If so, attach it
259 /// to the parameter declaration.
261 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
263 if (!param || !DefaultArg)
266 ParmVarDecl *Param = cast<ParmVarDecl>(param);
267 UnparsedDefaultArgLocs.erase(Param);
269 // Default arguments are only permitted in C++
270 if (!getLangOptions().CPlusPlus) {
271 Diag(EqualLoc, diag::err_param_default_argument)
272 << DefaultArg->getSourceRange();
273 Param->setInvalidDecl();
277 // Check for unexpanded parameter packs.
278 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
279 Param->setInvalidDecl();
283 // Check that the default argument is well-formed
284 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
285 if (DefaultArgChecker.Visit(DefaultArg)) {
286 Param->setInvalidDecl();
290 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
293 /// ActOnParamUnparsedDefaultArgument - We've seen a default
294 /// argument for a function parameter, but we can't parse it yet
295 /// because we're inside a class definition. Note that this default
296 /// argument will be parsed later.
297 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
298 SourceLocation EqualLoc,
299 SourceLocation ArgLoc) {
303 ParmVarDecl *Param = cast<ParmVarDecl>(param);
305 Param->setUnparsedDefaultArg();
307 UnparsedDefaultArgLocs[Param] = ArgLoc;
310 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
311 /// the default argument for the parameter param failed.
312 void Sema::ActOnParamDefaultArgumentError(Decl *param) {
316 ParmVarDecl *Param = cast<ParmVarDecl>(param);
318 Param->setInvalidDecl();
320 UnparsedDefaultArgLocs.erase(Param);
323 /// CheckExtraCXXDefaultArguments - Check for any extra default
324 /// arguments in the declarator, which is not a function declaration
325 /// or definition and therefore is not permitted to have default
326 /// arguments. This routine should be invoked for every declarator
327 /// that is not a function declaration or definition.
328 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
329 // C++ [dcl.fct.default]p3
330 // A default argument expression shall be specified only in the
331 // parameter-declaration-clause of a function declaration or in a
332 // template-parameter (14.1). It shall not be specified for a
333 // parameter pack. If it is specified in a
334 // parameter-declaration-clause, it shall not occur within a
335 // declarator or abstract-declarator of a parameter-declaration.
336 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
337 DeclaratorChunk &chunk = D.getTypeObject(i);
338 if (chunk.Kind == DeclaratorChunk::Function) {
339 for (unsigned argIdx = 0, e = chunk.Fun.NumArgs; argIdx != e; ++argIdx) {
341 cast<ParmVarDecl>(chunk.Fun.ArgInfo[argIdx].Param);
342 if (Param->hasUnparsedDefaultArg()) {
343 CachedTokens *Toks = chunk.Fun.ArgInfo[argIdx].DefaultArgTokens;
344 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
345 << SourceRange((*Toks)[1].getLocation(), Toks->back().getLocation());
347 chunk.Fun.ArgInfo[argIdx].DefaultArgTokens = 0;
348 } else if (Param->getDefaultArg()) {
349 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
350 << Param->getDefaultArg()->getSourceRange();
351 Param->setDefaultArg(0);
358 // MergeCXXFunctionDecl - Merge two declarations of the same C++
359 // function, once we already know that they have the same
360 // type. Subroutine of MergeFunctionDecl. Returns true if there was an
361 // error, false otherwise.
362 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old) {
363 bool Invalid = false;
365 // C++ [dcl.fct.default]p4:
366 // For non-template functions, default arguments can be added in
367 // later declarations of a function in the same
368 // scope. Declarations in different scopes have completely
369 // distinct sets of default arguments. That is, declarations in
370 // inner scopes do not acquire default arguments from
371 // declarations in outer scopes, and vice versa. In a given
372 // function declaration, all parameters subsequent to a
373 // parameter with a default argument shall have default
374 // arguments supplied in this or previous declarations. A
375 // default argument shall not be redefined by a later
376 // declaration (not even to the same value).
378 // C++ [dcl.fct.default]p6:
379 // Except for member functions of class templates, the default arguments
380 // in a member function definition that appears outside of the class
381 // definition are added to the set of default arguments provided by the
382 // member function declaration in the class definition.
383 for (unsigned p = 0, NumParams = Old->getNumParams(); p < NumParams; ++p) {
384 ParmVarDecl *OldParam = Old->getParamDecl(p);
385 ParmVarDecl *NewParam = New->getParamDecl(p);
387 if (OldParam->hasDefaultArg() && NewParam->hasDefaultArg()) {
389 unsigned DiagDefaultParamID =
390 diag::err_param_default_argument_redefinition;
392 // MSVC accepts that default parameters be redefined for member functions
393 // of template class. The new default parameter's value is ignored.
395 if (getLangOptions().Microsoft) {
396 CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(New);
397 if (MD && MD->getParent()->getDescribedClassTemplate()) {
398 // Merge the old default argument into the new parameter.
399 NewParam->setHasInheritedDefaultArg();
400 if (OldParam->hasUninstantiatedDefaultArg())
401 NewParam->setUninstantiatedDefaultArg(
402 OldParam->getUninstantiatedDefaultArg());
404 NewParam->setDefaultArg(OldParam->getInit());
405 DiagDefaultParamID = diag::warn_param_default_argument_redefinition;
410 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
411 // hint here. Alternatively, we could walk the type-source information
412 // for NewParam to find the last source location in the type... but it
413 // isn't worth the effort right now. This is the kind of test case that
414 // is hard to get right:
416 // void g(int (*fp)(int) = f);
417 // void g(int (*fp)(int) = &f);
418 Diag(NewParam->getLocation(), DiagDefaultParamID)
419 << NewParam->getDefaultArgRange();
421 // Look for the function declaration where the default argument was
422 // actually written, which may be a declaration prior to Old.
423 for (FunctionDecl *Older = Old->getPreviousDeclaration();
424 Older; Older = Older->getPreviousDeclaration()) {
425 if (!Older->getParamDecl(p)->hasDefaultArg())
428 OldParam = Older->getParamDecl(p);
431 Diag(OldParam->getLocation(), diag::note_previous_definition)
432 << OldParam->getDefaultArgRange();
433 } else if (OldParam->hasDefaultArg()) {
434 // Merge the old default argument into the new parameter.
435 // It's important to use getInit() here; getDefaultArg()
436 // strips off any top-level ExprWithCleanups.
437 NewParam->setHasInheritedDefaultArg();
438 if (OldParam->hasUninstantiatedDefaultArg())
439 NewParam->setUninstantiatedDefaultArg(
440 OldParam->getUninstantiatedDefaultArg());
442 NewParam->setDefaultArg(OldParam->getInit());
443 } else if (NewParam->hasDefaultArg()) {
444 if (New->getDescribedFunctionTemplate()) {
445 // Paragraph 4, quoted above, only applies to non-template functions.
446 Diag(NewParam->getLocation(),
447 diag::err_param_default_argument_template_redecl)
448 << NewParam->getDefaultArgRange();
449 Diag(Old->getLocation(), diag::note_template_prev_declaration)
451 } else if (New->getTemplateSpecializationKind()
452 != TSK_ImplicitInstantiation &&
453 New->getTemplateSpecializationKind() != TSK_Undeclared) {
454 // C++ [temp.expr.spec]p21:
455 // Default function arguments shall not be specified in a declaration
456 // or a definition for one of the following explicit specializations:
457 // - the explicit specialization of a function template;
458 // - the explicit specialization of a member function template;
459 // - the explicit specialization of a member function of a class
460 // template where the class template specialization to which the
461 // member function specialization belongs is implicitly
463 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
464 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
465 << New->getDeclName()
466 << NewParam->getDefaultArgRange();
467 } else if (New->getDeclContext()->isDependentContext()) {
468 // C++ [dcl.fct.default]p6 (DR217):
469 // Default arguments for a member function of a class template shall
470 // be specified on the initial declaration of the member function
471 // within the class template.
473 // Reading the tea leaves a bit in DR217 and its reference to DR205
474 // leads me to the conclusion that one cannot add default function
475 // arguments for an out-of-line definition of a member function of a
478 if (CXXRecordDecl *Record
479 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
480 if (Record->getDescribedClassTemplate())
482 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
488 Diag(NewParam->getLocation(),
489 diag::err_param_default_argument_member_template_redecl)
491 << NewParam->getDefaultArgRange();
492 } else if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(New)) {
493 CXXSpecialMember NewSM = getSpecialMember(Ctor),
494 OldSM = getSpecialMember(cast<CXXConstructorDecl>(Old));
495 if (NewSM != OldSM) {
496 Diag(NewParam->getLocation(),diag::warn_default_arg_makes_ctor_special)
497 << NewParam->getDefaultArgRange() << NewSM;
498 Diag(Old->getLocation(), diag::note_previous_declaration_special)
505 if (CheckEquivalentExceptionSpec(Old, New))
511 /// \brief Merge the exception specifications of two variable declarations.
513 /// This is called when there's a redeclaration of a VarDecl. The function
514 /// checks if the redeclaration might have an exception specification and
515 /// validates compatibility and merges the specs if necessary.
516 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
517 // Shortcut if exceptions are disabled.
518 if (!getLangOptions().CXXExceptions)
521 assert(Context.hasSameType(New->getType(), Old->getType()) &&
522 "Should only be called if types are otherwise the same.");
524 QualType NewType = New->getType();
525 QualType OldType = Old->getType();
527 // We're only interested in pointers and references to functions, as well
528 // as pointers to member functions.
529 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
530 NewType = R->getPointeeType();
531 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
532 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
533 NewType = P->getPointeeType();
534 OldType = OldType->getAs<PointerType>()->getPointeeType();
535 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
536 NewType = M->getPointeeType();
537 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
540 if (!NewType->isFunctionProtoType())
543 // There's lots of special cases for functions. For function pointers, system
544 // libraries are hopefully not as broken so that we don't need these
546 if (CheckEquivalentExceptionSpec(
547 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
548 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
549 New->setInvalidDecl();
553 /// CheckCXXDefaultArguments - Verify that the default arguments for a
554 /// function declaration are well-formed according to C++
555 /// [dcl.fct.default].
556 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
557 unsigned NumParams = FD->getNumParams();
560 // Find first parameter with a default argument
561 for (p = 0; p < NumParams; ++p) {
562 ParmVarDecl *Param = FD->getParamDecl(p);
563 if (Param->hasDefaultArg())
567 // C++ [dcl.fct.default]p4:
568 // In a given function declaration, all parameters
569 // subsequent to a parameter with a default argument shall
570 // have default arguments supplied in this or previous
571 // declarations. A default argument shall not be redefined
572 // by a later declaration (not even to the same value).
573 unsigned LastMissingDefaultArg = 0;
574 for (; p < NumParams; ++p) {
575 ParmVarDecl *Param = FD->getParamDecl(p);
576 if (!Param->hasDefaultArg()) {
577 if (Param->isInvalidDecl())
578 /* We already complained about this parameter. */;
579 else if (Param->getIdentifier())
580 Diag(Param->getLocation(),
581 diag::err_param_default_argument_missing_name)
582 << Param->getIdentifier();
584 Diag(Param->getLocation(),
585 diag::err_param_default_argument_missing);
587 LastMissingDefaultArg = p;
591 if (LastMissingDefaultArg > 0) {
592 // Some default arguments were missing. Clear out all of the
593 // default arguments up to (and including) the last missing
594 // default argument, so that we leave the function parameters
595 // in a semantically valid state.
596 for (p = 0; p <= LastMissingDefaultArg; ++p) {
597 ParmVarDecl *Param = FD->getParamDecl(p);
598 if (Param->hasDefaultArg()) {
599 Param->setDefaultArg(0);
605 /// isCurrentClassName - Determine whether the identifier II is the
606 /// name of the class type currently being defined. In the case of
607 /// nested classes, this will only return true if II is the name of
608 /// the innermost class.
609 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
610 const CXXScopeSpec *SS) {
611 assert(getLangOptions().CPlusPlus && "No class names in C!");
613 CXXRecordDecl *CurDecl;
614 if (SS && SS->isSet() && !SS->isInvalid()) {
615 DeclContext *DC = computeDeclContext(*SS, true);
616 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
618 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
620 if (CurDecl && CurDecl->getIdentifier())
621 return &II == CurDecl->getIdentifier();
626 /// \brief Check the validity of a C++ base class specifier.
628 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
629 /// and returns NULL otherwise.
631 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
632 SourceRange SpecifierRange,
633 bool Virtual, AccessSpecifier Access,
634 TypeSourceInfo *TInfo,
635 SourceLocation EllipsisLoc) {
636 QualType BaseType = TInfo->getType();
638 // C++ [class.union]p1:
639 // A union shall not have base classes.
640 if (Class->isUnion()) {
641 Diag(Class->getLocation(), diag::err_base_clause_on_union)
646 if (EllipsisLoc.isValid() &&
647 !TInfo->getType()->containsUnexpandedParameterPack()) {
648 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
649 << TInfo->getTypeLoc().getSourceRange();
650 EllipsisLoc = SourceLocation();
653 if (BaseType->isDependentType())
654 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
655 Class->getTagKind() == TTK_Class,
656 Access, TInfo, EllipsisLoc);
658 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
660 // Base specifiers must be record types.
661 if (!BaseType->isRecordType()) {
662 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
666 // C++ [class.union]p1:
667 // A union shall not be used as a base class.
668 if (BaseType->isUnionType()) {
669 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
673 // C++ [class.derived]p2:
674 // The class-name in a base-specifier shall not be an incompletely
676 if (RequireCompleteType(BaseLoc, BaseType,
677 PDiag(diag::err_incomplete_base_class)
678 << SpecifierRange)) {
679 Class->setInvalidDecl();
683 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
684 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
685 assert(BaseDecl && "Record type has no declaration");
686 BaseDecl = BaseDecl->getDefinition();
687 assert(BaseDecl && "Base type is not incomplete, but has no definition");
688 CXXRecordDecl * CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
689 assert(CXXBaseDecl && "Base type is not a C++ type");
692 // If a class is marked final and it appears as a base-type-specifier in
693 // base-clause, the program is ill-formed.
694 if (CXXBaseDecl->hasAttr<FinalAttr>()) {
695 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
696 << CXXBaseDecl->getDeclName();
697 Diag(CXXBaseDecl->getLocation(), diag::note_previous_decl)
698 << CXXBaseDecl->getDeclName();
702 if (BaseDecl->isInvalidDecl())
703 Class->setInvalidDecl();
705 // Create the base specifier.
706 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
707 Class->getTagKind() == TTK_Class,
708 Access, TInfo, EllipsisLoc);
711 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
712 /// one entry in the base class list of a class specifier, for
714 /// class foo : public bar, virtual private baz {
715 /// 'public bar' and 'virtual private baz' are each base-specifiers.
717 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
718 bool Virtual, AccessSpecifier Access,
719 ParsedType basetype, SourceLocation BaseLoc,
720 SourceLocation EllipsisLoc) {
724 AdjustDeclIfTemplate(classdecl);
725 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
729 TypeSourceInfo *TInfo = 0;
730 GetTypeFromParser(basetype, &TInfo);
732 if (EllipsisLoc.isInvalid() &&
733 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
737 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
738 Virtual, Access, TInfo,
745 /// \brief Performs the actual work of attaching the given base class
746 /// specifiers to a C++ class.
747 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
752 // Used to keep track of which base types we have already seen, so
753 // that we can properly diagnose redundant direct base types. Note
754 // that the key is always the unqualified canonical type of the base
756 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
758 // Copy non-redundant base specifiers into permanent storage.
759 unsigned NumGoodBases = 0;
760 bool Invalid = false;
761 for (unsigned idx = 0; idx < NumBases; ++idx) {
763 = Context.getCanonicalType(Bases[idx]->getType());
764 NewBaseType = NewBaseType.getLocalUnqualifiedType();
765 if (!Class->hasObjectMember()) {
766 if (const RecordType *FDTTy =
767 NewBaseType.getTypePtr()->getAs<RecordType>())
768 if (FDTTy->getDecl()->hasObjectMember())
769 Class->setHasObjectMember(true);
772 if (KnownBaseTypes[NewBaseType]) {
774 // A class shall not be specified as a direct base class of a
775 // derived class more than once.
776 Diag(Bases[idx]->getSourceRange().getBegin(),
777 diag::err_duplicate_base_class)
778 << KnownBaseTypes[NewBaseType]->getType()
779 << Bases[idx]->getSourceRange();
781 // Delete the duplicate base class specifier; we're going to
782 // overwrite its pointer later.
783 Context.Deallocate(Bases[idx]);
787 // Okay, add this new base class.
788 KnownBaseTypes[NewBaseType] = Bases[idx];
789 Bases[NumGoodBases++] = Bases[idx];
793 // Attach the remaining base class specifiers to the derived class.
794 Class->setBases(Bases, NumGoodBases);
796 // Delete the remaining (good) base class specifiers, since their
797 // data has been copied into the CXXRecordDecl.
798 for (unsigned idx = 0; idx < NumGoodBases; ++idx)
799 Context.Deallocate(Bases[idx]);
804 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
805 /// class, after checking whether there are any duplicate base
807 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl, BaseTy **Bases,
809 if (!ClassDecl || !Bases || !NumBases)
812 AdjustDeclIfTemplate(ClassDecl);
813 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl),
814 (CXXBaseSpecifier**)(Bases), NumBases);
817 static CXXRecordDecl *GetClassForType(QualType T) {
818 if (const RecordType *RT = T->getAs<RecordType>())
819 return cast<CXXRecordDecl>(RT->getDecl());
820 else if (const InjectedClassNameType *ICT = T->getAs<InjectedClassNameType>())
821 return ICT->getDecl();
826 /// \brief Determine whether the type \p Derived is a C++ class that is
827 /// derived from the type \p Base.
828 bool Sema::IsDerivedFrom(QualType Derived, QualType Base) {
829 if (!getLangOptions().CPlusPlus)
832 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
836 CXXRecordDecl *BaseRD = GetClassForType(Base);
840 // FIXME: instantiate DerivedRD if necessary. We need a PoI for this.
841 return DerivedRD->hasDefinition() && DerivedRD->isDerivedFrom(BaseRD);
844 /// \brief Determine whether the type \p Derived is a C++ class that is
845 /// derived from the type \p Base.
846 bool Sema::IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths) {
847 if (!getLangOptions().CPlusPlus)
850 CXXRecordDecl *DerivedRD = GetClassForType(Derived);
854 CXXRecordDecl *BaseRD = GetClassForType(Base);
858 return DerivedRD->isDerivedFrom(BaseRD, Paths);
861 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
862 CXXCastPath &BasePathArray) {
863 assert(BasePathArray.empty() && "Base path array must be empty!");
864 assert(Paths.isRecordingPaths() && "Must record paths!");
866 const CXXBasePath &Path = Paths.front();
868 // We first go backward and check if we have a virtual base.
869 // FIXME: It would be better if CXXBasePath had the base specifier for
870 // the nearest virtual base.
872 for (unsigned I = Path.size(); I != 0; --I) {
873 if (Path[I - 1].Base->isVirtual()) {
879 // Now add all bases.
880 for (unsigned I = Start, E = Path.size(); I != E; ++I)
881 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
884 /// \brief Determine whether the given base path includes a virtual
886 bool Sema::BasePathInvolvesVirtualBase(const CXXCastPath &BasePath) {
887 for (CXXCastPath::const_iterator B = BasePath.begin(),
888 BEnd = BasePath.end();
890 if ((*B)->isVirtual())
896 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
897 /// conversion (where Derived and Base are class types) is
898 /// well-formed, meaning that the conversion is unambiguous (and
899 /// that all of the base classes are accessible). Returns true
900 /// and emits a diagnostic if the code is ill-formed, returns false
901 /// otherwise. Loc is the location where this routine should point to
902 /// if there is an error, and Range is the source range to highlight
903 /// if there is an error.
905 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
906 unsigned InaccessibleBaseID,
907 unsigned AmbigiousBaseConvID,
908 SourceLocation Loc, SourceRange Range,
909 DeclarationName Name,
910 CXXCastPath *BasePath) {
911 // First, determine whether the path from Derived to Base is
912 // ambiguous. This is slightly more expensive than checking whether
913 // the Derived to Base conversion exists, because here we need to
914 // explore multiple paths to determine if there is an ambiguity.
915 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
916 /*DetectVirtual=*/false);
917 bool DerivationOkay = IsDerivedFrom(Derived, Base, Paths);
918 assert(DerivationOkay &&
919 "Can only be used with a derived-to-base conversion");
920 (void)DerivationOkay;
922 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType())) {
923 if (InaccessibleBaseID) {
924 // Check that the base class can be accessed.
925 switch (CheckBaseClassAccess(Loc, Base, Derived, Paths.front(),
926 InaccessibleBaseID)) {
927 case AR_inaccessible:
936 // Build a base path if necessary.
938 BuildBasePathArray(Paths, *BasePath);
942 // We know that the derived-to-base conversion is ambiguous, and
943 // we're going to produce a diagnostic. Perform the derived-to-base
944 // search just one more time to compute all of the possible paths so
945 // that we can print them out. This is more expensive than any of
946 // the previous derived-to-base checks we've done, but at this point
947 // performance isn't as much of an issue.
949 Paths.setRecordingPaths(true);
950 bool StillOkay = IsDerivedFrom(Derived, Base, Paths);
951 assert(StillOkay && "Can only be used with a derived-to-base conversion");
954 // Build up a textual representation of the ambiguous paths, e.g.,
955 // D -> B -> A, that will be used to illustrate the ambiguous
956 // conversions in the diagnostic. We only print one of the paths
957 // to each base class subobject.
958 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
960 Diag(Loc, AmbigiousBaseConvID)
961 << Derived << Base << PathDisplayStr << Range << Name;
966 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
967 SourceLocation Loc, SourceRange Range,
968 CXXCastPath *BasePath,
970 return CheckDerivedToBaseConversion(Derived, Base,
972 : diag::err_upcast_to_inaccessible_base,
973 diag::err_ambiguous_derived_to_base_conv,
974 Loc, Range, DeclarationName(),
979 /// @brief Builds a string representing ambiguous paths from a
980 /// specific derived class to different subobjects of the same base
983 /// This function builds a string that can be used in error messages
984 /// to show the different paths that one can take through the
985 /// inheritance hierarchy to go from the derived class to different
986 /// subobjects of a base class. The result looks something like this:
988 /// struct D -> struct B -> struct A
989 /// struct D -> struct C -> struct A
991 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
992 std::string PathDisplayStr;
993 std::set<unsigned> DisplayedPaths;
994 for (CXXBasePaths::paths_iterator Path = Paths.begin();
995 Path != Paths.end(); ++Path) {
996 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
997 // We haven't displayed a path to this particular base
998 // class subobject yet.
999 PathDisplayStr += "\n ";
1000 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
1001 for (CXXBasePath::const_iterator Element = Path->begin();
1002 Element != Path->end(); ++Element)
1003 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
1007 return PathDisplayStr;
1010 //===----------------------------------------------------------------------===//
1011 // C++ class member Handling
1012 //===----------------------------------------------------------------------===//
1014 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
1015 Decl *Sema::ActOnAccessSpecifier(AccessSpecifier Access,
1016 SourceLocation ASLoc,
1017 SourceLocation ColonLoc) {
1018 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
1019 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
1021 CurContext->addHiddenDecl(ASDecl);
1025 /// CheckOverrideControl - Check C++0x override control semantics.
1026 void Sema::CheckOverrideControl(const Decl *D) {
1027 const CXXMethodDecl *MD = llvm::dyn_cast<CXXMethodDecl>(D);
1028 if (!MD || !MD->isVirtual())
1031 if (MD->isDependentContext())
1034 // C++0x [class.virtual]p3:
1035 // If a virtual function is marked with the virt-specifier override and does
1036 // not override a member function of a base class,
1037 // the program is ill-formed.
1038 bool HasOverriddenMethods =
1039 MD->begin_overridden_methods() != MD->end_overridden_methods();
1040 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods) {
1041 Diag(MD->getLocation(),
1042 diag::err_function_marked_override_not_overriding)
1043 << MD->getDeclName();
1048 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
1049 /// function overrides a virtual member function marked 'final', according to
1050 /// C++0x [class.virtual]p3.
1051 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
1052 const CXXMethodDecl *Old) {
1053 if (!Old->hasAttr<FinalAttr>())
1056 Diag(New->getLocation(), diag::err_final_function_overridden)
1057 << New->getDeclName();
1058 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
1062 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
1063 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
1064 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
1065 /// one has been parsed, and 'HasDeferredInit' is true if an initializer is
1066 /// present but parsing it has been deferred.
1068 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
1069 MultiTemplateParamsArg TemplateParameterLists,
1070 ExprTy *BW, const VirtSpecifiers &VS,
1071 ExprTy *InitExpr, bool HasDeferredInit,
1072 bool IsDefinition) {
1073 const DeclSpec &DS = D.getDeclSpec();
1074 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
1075 DeclarationName Name = NameInfo.getName();
1076 SourceLocation Loc = NameInfo.getLoc();
1078 // For anonymous bitfields, the location should point to the type.
1079 if (Loc.isInvalid())
1080 Loc = D.getSourceRange().getBegin();
1082 Expr *BitWidth = static_cast<Expr*>(BW);
1083 Expr *Init = static_cast<Expr*>(InitExpr);
1085 assert(isa<CXXRecordDecl>(CurContext));
1086 assert(!DS.isFriendSpecified());
1087 assert(!Init || !HasDeferredInit);
1089 bool isFunc = false;
1090 if (D.isFunctionDeclarator())
1092 else if (D.getNumTypeObjects() == 0 &&
1093 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_typename) {
1094 QualType TDType = GetTypeFromParser(DS.getRepAsType());
1095 isFunc = TDType->isFunctionType();
1098 // C++ 9.2p6: A member shall not be declared to have automatic storage
1099 // duration (auto, register) or with the extern storage-class-specifier.
1100 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
1101 // data members and cannot be applied to names declared const or static,
1102 // and cannot be applied to reference members.
1103 switch (DS.getStorageClassSpec()) {
1104 case DeclSpec::SCS_unspecified:
1105 case DeclSpec::SCS_typedef:
1106 case DeclSpec::SCS_static:
1109 case DeclSpec::SCS_mutable:
1111 if (DS.getStorageClassSpecLoc().isValid())
1112 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
1114 Diag(DS.getThreadSpecLoc(), diag::err_mutable_function);
1116 // FIXME: It would be nicer if the keyword was ignored only for this
1117 // declarator. Otherwise we could get follow-up errors.
1118 D.getMutableDeclSpec().ClearStorageClassSpecs();
1122 if (DS.getStorageClassSpecLoc().isValid())
1123 Diag(DS.getStorageClassSpecLoc(),
1124 diag::err_storageclass_invalid_for_member);
1126 Diag(DS.getThreadSpecLoc(), diag::err_storageclass_invalid_for_member);
1127 D.getMutableDeclSpec().ClearStorageClassSpecs();
1130 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
1131 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
1136 CXXScopeSpec &SS = D.getCXXScopeSpec();
1138 if (SS.isSet() && !SS.isInvalid()) {
1139 // The user provided a superfluous scope specifier inside a class
1145 DeclContext *DC = 0;
1146 if ((DC = computeDeclContext(SS, false)) && DC->Equals(CurContext))
1147 Diag(D.getIdentifierLoc(), diag::warn_member_extra_qualification)
1148 << Name << FixItHint::CreateRemoval(SS.getRange());
1150 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
1151 << Name << SS.getRange();
1156 // FIXME: Check for template parameters!
1157 // FIXME: Check that the name is an identifier!
1158 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D, BitWidth,
1159 HasDeferredInit, AS);
1160 assert(Member && "HandleField never returns null");
1162 assert(!HasDeferredInit);
1164 Member = HandleDeclarator(S, D, move(TemplateParameterLists), IsDefinition);
1169 // Non-instance-fields can't have a bitfield.
1171 if (Member->isInvalidDecl()) {
1172 // don't emit another diagnostic.
1173 } else if (isa<VarDecl>(Member)) {
1174 // C++ 9.6p3: A bit-field shall not be a static member.
1175 // "static member 'A' cannot be a bit-field"
1176 Diag(Loc, diag::err_static_not_bitfield)
1177 << Name << BitWidth->getSourceRange();
1178 } else if (isa<TypedefDecl>(Member)) {
1179 // "typedef member 'x' cannot be a bit-field"
1180 Diag(Loc, diag::err_typedef_not_bitfield)
1181 << Name << BitWidth->getSourceRange();
1183 // A function typedef ("typedef int f(); f a;").
1184 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
1185 Diag(Loc, diag::err_not_integral_type_bitfield)
1186 << Name << cast<ValueDecl>(Member)->getType()
1187 << BitWidth->getSourceRange();
1191 Member->setInvalidDecl();
1194 Member->setAccess(AS);
1196 // If we have declared a member function template, set the access of the
1197 // templated declaration as well.
1198 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
1199 FunTmpl->getTemplatedDecl()->setAccess(AS);
1202 if (VS.isOverrideSpecified()) {
1203 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1204 if (!MD || !MD->isVirtual()) {
1205 Diag(Member->getLocStart(),
1206 diag::override_keyword_only_allowed_on_virtual_member_functions)
1207 << "override" << FixItHint::CreateRemoval(VS.getOverrideLoc());
1209 MD->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context));
1211 if (VS.isFinalSpecified()) {
1212 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
1213 if (!MD || !MD->isVirtual()) {
1214 Diag(Member->getLocStart(),
1215 diag::override_keyword_only_allowed_on_virtual_member_functions)
1216 << "final" << FixItHint::CreateRemoval(VS.getFinalLoc());
1218 MD->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context));
1221 if (VS.getLastLocation().isValid()) {
1222 // Update the end location of a method that has a virt-specifiers.
1223 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
1224 MD->setRangeEnd(VS.getLastLocation());
1227 CheckOverrideControl(Member);
1229 assert((Name || isInstField) && "No identifier for non-field ?");
1232 AddInitializerToDecl(Member, Init, false,
1233 DS.getTypeSpecType() == DeclSpec::TST_auto);
1234 else if (DS.getTypeSpecType() == DeclSpec::TST_auto &&
1235 DS.getStorageClassSpec() == DeclSpec::SCS_static) {
1236 // C++0x [dcl.spec.auto]p4: 'auto' can only be used in the type of a static
1237 // data member if a brace-or-equal-initializer is provided.
1238 Diag(Loc, diag::err_auto_var_requires_init)
1239 << Name << cast<ValueDecl>(Member)->getType();
1240 Member->setInvalidDecl();
1243 FinalizeDeclaration(Member);
1246 FieldCollector->Add(cast<FieldDecl>(Member));
1250 /// ActOnCXXInClassMemberInitializer - This is invoked after parsing an
1251 /// in-class initializer for a non-static C++ class member. Such parsing
1252 /// is deferred until the class is complete.
1254 Sema::ActOnCXXInClassMemberInitializer(Decl *D, SourceLocation EqualLoc,
1256 FieldDecl *FD = cast<FieldDecl>(D);
1259 FD->setInvalidDecl();
1260 FD->removeInClassInitializer();
1264 ExprResult Init = InitExpr;
1265 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
1266 // FIXME: if there is no EqualLoc, this is list-initialization.
1267 Init = PerformCopyInitialization(
1268 InitializedEntity::InitializeMember(FD), EqualLoc, InitExpr);
1269 if (Init.isInvalid()) {
1270 FD->setInvalidDecl();
1274 CheckImplicitConversions(Init.get(), EqualLoc);
1277 // C++0x [class.base.init]p7:
1278 // The initialization of each base and member constitutes a
1280 Init = MaybeCreateExprWithCleanups(Init);
1281 if (Init.isInvalid()) {
1282 FD->setInvalidDecl();
1286 InitExpr = Init.release();
1288 FD->setInClassInitializer(InitExpr);
1291 /// \brief Find the direct and/or virtual base specifiers that
1292 /// correspond to the given base type, for use in base initialization
1293 /// within a constructor.
1294 static bool FindBaseInitializer(Sema &SemaRef,
1295 CXXRecordDecl *ClassDecl,
1297 const CXXBaseSpecifier *&DirectBaseSpec,
1298 const CXXBaseSpecifier *&VirtualBaseSpec) {
1299 // First, check for a direct base class.
1301 for (CXXRecordDecl::base_class_const_iterator Base
1302 = ClassDecl->bases_begin();
1303 Base != ClassDecl->bases_end(); ++Base) {
1304 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base->getType())) {
1305 // We found a direct base of this type. That's what we're
1307 DirectBaseSpec = &*Base;
1312 // Check for a virtual base class.
1313 // FIXME: We might be able to short-circuit this if we know in advance that
1314 // there are no virtual bases.
1315 VirtualBaseSpec = 0;
1316 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
1317 // We haven't found a base yet; search the class hierarchy for a
1318 // virtual base class.
1319 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1320 /*DetectVirtual=*/false);
1321 if (SemaRef.IsDerivedFrom(SemaRef.Context.getTypeDeclType(ClassDecl),
1323 for (CXXBasePaths::paths_iterator Path = Paths.begin();
1324 Path != Paths.end(); ++Path) {
1325 if (Path->back().Base->isVirtual()) {
1326 VirtualBaseSpec = Path->back().Base;
1333 return DirectBaseSpec || VirtualBaseSpec;
1336 /// ActOnMemInitializer - Handle a C++ member initializer.
1338 Sema::ActOnMemInitializer(Decl *ConstructorD,
1341 IdentifierInfo *MemberOrBase,
1342 ParsedType TemplateTypeTy,
1343 SourceLocation IdLoc,
1344 SourceLocation LParenLoc,
1345 ExprTy **Args, unsigned NumArgs,
1346 SourceLocation RParenLoc,
1347 SourceLocation EllipsisLoc) {
1351 AdjustDeclIfTemplate(ConstructorD);
1353 CXXConstructorDecl *Constructor
1354 = dyn_cast<CXXConstructorDecl>(ConstructorD);
1356 // The user wrote a constructor initializer on a function that is
1357 // not a C++ constructor. Ignore the error for now, because we may
1358 // have more member initializers coming; we'll diagnose it just
1359 // once in ActOnMemInitializers.
1363 CXXRecordDecl *ClassDecl = Constructor->getParent();
1365 // C++ [class.base.init]p2:
1366 // Names in a mem-initializer-id are looked up in the scope of the
1367 // constructor's class and, if not found in that scope, are looked
1368 // up in the scope containing the constructor's definition.
1369 // [Note: if the constructor's class contains a member with the
1370 // same name as a direct or virtual base class of the class, a
1371 // mem-initializer-id naming the member or base class and composed
1372 // of a single identifier refers to the class member. A
1373 // mem-initializer-id for the hidden base class may be specified
1374 // using a qualified name. ]
1375 if (!SS.getScopeRep() && !TemplateTypeTy) {
1376 // Look for a member, first.
1377 FieldDecl *Member = 0;
1378 DeclContext::lookup_result Result
1379 = ClassDecl->lookup(MemberOrBase);
1380 if (Result.first != Result.second) {
1381 Member = dyn_cast<FieldDecl>(*Result.first);
1384 if (EllipsisLoc.isValid())
1385 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1386 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1388 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1389 LParenLoc, RParenLoc);
1392 // Handle anonymous union case.
1393 if (IndirectFieldDecl* IndirectField
1394 = dyn_cast<IndirectFieldDecl>(*Result.first)) {
1395 if (EllipsisLoc.isValid())
1396 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
1397 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1399 return BuildMemberInitializer(IndirectField, (Expr**)Args,
1401 LParenLoc, RParenLoc);
1405 // It didn't name a member, so see if it names a class.
1407 TypeSourceInfo *TInfo = 0;
1409 if (TemplateTypeTy) {
1410 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
1412 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
1413 LookupParsedName(R, S, &SS);
1415 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
1417 if (R.isAmbiguous()) return true;
1419 // We don't want access-control diagnostics here.
1420 R.suppressDiagnostics();
1422 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
1423 bool NotUnknownSpecialization = false;
1424 DeclContext *DC = computeDeclContext(SS, false);
1425 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
1426 NotUnknownSpecialization = !Record->hasAnyDependentBases();
1428 if (!NotUnknownSpecialization) {
1429 // When the scope specifier can refer to a member of an unknown
1430 // specialization, we take it as a type name.
1431 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
1432 SS.getWithLocInContext(Context),
1433 *MemberOrBase, IdLoc);
1434 if (BaseType.isNull())
1438 R.setLookupName(MemberOrBase);
1442 // If no results were found, try to correct typos.
1443 if (R.empty() && BaseType.isNull() &&
1444 CorrectTypo(R, S, &SS, ClassDecl, 0, CTC_NoKeywords) &&
1445 R.isSingleResult()) {
1446 if (FieldDecl *Member = R.getAsSingle<FieldDecl>()) {
1447 if (Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl)) {
1448 // We have found a non-static data member with a similar
1449 // name to what was typed; complain and initialize that
1451 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1452 << MemberOrBase << true << R.getLookupName()
1453 << FixItHint::CreateReplacement(R.getNameLoc(),
1454 R.getLookupName().getAsString());
1455 Diag(Member->getLocation(), diag::note_previous_decl)
1456 << Member->getDeclName();
1458 return BuildMemberInitializer(Member, (Expr**)Args, NumArgs, IdLoc,
1459 LParenLoc, RParenLoc);
1461 } else if (TypeDecl *Type = R.getAsSingle<TypeDecl>()) {
1462 const CXXBaseSpecifier *DirectBaseSpec;
1463 const CXXBaseSpecifier *VirtualBaseSpec;
1464 if (FindBaseInitializer(*this, ClassDecl,
1465 Context.getTypeDeclType(Type),
1466 DirectBaseSpec, VirtualBaseSpec)) {
1467 // We have found a direct or virtual base class with a
1468 // similar name to what was typed; complain and initialize
1470 Diag(R.getNameLoc(), diag::err_mem_init_not_member_or_class_suggest)
1471 << MemberOrBase << false << R.getLookupName()
1472 << FixItHint::CreateReplacement(R.getNameLoc(),
1473 R.getLookupName().getAsString());
1475 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec? DirectBaseSpec
1477 Diag(BaseSpec->getSourceRange().getBegin(),
1478 diag::note_base_class_specified_here)
1479 << BaseSpec->getType()
1480 << BaseSpec->getSourceRange();
1487 if (!TyD && BaseType.isNull()) {
1488 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
1489 << MemberOrBase << SourceRange(IdLoc, RParenLoc);
1494 if (BaseType.isNull()) {
1495 BaseType = Context.getTypeDeclType(TyD);
1497 NestedNameSpecifier *Qualifier =
1498 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1500 // FIXME: preserve source range information
1501 BaseType = Context.getElaboratedType(ETK_None, Qualifier, BaseType);
1507 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
1509 return BuildBaseInitializer(BaseType, TInfo, (Expr **)Args, NumArgs,
1510 LParenLoc, RParenLoc, ClassDecl, EllipsisLoc);
1513 /// Checks an initializer expression for use of uninitialized fields, such as
1514 /// containing the field that is being initialized. Returns true if there is an
1515 /// uninitialized field was used an updates the SourceLocation parameter; false
1517 static bool InitExprContainsUninitializedFields(const Stmt *S,
1518 const ValueDecl *LhsField,
1519 SourceLocation *L) {
1520 assert(isa<FieldDecl>(LhsField) || isa<IndirectFieldDecl>(LhsField));
1522 if (isa<CallExpr>(S)) {
1523 // Do not descend into function calls or constructors, as the use
1524 // of an uninitialized field may be valid. One would have to inspect
1525 // the contents of the function/ctor to determine if it is safe or not.
1526 // i.e. Pass-by-value is never safe, but pass-by-reference and pointers
1527 // may be safe, depending on what the function/ctor does.
1530 if (const MemberExpr *ME = dyn_cast<MemberExpr>(S)) {
1531 const NamedDecl *RhsField = ME->getMemberDecl();
1533 if (const VarDecl *VD = dyn_cast<VarDecl>(RhsField)) {
1534 // The member expression points to a static data member.
1535 assert(VD->isStaticDataMember() &&
1536 "Member points to non-static data member!");
1541 if (isa<EnumConstantDecl>(RhsField)) {
1542 // The member expression points to an enum.
1546 if (RhsField == LhsField) {
1547 // Initializing a field with itself. Throw a warning.
1548 // But wait; there are exceptions!
1549 // Exception #1: The field may not belong to this record.
1550 // e.g. Foo(const Foo& rhs) : A(rhs.A) {}
1551 const Expr *base = ME->getBase();
1552 if (base != NULL && !isa<CXXThisExpr>(base->IgnoreParenCasts())) {
1553 // Even though the field matches, it does not belong to this record.
1556 // None of the exceptions triggered; return true to indicate an
1557 // uninitialized field was used.
1558 *L = ME->getMemberLoc();
1561 } else if (isa<UnaryExprOrTypeTraitExpr>(S)) {
1562 // sizeof/alignof doesn't reference contents, do not warn.
1564 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(S)) {
1565 // address-of doesn't reference contents (the pointer may be dereferenced
1566 // in the same expression but it would be rare; and weird).
1567 if (UOE->getOpcode() == UO_AddrOf)
1570 for (Stmt::const_child_range it = S->children(); it; ++it) {
1572 // An expression such as 'member(arg ?: "")' may trigger this.
1575 if (InitExprContainsUninitializedFields(*it, LhsField, L))
1582 Sema::BuildMemberInitializer(ValueDecl *Member, Expr **Args,
1583 unsigned NumArgs, SourceLocation IdLoc,
1584 SourceLocation LParenLoc,
1585 SourceLocation RParenLoc) {
1586 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
1587 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
1588 assert((DirectMember || IndirectMember) &&
1589 "Member must be a FieldDecl or IndirectFieldDecl");
1591 if (Member->isInvalidDecl())
1594 // Diagnose value-uses of fields to initialize themselves, e.g.
1596 // where foo is not also a parameter to the constructor.
1597 // TODO: implement -Wuninitialized and fold this into that framework.
1598 for (unsigned i = 0; i < NumArgs; ++i) {
1600 if (InitExprContainsUninitializedFields(Args[i], Member, &L)) {
1601 // FIXME: Return true in the case when other fields are used before being
1602 // uninitialized. For example, let this field be the i'th field. When
1603 // initializing the i'th field, throw a warning if any of the >= i'th
1604 // fields are used, as they are not yet initialized.
1605 // Right now we are only handling the case where the i'th field uses
1606 // itself in its initializer.
1607 Diag(L, diag::warn_field_is_uninit);
1611 bool HasDependentArg = false;
1612 for (unsigned i = 0; i < NumArgs; i++)
1613 HasDependentArg |= Args[i]->isTypeDependent();
1616 if (Member->getType()->isDependentType() || HasDependentArg) {
1617 // Can't check initialization for a member of dependent type or when
1618 // any of the arguments are type-dependent expressions.
1619 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1622 // Erase any temporaries within this evaluation context; we're not
1623 // going to track them in the AST, since we'll be rebuilding the
1624 // ASTs during template instantiation.
1625 ExprTemporaries.erase(
1626 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1627 ExprTemporaries.end());
1629 // Initialize the member.
1630 InitializedEntity MemberEntity =
1631 DirectMember ? InitializedEntity::InitializeMember(DirectMember, 0)
1632 : InitializedEntity::InitializeMember(IndirectMember, 0);
1633 InitializationKind Kind =
1634 InitializationKind::CreateDirect(IdLoc, LParenLoc, RParenLoc);
1636 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args, NumArgs);
1638 ExprResult MemberInit =
1639 InitSeq.Perform(*this, MemberEntity, Kind,
1640 MultiExprArg(*this, Args, NumArgs), 0);
1641 if (MemberInit.isInvalid())
1644 CheckImplicitConversions(MemberInit.get(), LParenLoc);
1646 // C++0x [class.base.init]p7:
1647 // The initialization of each base and member constitutes a
1649 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
1650 if (MemberInit.isInvalid())
1653 // If we are in a dependent context, template instantiation will
1654 // perform this type-checking again. Just save the arguments that we
1655 // received in a ParenListExpr.
1656 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1657 // of the information that we have about the member
1658 // initializer. However, deconstructing the ASTs is a dicey process,
1659 // and this approach is far more likely to get the corner cases right.
1660 if (CurContext->isDependentContext())
1661 Init = new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1664 Init = MemberInit.get();
1668 return new (Context) CXXCtorInitializer(Context, DirectMember,
1669 IdLoc, LParenLoc, Init,
1672 return new (Context) CXXCtorInitializer(Context, IndirectMember,
1673 IdLoc, LParenLoc, Init,
1679 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo,
1680 Expr **Args, unsigned NumArgs,
1681 SourceLocation NameLoc,
1682 SourceLocation LParenLoc,
1683 SourceLocation RParenLoc,
1684 CXXRecordDecl *ClassDecl) {
1685 SourceLocation Loc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
1686 if (!LangOpts.CPlusPlus0x)
1687 return Diag(Loc, diag::err_delegation_0x_only)
1688 << TInfo->getTypeLoc().getLocalSourceRange();
1690 // Initialize the object.
1691 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
1692 QualType(ClassDecl->getTypeForDecl(), 0));
1693 InitializationKind Kind =
1694 InitializationKind::CreateDirect(NameLoc, LParenLoc, RParenLoc);
1696 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args, NumArgs);
1698 ExprResult DelegationInit =
1699 InitSeq.Perform(*this, DelegationEntity, Kind,
1700 MultiExprArg(*this, Args, NumArgs), 0);
1701 if (DelegationInit.isInvalid())
1704 CXXConstructExpr *ConExpr = cast<CXXConstructExpr>(DelegationInit.get());
1705 CXXConstructorDecl *Constructor
1706 = ConExpr->getConstructor();
1707 assert(Constructor && "Delegating constructor with no target?");
1709 CheckImplicitConversions(DelegationInit.get(), LParenLoc);
1711 // C++0x [class.base.init]p7:
1712 // The initialization of each base and member constitutes a
1714 DelegationInit = MaybeCreateExprWithCleanups(DelegationInit);
1715 if (DelegationInit.isInvalid())
1718 // If we are in a dependent context, template instantiation will
1719 // perform this type-checking again. Just save the arguments that we
1720 // received in a ParenListExpr.
1721 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1722 // of the information that we have about the base
1723 // initializer. However, deconstructing the ASTs is a dicey process,
1724 // and this approach is far more likely to get the corner cases right.
1725 if (CurContext->isDependentContext()) {
1727 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args,
1728 NumArgs, RParenLoc));
1729 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc,
1730 Constructor, Init.takeAs<Expr>(),
1734 return new (Context) CXXCtorInitializer(Context, Loc, LParenLoc, Constructor,
1735 DelegationInit.takeAs<Expr>(),
1740 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
1741 Expr **Args, unsigned NumArgs,
1742 SourceLocation LParenLoc, SourceLocation RParenLoc,
1743 CXXRecordDecl *ClassDecl,
1744 SourceLocation EllipsisLoc) {
1745 bool HasDependentArg = false;
1746 for (unsigned i = 0; i < NumArgs; i++)
1747 HasDependentArg |= Args[i]->isTypeDependent();
1749 SourceLocation BaseLoc
1750 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
1752 if (!BaseType->isDependentType() && !BaseType->isRecordType())
1753 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
1754 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1756 // C++ [class.base.init]p2:
1757 // [...] Unless the mem-initializer-id names a nonstatic data
1758 // member of the constructor's class or a direct or virtual base
1759 // of that class, the mem-initializer is ill-formed. A
1760 // mem-initializer-list can initialize a base class using any
1761 // name that denotes that base class type.
1762 bool Dependent = BaseType->isDependentType() || HasDependentArg;
1764 if (EllipsisLoc.isValid()) {
1765 // This is a pack expansion.
1766 if (!BaseType->containsUnexpandedParameterPack()) {
1767 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1768 << SourceRange(BaseLoc, RParenLoc);
1770 EllipsisLoc = SourceLocation();
1773 // Check for any unexpanded parameter packs.
1774 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
1777 for (unsigned I = 0; I != NumArgs; ++I)
1778 if (DiagnoseUnexpandedParameterPack(Args[I]))
1782 // Check for direct and virtual base classes.
1783 const CXXBaseSpecifier *DirectBaseSpec = 0;
1784 const CXXBaseSpecifier *VirtualBaseSpec = 0;
1786 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
1788 return BuildDelegatingInitializer(BaseTInfo, Args, NumArgs, BaseLoc,
1789 LParenLoc, RParenLoc, ClassDecl);
1791 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
1794 // C++ [base.class.init]p2:
1795 // Unless the mem-initializer-id names a nonstatic data member of the
1796 // constructor's class or a direct or virtual base of that class, the
1797 // mem-initializer is ill-formed.
1798 if (!DirectBaseSpec && !VirtualBaseSpec) {
1799 // If the class has any dependent bases, then it's possible that
1800 // one of those types will resolve to the same type as
1801 // BaseType. Therefore, just treat this as a dependent base
1802 // class initialization. FIXME: Should we try to check the
1803 // initialization anyway? It seems odd.
1804 if (ClassDecl->hasAnyDependentBases())
1807 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
1808 << BaseType << Context.getTypeDeclType(ClassDecl)
1809 << BaseTInfo->getTypeLoc().getLocalSourceRange();
1814 // Can't check initialization for a base of dependent type or when
1815 // any of the arguments are type-dependent expressions.
1817 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1820 // Erase any temporaries within this evaluation context; we're not
1821 // going to track them in the AST, since we'll be rebuilding the
1822 // ASTs during template instantiation.
1823 ExprTemporaries.erase(
1824 ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
1825 ExprTemporaries.end());
1827 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1828 /*IsVirtual=*/false,
1830 BaseInit.takeAs<Expr>(),
1835 // C++ [base.class.init]p2:
1836 // If a mem-initializer-id is ambiguous because it designates both
1837 // a direct non-virtual base class and an inherited virtual base
1838 // class, the mem-initializer is ill-formed.
1839 if (DirectBaseSpec && VirtualBaseSpec)
1840 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
1841 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
1843 CXXBaseSpecifier *BaseSpec
1844 = const_cast<CXXBaseSpecifier *>(DirectBaseSpec);
1846 BaseSpec = const_cast<CXXBaseSpecifier *>(VirtualBaseSpec);
1848 // Initialize the base.
1849 InitializedEntity BaseEntity =
1850 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
1851 InitializationKind Kind =
1852 InitializationKind::CreateDirect(BaseLoc, LParenLoc, RParenLoc);
1854 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args, NumArgs);
1856 ExprResult BaseInit =
1857 InitSeq.Perform(*this, BaseEntity, Kind,
1858 MultiExprArg(*this, Args, NumArgs), 0);
1859 if (BaseInit.isInvalid())
1862 CheckImplicitConversions(BaseInit.get(), LParenLoc);
1864 // C++0x [class.base.init]p7:
1865 // The initialization of each base and member constitutes a
1867 BaseInit = MaybeCreateExprWithCleanups(BaseInit);
1868 if (BaseInit.isInvalid())
1871 // If we are in a dependent context, template instantiation will
1872 // perform this type-checking again. Just save the arguments that we
1873 // received in a ParenListExpr.
1874 // FIXME: This isn't quite ideal, since our ASTs don't capture all
1875 // of the information that we have about the base
1876 // initializer. However, deconstructing the ASTs is a dicey process,
1877 // and this approach is far more likely to get the corner cases right.
1878 if (CurContext->isDependentContext()) {
1880 = Owned(new (Context) ParenListExpr(Context, LParenLoc, Args, NumArgs,
1882 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1883 BaseSpec->isVirtual(),
1885 Init.takeAs<Expr>(),
1890 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
1891 BaseSpec->isVirtual(),
1893 BaseInit.takeAs<Expr>(),
1898 /// ImplicitInitializerKind - How an implicit base or member initializer should
1899 /// initialize its base or member.
1900 enum ImplicitInitializerKind {
1907 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1908 ImplicitInitializerKind ImplicitInitKind,
1909 CXXBaseSpecifier *BaseSpec,
1910 bool IsInheritedVirtualBase,
1911 CXXCtorInitializer *&CXXBaseInit) {
1912 InitializedEntity InitEntity
1913 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
1914 IsInheritedVirtualBase);
1916 ExprResult BaseInit;
1918 switch (ImplicitInitKind) {
1920 InitializationKind InitKind
1921 = InitializationKind::CreateDefault(Constructor->getLocation());
1922 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
1923 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1924 MultiExprArg(SemaRef, 0, 0));
1929 ParmVarDecl *Param = Constructor->getParamDecl(0);
1930 QualType ParamType = Param->getType().getNonReferenceType();
1933 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1934 Constructor->getLocation(), ParamType,
1937 // Cast to the base class to avoid ambiguities.
1939 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
1940 ParamType.getQualifiers());
1942 CXXCastPath BasePath;
1943 BasePath.push_back(BaseSpec);
1944 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
1945 CK_UncheckedDerivedToBase,
1946 VK_LValue, &BasePath).take();
1948 InitializationKind InitKind
1949 = InitializationKind::CreateDirect(Constructor->getLocation(),
1950 SourceLocation(), SourceLocation());
1951 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind,
1953 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind,
1954 MultiExprArg(&CopyCtorArg, 1));
1959 assert(false && "Unhandled initializer kind!");
1962 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
1963 if (BaseInit.isInvalid())
1967 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
1968 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
1970 BaseSpec->isVirtual(),
1972 BaseInit.takeAs<Expr>(),
1980 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
1981 ImplicitInitializerKind ImplicitInitKind,
1983 CXXCtorInitializer *&CXXMemberInit) {
1984 if (Field->isInvalidDecl())
1987 SourceLocation Loc = Constructor->getLocation();
1989 if (ImplicitInitKind == IIK_Copy) {
1990 ParmVarDecl *Param = Constructor->getParamDecl(0);
1991 QualType ParamType = Param->getType().getNonReferenceType();
1993 Expr *MemberExprBase =
1994 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(), Param,
1995 Loc, ParamType, VK_LValue, 0);
1997 // Build a reference to this field within the parameter.
1999 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
2000 Sema::LookupMemberName);
2001 MemberLookup.addDecl(Field, AS_public);
2002 MemberLookup.resolveKind();
2003 ExprResult CopyCtorArg
2004 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
2008 /*FirstQualifierInScope=*/0,
2010 /*TemplateArgs=*/0);
2011 if (CopyCtorArg.isInvalid())
2014 // When the field we are copying is an array, create index variables for
2015 // each dimension of the array. We use these index variables to subscript
2016 // the source array, and other clients (e.g., CodeGen) will perform the
2017 // necessary iteration with these index variables.
2018 llvm::SmallVector<VarDecl *, 4> IndexVariables;
2019 QualType BaseType = Field->getType();
2020 QualType SizeType = SemaRef.Context.getSizeType();
2021 while (const ConstantArrayType *Array
2022 = SemaRef.Context.getAsConstantArrayType(BaseType)) {
2023 // Create the iteration variable for this array index.
2024 IdentifierInfo *IterationVarName = 0;
2026 llvm::SmallString<8> Str;
2027 llvm::raw_svector_ostream OS(Str);
2028 OS << "__i" << IndexVariables.size();
2029 IterationVarName = &SemaRef.Context.Idents.get(OS.str());
2031 VarDecl *IterationVar
2032 = VarDecl::Create(SemaRef.Context, SemaRef.CurContext, Loc, Loc,
2033 IterationVarName, SizeType,
2034 SemaRef.Context.getTrivialTypeSourceInfo(SizeType, Loc),
2036 IndexVariables.push_back(IterationVar);
2038 // Create a reference to the iteration variable.
2039 ExprResult IterationVarRef
2040 = SemaRef.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc);
2041 assert(!IterationVarRef.isInvalid() &&
2042 "Reference to invented variable cannot fail!");
2044 // Subscript the array with this iteration variable.
2045 CopyCtorArg = SemaRef.CreateBuiltinArraySubscriptExpr(CopyCtorArg.take(),
2047 IterationVarRef.take(),
2049 if (CopyCtorArg.isInvalid())
2052 BaseType = Array->getElementType();
2055 // Construct the entity that we will be initializing. For an array, this
2056 // will be first element in the array, which may require several levels
2057 // of array-subscript entities.
2058 llvm::SmallVector<InitializedEntity, 4> Entities;
2059 Entities.reserve(1 + IndexVariables.size());
2060 Entities.push_back(InitializedEntity::InitializeMember(Field));
2061 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
2062 Entities.push_back(InitializedEntity::InitializeElement(SemaRef.Context,
2066 // Direct-initialize to use the copy constructor.
2067 InitializationKind InitKind =
2068 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
2070 Expr *CopyCtorArgE = CopyCtorArg.takeAs<Expr>();
2071 InitializationSequence InitSeq(SemaRef, Entities.back(), InitKind,
2074 ExprResult MemberInit
2075 = InitSeq.Perform(SemaRef, Entities.back(), InitKind,
2076 MultiExprArg(&CopyCtorArgE, 1));
2077 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2078 if (MemberInit.isInvalid())
2082 = CXXCtorInitializer::Create(SemaRef.Context, Field, Loc, Loc,
2083 MemberInit.takeAs<Expr>(), Loc,
2084 IndexVariables.data(),
2085 IndexVariables.size());
2089 assert(ImplicitInitKind == IIK_Default && "Unhandled implicit init kind!");
2091 QualType FieldBaseElementType =
2092 SemaRef.Context.getBaseElementType(Field->getType());
2094 if (FieldBaseElementType->isRecordType()) {
2095 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
2096 InitializationKind InitKind =
2097 InitializationKind::CreateDefault(Loc);
2099 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, 0, 0);
2100 ExprResult MemberInit =
2101 InitSeq.Perform(SemaRef, InitEntity, InitKind, MultiExprArg());
2103 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
2104 if (MemberInit.isInvalid())
2108 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
2115 if (!Field->getParent()->isUnion()) {
2116 if (FieldBaseElementType->isReferenceType()) {
2117 SemaRef.Diag(Constructor->getLocation(),
2118 diag::err_uninitialized_member_in_ctor)
2119 << (int)Constructor->isImplicit()
2120 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2121 << 0 << Field->getDeclName();
2122 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2126 if (FieldBaseElementType.isConstQualified()) {
2127 SemaRef.Diag(Constructor->getLocation(),
2128 diag::err_uninitialized_member_in_ctor)
2129 << (int)Constructor->isImplicit()
2130 << SemaRef.Context.getTagDeclType(Constructor->getParent())
2131 << 1 << Field->getDeclName();
2132 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
2137 // Nothing to initialize.
2143 struct BaseAndFieldInfo {
2145 CXXConstructorDecl *Ctor;
2146 bool AnyErrorsInInits;
2147 ImplicitInitializerKind IIK;
2148 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
2149 llvm::SmallVector<CXXCtorInitializer*, 8> AllToInit;
2151 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
2152 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
2153 // FIXME: Handle implicit move constructors.
2154 if (Ctor->isImplicit() && Ctor->isCopyConstructor())
2162 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
2163 FieldDecl *Top, FieldDecl *Field) {
2165 // Overwhelmingly common case: we have a direct initializer for this field.
2166 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(Field)) {
2167 Info.AllToInit.push_back(Init);
2171 // C++0x [class.base.init]p8: if the entity is a non-static data member that
2172 // has a brace-or-equal-initializer, the entity is initialized as specified
2174 if (Field->hasInClassInitializer()) {
2175 Info.AllToInit.push_back(
2176 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
2178 SourceLocation(), 0,
2183 if (Info.IIK == IIK_Default && Field->isAnonymousStructOrUnion()) {
2184 const RecordType *FieldClassType = Field->getType()->getAs<RecordType>();
2185 assert(FieldClassType && "anonymous struct/union without record type");
2186 CXXRecordDecl *FieldClassDecl
2187 = cast<CXXRecordDecl>(FieldClassType->getDecl());
2189 // Even though union members never have non-trivial default
2190 // constructions in C++03, we still build member initializers for aggregate
2191 // record types which can be union members, and C++0x allows non-trivial
2192 // default constructors for union members, so we ensure that only one
2193 // member is initialized for these.
2194 if (FieldClassDecl->isUnion()) {
2195 // First check for an explicit initializer for one field.
2196 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2197 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2198 if (CXXCtorInitializer *Init = Info.AllBaseFields.lookup(*FA)) {
2199 Info.AllToInit.push_back(Init);
2201 // Once we've initialized a field of an anonymous union, the union
2202 // field in the class is also initialized, so exit immediately.
2204 } else if ((*FA)->isAnonymousStructOrUnion()) {
2205 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
2210 // Fallthrough and construct a default initializer for the union as
2211 // a whole, which can call its default constructor if such a thing exists
2212 // (C++0x perhaps). FIXME: It's not clear that this is the correct
2213 // behavior going forward with C++0x, when anonymous unions there are
2214 // finalized, we should revisit this.
2216 // For structs, we simply descend through to initialize all members where
2218 for (RecordDecl::field_iterator FA = FieldClassDecl->field_begin(),
2219 EA = FieldClassDecl->field_end(); FA != EA; FA++) {
2220 if (CollectFieldInitializer(SemaRef, Info, Top, *FA))
2226 // Don't try to build an implicit initializer if there were semantic
2227 // errors in any of the initializers (and therefore we might be
2228 // missing some that the user actually wrote).
2229 if (Info.AnyErrorsInInits || Field->isInvalidDecl())
2232 CXXCtorInitializer *Init = 0;
2233 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field, Init))
2237 Info.AllToInit.push_back(Init);
2243 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
2244 CXXCtorInitializer *Initializer) {
2245 assert(Initializer->isDelegatingInitializer());
2246 Constructor->setNumCtorInitializers(1);
2247 CXXCtorInitializer **initializer =
2248 new (Context) CXXCtorInitializer*[1];
2249 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
2250 Constructor->setCtorInitializers(initializer);
2252 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
2253 MarkDeclarationReferenced(Initializer->getSourceLocation(), Dtor);
2254 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
2257 DelegatingCtorDecls.push_back(Constructor);
2263 Sema::SetCtorInitializers(CXXConstructorDecl *Constructor,
2264 CXXCtorInitializer **Initializers,
2265 unsigned NumInitializers,
2267 if (Constructor->getDeclContext()->isDependentContext()) {
2268 // Just store the initializers as written, they will be checked during
2270 if (NumInitializers > 0) {
2271 Constructor->setNumCtorInitializers(NumInitializers);
2272 CXXCtorInitializer **baseOrMemberInitializers =
2273 new (Context) CXXCtorInitializer*[NumInitializers];
2274 memcpy(baseOrMemberInitializers, Initializers,
2275 NumInitializers * sizeof(CXXCtorInitializer*));
2276 Constructor->setCtorInitializers(baseOrMemberInitializers);
2282 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
2284 // We need to build the initializer AST according to order of construction
2285 // and not what user specified in the Initializers list.
2286 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
2290 bool HadError = false;
2292 for (unsigned i = 0; i < NumInitializers; i++) {
2293 CXXCtorInitializer *Member = Initializers[i];
2295 if (Member->isBaseInitializer())
2296 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
2298 Info.AllBaseFields[Member->getAnyMember()] = Member;
2301 // Keep track of the direct virtual bases.
2302 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
2303 for (CXXRecordDecl::base_class_iterator I = ClassDecl->bases_begin(),
2304 E = ClassDecl->bases_end(); I != E; ++I) {
2306 DirectVBases.insert(I);
2309 // Push virtual bases before others.
2310 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2311 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2313 if (CXXCtorInitializer *Value
2314 = Info.AllBaseFields.lookup(VBase->getType()->getAs<RecordType>())) {
2315 Info.AllToInit.push_back(Value);
2316 } else if (!AnyErrors) {
2317 bool IsInheritedVirtualBase = !DirectVBases.count(VBase);
2318 CXXCtorInitializer *CXXBaseInit;
2319 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2320 VBase, IsInheritedVirtualBase,
2326 Info.AllToInit.push_back(CXXBaseInit);
2330 // Non-virtual bases.
2331 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2332 E = ClassDecl->bases_end(); Base != E; ++Base) {
2333 // Virtuals are in the virtual base list and already constructed.
2334 if (Base->isVirtual())
2337 if (CXXCtorInitializer *Value
2338 = Info.AllBaseFields.lookup(Base->getType()->getAs<RecordType>())) {
2339 Info.AllToInit.push_back(Value);
2340 } else if (!AnyErrors) {
2341 CXXCtorInitializer *CXXBaseInit;
2342 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
2343 Base, /*IsInheritedVirtualBase=*/false,
2349 Info.AllToInit.push_back(CXXBaseInit);
2354 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2355 E = ClassDecl->field_end(); Field != E; ++Field) {
2356 if ((*Field)->getType()->isIncompleteArrayType()) {
2357 assert(ClassDecl->hasFlexibleArrayMember() &&
2358 "Incomplete array type is not valid");
2361 if (CollectFieldInitializer(*this, Info, *Field, *Field))
2365 NumInitializers = Info.AllToInit.size();
2366 if (NumInitializers > 0) {
2367 Constructor->setNumCtorInitializers(NumInitializers);
2368 CXXCtorInitializer **baseOrMemberInitializers =
2369 new (Context) CXXCtorInitializer*[NumInitializers];
2370 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
2371 NumInitializers * sizeof(CXXCtorInitializer*));
2372 Constructor->setCtorInitializers(baseOrMemberInitializers);
2374 // Constructors implicitly reference the base and member
2376 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
2377 Constructor->getParent());
2383 static void *GetKeyForTopLevelField(FieldDecl *Field) {
2384 // For anonymous unions, use the class declaration as the key.
2385 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
2386 if (RT->getDecl()->isAnonymousStructOrUnion())
2387 return static_cast<void *>(RT->getDecl());
2389 return static_cast<void *>(Field);
2392 static void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
2393 return const_cast<Type*>(Context.getCanonicalType(BaseType).getTypePtr());
2396 static void *GetKeyForMember(ASTContext &Context,
2397 CXXCtorInitializer *Member) {
2398 if (!Member->isAnyMemberInitializer())
2399 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
2401 // For fields injected into the class via declaration of an anonymous union,
2402 // use its anonymous union class declaration as the unique key.
2403 FieldDecl *Field = Member->getAnyMember();
2405 // If the field is a member of an anonymous struct or union, our key
2406 // is the anonymous record decl that's a direct child of the class.
2407 RecordDecl *RD = Field->getParent();
2408 if (RD->isAnonymousStructOrUnion()) {
2410 RecordDecl *Parent = cast<RecordDecl>(RD->getDeclContext());
2411 if (Parent->isAnonymousStructOrUnion())
2417 return static_cast<void *>(RD);
2420 return static_cast<void *>(Field);
2424 DiagnoseBaseOrMemInitializerOrder(Sema &SemaRef,
2425 const CXXConstructorDecl *Constructor,
2426 CXXCtorInitializer **Inits,
2427 unsigned NumInits) {
2428 if (Constructor->getDeclContext()->isDependentContext())
2431 // Don't check initializers order unless the warning is enabled at the
2432 // location of at least one initializer.
2433 bool ShouldCheckOrder = false;
2434 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2435 CXXCtorInitializer *Init = Inits[InitIndex];
2436 if (SemaRef.Diags.getDiagnosticLevel(diag::warn_initializer_out_of_order,
2437 Init->getSourceLocation())
2438 != Diagnostic::Ignored) {
2439 ShouldCheckOrder = true;
2443 if (!ShouldCheckOrder)
2446 // Build the list of bases and members in the order that they'll
2447 // actually be initialized. The explicit initializers should be in
2448 // this same order but may be missing things.
2449 llvm::SmallVector<const void*, 32> IdealInitKeys;
2451 const CXXRecordDecl *ClassDecl = Constructor->getParent();
2453 // 1. Virtual bases.
2454 for (CXXRecordDecl::base_class_const_iterator VBase =
2455 ClassDecl->vbases_begin(),
2456 E = ClassDecl->vbases_end(); VBase != E; ++VBase)
2457 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase->getType()));
2459 // 2. Non-virtual bases.
2460 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(),
2461 E = ClassDecl->bases_end(); Base != E; ++Base) {
2462 if (Base->isVirtual())
2464 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base->getType()));
2467 // 3. Direct fields.
2468 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
2469 E = ClassDecl->field_end(); Field != E; ++Field)
2470 IdealInitKeys.push_back(GetKeyForTopLevelField(*Field));
2472 unsigned NumIdealInits = IdealInitKeys.size();
2473 unsigned IdealIndex = 0;
2475 CXXCtorInitializer *PrevInit = 0;
2476 for (unsigned InitIndex = 0; InitIndex != NumInits; ++InitIndex) {
2477 CXXCtorInitializer *Init = Inits[InitIndex];
2478 void *InitKey = GetKeyForMember(SemaRef.Context, Init);
2480 // Scan forward to try to find this initializer in the idealized
2481 // initializers list.
2482 for (; IdealIndex != NumIdealInits; ++IdealIndex)
2483 if (InitKey == IdealInitKeys[IdealIndex])
2486 // If we didn't find this initializer, it must be because we
2487 // scanned past it on a previous iteration. That can only
2488 // happen if we're out of order; emit a warning.
2489 if (IdealIndex == NumIdealInits && PrevInit) {
2490 Sema::SemaDiagnosticBuilder D =
2491 SemaRef.Diag(PrevInit->getSourceLocation(),
2492 diag::warn_initializer_out_of_order);
2494 if (PrevInit->isAnyMemberInitializer())
2495 D << 0 << PrevInit->getAnyMember()->getDeclName();
2497 D << 1 << PrevInit->getBaseClassInfo()->getType();
2499 if (Init->isAnyMemberInitializer())
2500 D << 0 << Init->getAnyMember()->getDeclName();
2502 D << 1 << Init->getBaseClassInfo()->getType();
2504 // Move back to the initializer's location in the ideal list.
2505 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
2506 if (InitKey == IdealInitKeys[IdealIndex])
2509 assert(IdealIndex != NumIdealInits &&
2510 "initializer not found in initializer list");
2518 bool CheckRedundantInit(Sema &S,
2519 CXXCtorInitializer *Init,
2520 CXXCtorInitializer *&PrevInit) {
2526 if (FieldDecl *Field = Init->getMember())
2527 S.Diag(Init->getSourceLocation(),
2528 diag::err_multiple_mem_initialization)
2529 << Field->getDeclName()
2530 << Init->getSourceRange();
2532 const Type *BaseClass = Init->getBaseClass();
2533 assert(BaseClass && "neither field nor base");
2534 S.Diag(Init->getSourceLocation(),
2535 diag::err_multiple_base_initialization)
2536 << QualType(BaseClass, 0)
2537 << Init->getSourceRange();
2539 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
2540 << 0 << PrevInit->getSourceRange();
2545 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
2546 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
2548 bool CheckRedundantUnionInit(Sema &S,
2549 CXXCtorInitializer *Init,
2550 RedundantUnionMap &Unions) {
2551 FieldDecl *Field = Init->getAnyMember();
2552 RecordDecl *Parent = Field->getParent();
2553 if (!Parent->isAnonymousStructOrUnion())
2556 NamedDecl *Child = Field;
2558 if (Parent->isUnion()) {
2559 UnionEntry &En = Unions[Parent];
2560 if (En.first && En.first != Child) {
2561 S.Diag(Init->getSourceLocation(),
2562 diag::err_multiple_mem_union_initialization)
2563 << Field->getDeclName()
2564 << Init->getSourceRange();
2565 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
2566 << 0 << En.second->getSourceRange();
2568 } else if (!En.first) {
2575 Parent = cast<RecordDecl>(Parent->getDeclContext());
2576 } while (Parent->isAnonymousStructOrUnion());
2582 /// ActOnMemInitializers - Handle the member initializers for a constructor.
2583 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
2584 SourceLocation ColonLoc,
2585 MemInitTy **meminits, unsigned NumMemInits,
2587 if (!ConstructorDecl)
2590 AdjustDeclIfTemplate(ConstructorDecl);
2592 CXXConstructorDecl *Constructor
2593 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
2596 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
2600 CXXCtorInitializer **MemInits =
2601 reinterpret_cast<CXXCtorInitializer **>(meminits);
2603 // Mapping for the duplicate initializers check.
2604 // For member initializers, this is keyed with a FieldDecl*.
2605 // For base initializers, this is keyed with a Type*.
2606 llvm::DenseMap<void*, CXXCtorInitializer *> Members;
2608 // Mapping for the inconsistent anonymous-union initializers check.
2609 RedundantUnionMap MemberUnions;
2611 bool HadError = false;
2612 for (unsigned i = 0; i < NumMemInits; i++) {
2613 CXXCtorInitializer *Init = MemInits[i];
2615 // Set the source order index.
2616 Init->setSourceOrder(i);
2618 if (Init->isAnyMemberInitializer()) {
2619 FieldDecl *Field = Init->getAnyMember();
2620 if (CheckRedundantInit(*this, Init, Members[Field]) ||
2621 CheckRedundantUnionInit(*this, Init, MemberUnions))
2623 } else if (Init->isBaseInitializer()) {
2624 void *Key = GetKeyForBase(Context, QualType(Init->getBaseClass(), 0));
2625 if (CheckRedundantInit(*this, Init, Members[Key]))
2628 assert(Init->isDelegatingInitializer());
2629 // This must be the only initializer
2630 if (i != 0 || NumMemInits > 1) {
2631 Diag(MemInits[0]->getSourceLocation(),
2632 diag::err_delegating_initializer_alone)
2633 << MemInits[0]->getSourceRange();
2635 // We will treat this as being the only initializer.
2637 SetDelegatingInitializer(Constructor, MemInits[i]);
2638 // Return immediately as the initializer is set.
2646 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits, NumMemInits);
2648 SetCtorInitializers(Constructor, MemInits, NumMemInits, AnyErrors);
2652 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
2653 CXXRecordDecl *ClassDecl) {
2654 // Ignore dependent contexts.
2655 if (ClassDecl->isDependentContext())
2658 // FIXME: all the access-control diagnostics are positioned on the
2659 // field/base declaration. That's probably good; that said, the
2660 // user might reasonably want to know why the destructor is being
2661 // emitted, and we currently don't say.
2663 // Non-static data members.
2664 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
2665 E = ClassDecl->field_end(); I != E; ++I) {
2666 FieldDecl *Field = *I;
2667 if (Field->isInvalidDecl())
2669 QualType FieldType = Context.getBaseElementType(Field->getType());
2671 const RecordType* RT = FieldType->getAs<RecordType>();
2675 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2676 if (FieldClassDecl->isInvalidDecl())
2678 if (FieldClassDecl->hasTrivialDestructor())
2681 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
2682 assert(Dtor && "No dtor found for FieldClassDecl!");
2683 CheckDestructorAccess(Field->getLocation(), Dtor,
2684 PDiag(diag::err_access_dtor_field)
2685 << Field->getDeclName()
2688 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2691 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
2694 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
2695 E = ClassDecl->bases_end(); Base != E; ++Base) {
2696 // Bases are always records in a well-formed non-dependent class.
2697 const RecordType *RT = Base->getType()->getAs<RecordType>();
2699 // Remember direct virtual bases.
2700 if (Base->isVirtual())
2701 DirectVirtualBases.insert(RT);
2703 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2704 // If our base class is invalid, we probably can't get its dtor anyway.
2705 if (BaseClassDecl->isInvalidDecl())
2707 // Ignore trivial destructors.
2708 if (BaseClassDecl->hasTrivialDestructor())
2711 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2712 assert(Dtor && "No dtor found for BaseClassDecl!");
2714 // FIXME: caret should be on the start of the class name
2715 CheckDestructorAccess(Base->getSourceRange().getBegin(), Dtor,
2716 PDiag(diag::err_access_dtor_base)
2718 << Base->getSourceRange());
2720 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2724 for (CXXRecordDecl::base_class_iterator VBase = ClassDecl->vbases_begin(),
2725 E = ClassDecl->vbases_end(); VBase != E; ++VBase) {
2727 // Bases are always records in a well-formed non-dependent class.
2728 const RecordType *RT = VBase->getType()->getAs<RecordType>();
2730 // Ignore direct virtual bases.
2731 if (DirectVirtualBases.count(RT))
2734 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
2735 // If our base class is invalid, we probably can't get its dtor anyway.
2736 if (BaseClassDecl->isInvalidDecl())
2738 // Ignore trivial destructors.
2739 if (BaseClassDecl->hasTrivialDestructor())
2742 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
2743 assert(Dtor && "No dtor found for BaseClassDecl!");
2744 CheckDestructorAccess(ClassDecl->getLocation(), Dtor,
2745 PDiag(diag::err_access_dtor_vbase)
2746 << VBase->getType());
2748 MarkDeclarationReferenced(Location, const_cast<CXXDestructorDecl*>(Dtor));
2752 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
2756 if (CXXConstructorDecl *Constructor
2757 = dyn_cast<CXXConstructorDecl>(CDtorDecl))
2758 SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false);
2761 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2762 unsigned DiagID, AbstractDiagSelID SelID) {
2764 return RequireNonAbstractType(Loc, T, PDiag(DiagID));
2766 return RequireNonAbstractType(Loc, T, PDiag(DiagID) << SelID);
2769 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
2770 const PartialDiagnostic &PD) {
2771 if (!getLangOptions().CPlusPlus)
2774 if (const ArrayType *AT = Context.getAsArrayType(T))
2775 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2777 if (const PointerType *PT = T->getAs<PointerType>()) {
2778 // Find the innermost pointer type.
2779 while (const PointerType *T = PT->getPointeeType()->getAs<PointerType>())
2782 if (const ArrayType *AT = Context.getAsArrayType(PT->getPointeeType()))
2783 return RequireNonAbstractType(Loc, AT->getElementType(), PD);
2786 const RecordType *RT = T->getAs<RecordType>();
2790 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
2792 // We can't answer whether something is abstract until it has a
2793 // definition. If it's currently being defined, we'll walk back
2794 // over all the declarations when we have a full definition.
2795 const CXXRecordDecl *Def = RD->getDefinition();
2796 if (!Def || Def->isBeingDefined())
2799 if (!RD->isAbstract())
2802 Diag(Loc, PD) << RD->getDeclName();
2803 DiagnoseAbstractType(RD);
2808 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
2809 // Check if we've already emitted the list of pure virtual functions
2811 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
2814 CXXFinalOverriderMap FinalOverriders;
2815 RD->getFinalOverriders(FinalOverriders);
2817 // Keep a set of seen pure methods so we won't diagnose the same method
2819 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
2821 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
2822 MEnd = FinalOverriders.end();
2825 for (OverridingMethods::iterator SO = M->second.begin(),
2826 SOEnd = M->second.end();
2827 SO != SOEnd; ++SO) {
2828 // C++ [class.abstract]p4:
2829 // A class is abstract if it contains or inherits at least one
2830 // pure virtual function for which the final overrider is pure
2834 if (SO->second.size() != 1)
2837 if (!SO->second.front().Method->isPure())
2840 if (!SeenPureMethods.insert(SO->second.front().Method))
2843 Diag(SO->second.front().Method->getLocation(),
2844 diag::note_pure_virtual_function)
2845 << SO->second.front().Method->getDeclName() << RD->getDeclName();
2849 if (!PureVirtualClassDiagSet)
2850 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
2851 PureVirtualClassDiagSet->insert(RD);
2855 struct AbstractUsageInfo {
2857 CXXRecordDecl *Record;
2858 CanQualType AbstractType;
2861 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
2862 : S(S), Record(Record),
2863 AbstractType(S.Context.getCanonicalType(
2864 S.Context.getTypeDeclType(Record))),
2867 void DiagnoseAbstractType() {
2868 if (Invalid) return;
2869 S.DiagnoseAbstractType(Record);
2873 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
2876 struct CheckAbstractUsage {
2877 AbstractUsageInfo &Info;
2878 const NamedDecl *Ctx;
2880 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
2881 : Info(Info), Ctx(Ctx) {}
2883 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2884 switch (TL.getTypeLocClass()) {
2885 #define ABSTRACT_TYPELOC(CLASS, PARENT)
2886 #define TYPELOC(CLASS, PARENT) \
2887 case TypeLoc::CLASS: Check(cast<CLASS##TypeLoc>(TL), Sel); break;
2888 #include "clang/AST/TypeLocNodes.def"
2892 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2893 Visit(TL.getResultLoc(), Sema::AbstractReturnType);
2894 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2898 TypeSourceInfo *TSI = TL.getArg(I)->getTypeSourceInfo();
2899 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
2903 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2904 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
2907 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
2908 // Visit the type parameters from a permissive context.
2909 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
2910 TemplateArgumentLoc TAL = TL.getArgLoc(I);
2911 if (TAL.getArgument().getKind() == TemplateArgument::Type)
2912 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
2913 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
2914 // TODO: other template argument types?
2918 // Visit pointee types from a permissive context.
2919 #define CheckPolymorphic(Type) \
2920 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
2921 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
2923 CheckPolymorphic(PointerTypeLoc)
2924 CheckPolymorphic(ReferenceTypeLoc)
2925 CheckPolymorphic(MemberPointerTypeLoc)
2926 CheckPolymorphic(BlockPointerTypeLoc)
2928 /// Handle all the types we haven't given a more specific
2929 /// implementation for above.
2930 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
2931 // Every other kind of type that we haven't called out already
2932 // that has an inner type is either (1) sugar or (2) contains that
2933 // inner type in some way as a subobject.
2934 if (TypeLoc Next = TL.getNextTypeLoc())
2935 return Visit(Next, Sel);
2937 // If there's no inner type and we're in a permissive context,
2939 if (Sel == Sema::AbstractNone) return;
2941 // Check whether the type matches the abstract type.
2942 QualType T = TL.getType();
2943 if (T->isArrayType()) {
2944 Sel = Sema::AbstractArrayType;
2945 T = Info.S.Context.getBaseElementType(T);
2947 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
2948 if (CT != Info.AbstractType) return;
2950 // It matched; do some magic.
2951 if (Sel == Sema::AbstractArrayType) {
2952 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
2953 << T << TL.getSourceRange();
2955 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
2956 << Sel << T << TL.getSourceRange();
2958 Info.DiagnoseAbstractType();
2962 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
2963 Sema::AbstractDiagSelID Sel) {
2964 CheckAbstractUsage(*this, D).Visit(TL, Sel);
2969 /// Check for invalid uses of an abstract type in a method declaration.
2970 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2971 CXXMethodDecl *MD) {
2972 // No need to do the check on definitions, which require that
2973 // the return/param types be complete.
2974 if (MD->doesThisDeclarationHaveABody())
2977 // For safety's sake, just ignore it if we don't have type source
2978 // information. This should never happen for non-implicit methods,
2980 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
2981 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
2984 /// Check for invalid uses of an abstract type within a class definition.
2985 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
2986 CXXRecordDecl *RD) {
2987 for (CXXRecordDecl::decl_iterator
2988 I = RD->decls_begin(), E = RD->decls_end(); I != E; ++I) {
2990 if (D->isImplicit()) continue;
2992 // Methods and method templates.
2993 if (isa<CXXMethodDecl>(D)) {
2994 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
2995 } else if (isa<FunctionTemplateDecl>(D)) {
2996 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
2997 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
2999 // Fields and static variables.
3000 } else if (isa<FieldDecl>(D)) {
3001 FieldDecl *FD = cast<FieldDecl>(D);
3002 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
3003 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
3004 } else if (isa<VarDecl>(D)) {
3005 VarDecl *VD = cast<VarDecl>(D);
3006 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
3007 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
3009 // Nested classes and class templates.
3010 } else if (isa<CXXRecordDecl>(D)) {
3011 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
3012 } else if (isa<ClassTemplateDecl>(D)) {
3013 CheckAbstractClassUsage(Info,
3014 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
3019 /// \brief Perform semantic checks on a class definition that has been
3020 /// completing, introducing implicitly-declared members, checking for
3021 /// abstract types, etc.
3022 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
3026 if (Record->isAbstract() && !Record->isInvalidDecl()) {
3027 AbstractUsageInfo Info(*this, Record);
3028 CheckAbstractClassUsage(Info, Record);
3031 // If this is not an aggregate type and has no user-declared constructor,
3032 // complain about any non-static data members of reference or const scalar
3033 // type, since they will never get initializers.
3034 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
3035 !Record->isAggregate() && !Record->hasUserDeclaredConstructor()) {
3036 bool Complained = false;
3037 for (RecordDecl::field_iterator F = Record->field_begin(),
3038 FEnd = Record->field_end();
3040 if (F->hasInClassInitializer())
3043 if (F->getType()->isReferenceType() ||
3044 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
3046 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
3047 << Record->getTagKind() << Record;
3051 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
3052 << F->getType()->isReferenceType()
3053 << F->getDeclName();
3058 if (Record->isDynamicClass() && !Record->isDependentType())
3059 DynamicClasses.push_back(Record);
3061 if (Record->getIdentifier()) {
3062 // C++ [class.mem]p13:
3063 // If T is the name of a class, then each of the following shall have a
3064 // name different from T:
3065 // - every member of every anonymous union that is a member of class T.
3067 // C++ [class.mem]p14:
3068 // In addition, if class T has a user-declared constructor (12.1), every
3069 // non-static data member of class T shall have a name different from T.
3070 for (DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
3071 R.first != R.second; ++R.first) {
3072 NamedDecl *D = *R.first;
3073 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
3074 isa<IndirectFieldDecl>(D)) {
3075 Diag(D->getLocation(), diag::err_member_name_of_class)
3076 << D->getDeclName();
3082 // Warn if the class has virtual methods but non-virtual public destructor.
3083 if (Record->isPolymorphic() && !Record->isDependentType()) {
3084 CXXDestructorDecl *dtor = Record->getDestructor();
3085 if (!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public))
3086 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
3087 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
3090 // See if a method overloads virtual methods in a base
3091 /// class without overriding any.
3092 if (!Record->isDependentType()) {
3093 for (CXXRecordDecl::method_iterator M = Record->method_begin(),
3094 MEnd = Record->method_end();
3096 if (!(*M)->isStatic())
3097 DiagnoseHiddenVirtualMethods(Record, *M);
3101 // Declare inherited constructors. We do this eagerly here because:
3102 // - The standard requires an eager diagnostic for conflicting inherited
3103 // constructors from different classes.
3104 // - The lazy declaration of the other implicit constructors is so as to not
3105 // waste space and performance on classes that are not meant to be
3106 // instantiated (e.g. meta-functions). This doesn't apply to classes that
3107 // have inherited constructors.
3108 DeclareInheritedConstructors(Record);
3110 if (!Record->isDependentType())
3111 CheckExplicitlyDefaultedMethods(Record);
3114 void Sema::CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record) {
3115 for (CXXRecordDecl::method_iterator MI = Record->method_begin(),
3116 ME = Record->method_end();
3118 if (!MI->isInvalidDecl() && MI->isExplicitlyDefaulted()) {
3119 switch (getSpecialMember(*MI)) {
3120 case CXXDefaultConstructor:
3121 CheckExplicitlyDefaultedDefaultConstructor(
3122 cast<CXXConstructorDecl>(*MI));
3126 CheckExplicitlyDefaultedDestructor(cast<CXXDestructorDecl>(*MI));
3129 case CXXCopyConstructor:
3130 CheckExplicitlyDefaultedCopyConstructor(cast<CXXConstructorDecl>(*MI));
3133 case CXXCopyAssignment:
3134 CheckExplicitlyDefaultedCopyAssignment(*MI);
3137 case CXXMoveConstructor:
3138 case CXXMoveAssignment:
3139 Diag(MI->getLocation(), diag::err_defaulted_move_unsupported);
3143 // FIXME: Do moves once they exist
3144 llvm_unreachable("non-special member explicitly defaulted!");
3151 void Sema::CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *CD) {
3152 assert(CD->isExplicitlyDefaulted() && CD->isDefaultConstructor());
3154 // Whether this was the first-declared instance of the constructor.
3155 // This affects whether we implicitly add an exception spec (and, eventually,
3156 // constexpr). It is also ill-formed to explicitly default a constructor such
3157 // that it would be deleted. (C++0x [decl.fct.def.default])
3158 bool First = CD == CD->getCanonicalDecl();
3160 bool HadError = false;
3161 if (CD->getNumParams() != 0) {
3162 Diag(CD->getLocation(), diag::err_defaulted_default_ctor_params)
3163 << CD->getSourceRange();
3167 ImplicitExceptionSpecification Spec
3168 = ComputeDefaultedDefaultCtorExceptionSpec(CD->getParent());
3169 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3170 if (EPI.ExceptionSpecType == EST_Delayed) {
3171 // Exception specification depends on some deferred part of the class. We'll
3172 // try again when the class's definition has been fully processed.
3175 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3176 *ExceptionType = Context.getFunctionType(
3177 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3179 if (CtorType->hasExceptionSpec()) {
3180 if (CheckEquivalentExceptionSpec(
3181 PDiag(diag::err_incorrect_defaulted_exception_spec)
3182 << CXXDefaultConstructor,
3184 ExceptionType, SourceLocation(),
3185 CtorType, CD->getLocation())) {
3189 // We set the declaration to have the computed exception spec here.
3190 // We know there are no parameters.
3191 EPI.ExtInfo = CtorType->getExtInfo();
3192 CD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3196 CD->setInvalidDecl();
3200 if (ShouldDeleteDefaultConstructor(CD)) {
3202 CD->setDeletedAsWritten();
3204 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3205 << CXXDefaultConstructor;
3206 CD->setInvalidDecl();
3211 void Sema::CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *CD) {
3212 assert(CD->isExplicitlyDefaulted() && CD->isCopyConstructor());
3214 // Whether this was the first-declared instance of the constructor.
3215 bool First = CD == CD->getCanonicalDecl();
3217 bool HadError = false;
3218 if (CD->getNumParams() != 1) {
3219 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_params)
3220 << CD->getSourceRange();
3224 ImplicitExceptionSpecification Spec(Context);
3226 llvm::tie(Spec, Const) =
3227 ComputeDefaultedCopyCtorExceptionSpecAndConst(CD->getParent());
3229 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3230 const FunctionProtoType *CtorType = CD->getType()->getAs<FunctionProtoType>(),
3231 *ExceptionType = Context.getFunctionType(
3232 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3234 // Check for parameter type matching.
3235 // This is a copy ctor so we know it's a cv-qualified reference to T.
3236 QualType ArgType = CtorType->getArgType(0);
3237 if (ArgType->getPointeeType().isVolatileQualified()) {
3238 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_volatile_param);
3241 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3242 Diag(CD->getLocation(), diag::err_defaulted_copy_ctor_const_param);
3246 if (CtorType->hasExceptionSpec()) {
3247 if (CheckEquivalentExceptionSpec(
3248 PDiag(diag::err_incorrect_defaulted_exception_spec)
3249 << CXXCopyConstructor,
3251 ExceptionType, SourceLocation(),
3252 CtorType, CD->getLocation())) {
3256 // We set the declaration to have the computed exception spec here.
3257 // We duplicate the one parameter type.
3258 EPI.ExtInfo = CtorType->getExtInfo();
3259 CD->setType(Context.getFunctionType(Context.VoidTy, &ArgType, 1, EPI));
3263 CD->setInvalidDecl();
3267 if (ShouldDeleteCopyConstructor(CD)) {
3269 CD->setDeletedAsWritten();
3271 Diag(CD->getLocation(), diag::err_out_of_line_default_deletes)
3272 << CXXCopyConstructor;
3273 CD->setInvalidDecl();
3278 void Sema::CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *MD) {
3279 assert(MD->isExplicitlyDefaulted());
3281 // Whether this was the first-declared instance of the operator
3282 bool First = MD == MD->getCanonicalDecl();
3284 bool HadError = false;
3285 if (MD->getNumParams() != 1) {
3286 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_params)
3287 << MD->getSourceRange();
3291 QualType ReturnType =
3292 MD->getType()->getAs<FunctionType>()->getResultType();
3293 if (!ReturnType->isLValueReferenceType() ||
3294 !Context.hasSameType(
3295 Context.getCanonicalType(ReturnType->getPointeeType()),
3296 Context.getCanonicalType(Context.getTypeDeclType(MD->getParent())))) {
3297 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_return_type);
3301 ImplicitExceptionSpecification Spec(Context);
3303 llvm::tie(Spec, Const) =
3304 ComputeDefaultedCopyCtorExceptionSpecAndConst(MD->getParent());
3306 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3307 const FunctionProtoType *OperType = MD->getType()->getAs<FunctionProtoType>(),
3308 *ExceptionType = Context.getFunctionType(
3309 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3311 QualType ArgType = OperType->getArgType(0);
3312 if (!ArgType->isReferenceType()) {
3313 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
3316 if (ArgType->getPointeeType().isVolatileQualified()) {
3317 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_volatile_param);
3320 if (ArgType->getPointeeType().isConstQualified() && !Const) {
3321 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_const_param);
3326 if (OperType->getTypeQuals()) {
3327 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_quals);
3331 if (OperType->hasExceptionSpec()) {
3332 if (CheckEquivalentExceptionSpec(
3333 PDiag(diag::err_incorrect_defaulted_exception_spec)
3334 << CXXCopyAssignment,
3336 ExceptionType, SourceLocation(),
3337 OperType, MD->getLocation())) {
3341 // We set the declaration to have the computed exception spec here.
3342 // We duplicate the one parameter type.
3343 EPI.RefQualifier = OperType->getRefQualifier();
3344 EPI.ExtInfo = OperType->getExtInfo();
3345 MD->setType(Context.getFunctionType(ReturnType, &ArgType, 1, EPI));
3349 MD->setInvalidDecl();
3353 if (ShouldDeleteCopyAssignmentOperator(MD)) {
3355 MD->setDeletedAsWritten();
3357 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes)
3358 << CXXCopyAssignment;
3359 MD->setInvalidDecl();
3364 void Sema::CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *DD) {
3365 assert(DD->isExplicitlyDefaulted());
3367 // Whether this was the first-declared instance of the destructor.
3368 bool First = DD == DD->getCanonicalDecl();
3370 ImplicitExceptionSpecification Spec
3371 = ComputeDefaultedDtorExceptionSpec(DD->getParent());
3372 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
3373 const FunctionProtoType *DtorType = DD->getType()->getAs<FunctionProtoType>(),
3374 *ExceptionType = Context.getFunctionType(
3375 Context.VoidTy, 0, 0, EPI)->getAs<FunctionProtoType>();
3377 if (DtorType->hasExceptionSpec()) {
3378 if (CheckEquivalentExceptionSpec(
3379 PDiag(diag::err_incorrect_defaulted_exception_spec)
3382 ExceptionType, SourceLocation(),
3383 DtorType, DD->getLocation())) {
3384 DD->setInvalidDecl();
3388 // We set the declaration to have the computed exception spec here.
3389 // There are no parameters.
3390 EPI.ExtInfo = DtorType->getExtInfo();
3391 DD->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
3394 if (ShouldDeleteDestructor(DD)) {
3396 DD->setDeletedAsWritten();
3398 Diag(DD->getLocation(), diag::err_out_of_line_default_deletes)
3400 DD->setInvalidDecl();
3405 bool Sema::ShouldDeleteDefaultConstructor(CXXConstructorDecl *CD) {
3406 CXXRecordDecl *RD = CD->getParent();
3407 assert(!RD->isDependentType() && "do deletion after instantiation");
3408 if (!LangOpts.CPlusPlus0x)
3411 SourceLocation Loc = CD->getLocation();
3413 // Do access control from the constructor
3414 ContextRAII CtorContext(*this, CD);
3416 bool Union = RD->isUnion();
3417 bool AllConst = true;
3419 // We do this because we should never actually use an anonymous
3420 // union's constructor.
3421 if (Union && RD->isAnonymousStructOrUnion())
3424 // FIXME: We should put some diagnostic logic right into this function.
3426 // C++0x [class.ctor]/5
3427 // A defaulted default constructor for class X is defined as deleted if:
3429 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3430 BE = RD->bases_end();
3432 // We'll handle this one later
3433 if (BI->isVirtual())
3436 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3437 assert(BaseDecl && "base isn't a CXXRecordDecl");
3439 // -- any [direct base class] has a type with a destructor that is
3440 // deleted or inaccessible from the defaulted default constructor
3441 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3442 if (BaseDtor->isDeleted())
3444 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3448 // -- any [direct base class either] has no default constructor or
3449 // overload resolution as applied to [its] default constructor
3450 // results in an ambiguity or in a function that is deleted or
3451 // inaccessible from the defaulted default constructor
3452 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3453 if (!BaseDefault || BaseDefault->isDeleted())
3456 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3457 PDiag()) != AR_accessible)
3461 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3462 BE = RD->vbases_end();
3464 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3465 assert(BaseDecl && "base isn't a CXXRecordDecl");
3467 // -- any [virtual base class] has a type with a destructor that is
3468 // delete or inaccessible from the defaulted default constructor
3469 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3470 if (BaseDtor->isDeleted())
3472 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3476 // -- any [virtual base class either] has no default constructor or
3477 // overload resolution as applied to [its] default constructor
3478 // results in an ambiguity or in a function that is deleted or
3479 // inaccessible from the defaulted default constructor
3480 CXXConstructorDecl *BaseDefault = LookupDefaultConstructor(BaseDecl);
3481 if (!BaseDefault || BaseDefault->isDeleted())
3484 if (CheckConstructorAccess(Loc, BaseDefault, BaseDefault->getAccess(),
3485 PDiag()) != AR_accessible)
3489 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3490 FE = RD->field_end();
3492 if (FI->isInvalidDecl())
3495 QualType FieldType = Context.getBaseElementType(FI->getType());
3496 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3498 // -- any non-static data member with no brace-or-equal-initializer is of
3500 if (FieldType->isReferenceType() && !FI->hasInClassInitializer())
3503 // -- X is a union and all its variant members are of const-qualified type
3504 // (or array thereof)
3505 if (Union && !FieldType.isConstQualified())
3509 // -- X is a union-like class that has a variant member with a non-trivial
3510 // default constructor
3511 if (Union && !FieldRecord->hasTrivialDefaultConstructor())
3514 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3515 if (FieldDtor->isDeleted())
3517 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3521 // -- any non-variant non-static data member of const-qualified type (or
3522 // array thereof) with no brace-or-equal-initializer does not have a
3523 // user-provided default constructor
3524 if (FieldType.isConstQualified() &&
3525 !FI->hasInClassInitializer() &&
3526 !FieldRecord->hasUserProvidedDefaultConstructor())
3529 if (!Union && FieldRecord->isUnion() &&
3530 FieldRecord->isAnonymousStructOrUnion()) {
3531 // We're okay to reuse AllConst here since we only care about the
3532 // value otherwise if we're in a union.
3535 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3536 UE = FieldRecord->field_end();
3538 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3539 CXXRecordDecl *UnionFieldRecord =
3540 UnionFieldType->getAsCXXRecordDecl();
3542 if (!UnionFieldType.isConstQualified())
3545 if (UnionFieldRecord &&
3546 !UnionFieldRecord->hasTrivialDefaultConstructor())
3553 // Don't try to initialize the anonymous union
3554 // This is technically non-conformant, but sanity demands it.
3558 // -- any non-static data member with no brace-or-equal-initializer has
3559 // class type M (or array thereof) and either M has no default
3560 // constructor or overload resolution as applied to M's default
3561 // constructor results in an ambiguity or in a function that is deleted
3562 // or inaccessible from the defaulted default constructor.
3563 if (!FI->hasInClassInitializer()) {
3564 CXXConstructorDecl *FieldDefault = LookupDefaultConstructor(FieldRecord);
3565 if (!FieldDefault || FieldDefault->isDeleted())
3567 if (CheckConstructorAccess(Loc, FieldDefault, FieldDefault->getAccess(),
3568 PDiag()) != AR_accessible)
3571 } else if (!Union && FieldType.isConstQualified() &&
3572 !FI->hasInClassInitializer()) {
3573 // -- any non-variant non-static data member of const-qualified type (or
3574 // array thereof) with no brace-or-equal-initializer does not have a
3575 // user-provided default constructor
3580 if (Union && AllConst)
3586 bool Sema::ShouldDeleteCopyConstructor(CXXConstructorDecl *CD) {
3587 CXXRecordDecl *RD = CD->getParent();
3588 assert(!RD->isDependentType() && "do deletion after instantiation");
3589 if (!LangOpts.CPlusPlus0x)
3592 SourceLocation Loc = CD->getLocation();
3594 // Do access control from the constructor
3595 ContextRAII CtorContext(*this, CD);
3597 bool Union = RD->isUnion();
3599 assert(!CD->getParamDecl(0)->getType()->getPointeeType().isNull() &&
3600 "copy assignment arg has no pointee type");
3602 CD->getParamDecl(0)->getType()->getPointeeType().isConstQualified() ?
3603 Qualifiers::Const : 0;
3605 // We do this because we should never actually use an anonymous
3606 // union's constructor.
3607 if (Union && RD->isAnonymousStructOrUnion())
3610 // FIXME: We should put some diagnostic logic right into this function.
3612 // C++0x [class.copy]/11
3613 // A defaulted [copy] constructor for class X is defined as delete if X has:
3615 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3616 BE = RD->bases_end();
3618 // We'll handle this one later
3619 if (BI->isVirtual())
3622 QualType BaseType = BI->getType();
3623 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3624 assert(BaseDecl && "base isn't a CXXRecordDecl");
3626 // -- any [direct base class] of a type with a destructor that is deleted or
3627 // inaccessible from the defaulted constructor
3628 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3629 if (BaseDtor->isDeleted())
3631 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3635 // -- a [direct base class] B that cannot be [copied] because overload
3636 // resolution, as applied to B's [copy] constructor, results in an
3637 // ambiguity or a function that is deleted or inaccessible from the
3638 // defaulted constructor
3639 CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
3640 if (!BaseCtor || BaseCtor->isDeleted())
3642 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3647 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3648 BE = RD->vbases_end();
3650 QualType BaseType = BI->getType();
3651 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3652 assert(BaseDecl && "base isn't a CXXRecordDecl");
3654 // -- any [virtual base class] of a type with a destructor that is deleted or
3655 // inaccessible from the defaulted constructor
3656 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3657 if (BaseDtor->isDeleted())
3659 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3663 // -- a [virtual base class] B that cannot be [copied] because overload
3664 // resolution, as applied to B's [copy] constructor, results in an
3665 // ambiguity or a function that is deleted or inaccessible from the
3666 // defaulted constructor
3667 CXXConstructorDecl *BaseCtor = LookupCopyConstructor(BaseDecl, ArgQuals);
3668 if (!BaseCtor || BaseCtor->isDeleted())
3670 if (CheckConstructorAccess(Loc, BaseCtor, BaseCtor->getAccess(), PDiag()) !=
3675 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3676 FE = RD->field_end();
3678 QualType FieldType = Context.getBaseElementType(FI->getType());
3680 // -- for a copy constructor, a non-static data member of rvalue reference
3682 if (FieldType->isRValueReferenceType())
3685 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3688 // This is an anonymous union
3689 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3690 // Anonymous unions inside unions do not variant members create
3692 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3693 UE = FieldRecord->field_end();
3695 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3696 CXXRecordDecl *UnionFieldRecord =
3697 UnionFieldType->getAsCXXRecordDecl();
3699 // -- a variant member with a non-trivial [copy] constructor and X
3700 // is a union-like class
3701 if (UnionFieldRecord &&
3702 !UnionFieldRecord->hasTrivialCopyConstructor())
3707 // Don't try to initalize an anonymous union
3710 // -- a variant member with a non-trivial [copy] constructor and X is a
3712 if (Union && !FieldRecord->hasTrivialCopyConstructor())
3715 // -- any [non-static data member] of a type with a destructor that is
3716 // deleted or inaccessible from the defaulted constructor
3717 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
3718 if (FieldDtor->isDeleted())
3720 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
3725 // -- a [non-static data member of class type (or array thereof)] B that
3726 // cannot be [copied] because overload resolution, as applied to B's
3727 // [copy] constructor, results in an ambiguity or a function that is
3728 // deleted or inaccessible from the defaulted constructor
3729 CXXConstructorDecl *FieldCtor = LookupCopyConstructor(FieldRecord,
3731 if (!FieldCtor || FieldCtor->isDeleted())
3733 if (CheckConstructorAccess(Loc, FieldCtor, FieldCtor->getAccess(),
3734 PDiag()) != AR_accessible)
3742 bool Sema::ShouldDeleteCopyAssignmentOperator(CXXMethodDecl *MD) {
3743 CXXRecordDecl *RD = MD->getParent();
3744 assert(!RD->isDependentType() && "do deletion after instantiation");
3745 if (!LangOpts.CPlusPlus0x)
3748 SourceLocation Loc = MD->getLocation();
3750 // Do access control from the constructor
3751 ContextRAII MethodContext(*this, MD);
3753 bool Union = RD->isUnion();
3756 MD->getParamDecl(0)->getType()->getPointeeType().isConstQualified();
3758 // We do this because we should never actually use an anonymous
3759 // union's constructor.
3760 if (Union && RD->isAnonymousStructOrUnion())
3763 DeclarationName OperatorName =
3764 Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3765 LookupResult R(*this, OperatorName, Loc, LookupOrdinaryName);
3766 R.suppressDiagnostics();
3768 // FIXME: We should put some diagnostic logic right into this function.
3770 // C++0x [class.copy]/11
3771 // A defaulted [copy] assignment operator for class X is defined as deleted
3774 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3775 BE = RD->bases_end();
3777 // We'll handle this one later
3778 if (BI->isVirtual())
3781 QualType BaseType = BI->getType();
3782 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3783 assert(BaseDecl && "base isn't a CXXRecordDecl");
3785 // -- a [direct base class] B that cannot be [copied] because overload
3786 // resolution, as applied to B's [copy] assignment operator, results in
3787 // an ambiguity or a function that is deleted or inaccessible from the
3788 // assignment operator
3790 LookupQualifiedName(R, BaseDecl, false);
3792 // Filter out any result that isn't a copy-assignment operator.
3793 LookupResult::Filter F = R.makeFilter();
3794 while (F.hasNext()) {
3795 NamedDecl *D = F.next();
3796 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3797 if (Method->isCopyAssignmentOperator())
3804 // Build a fake argument expression
3805 QualType ArgType = BaseType;
3806 QualType ThisType = BaseType;
3809 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3810 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3813 OverloadCandidateSet OCS((Loc));
3814 OverloadCandidateSet::iterator Best;
3816 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3818 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3823 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3824 BE = RD->vbases_end();
3826 QualType BaseType = BI->getType();
3827 CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl();
3828 assert(BaseDecl && "base isn't a CXXRecordDecl");
3830 // -- a [virtual base class] B that cannot be [copied] because overload
3831 // resolution, as applied to B's [copy] assignment operator, results in
3832 // an ambiguity or a function that is deleted or inaccessible from the
3833 // assignment operator
3835 LookupQualifiedName(R, BaseDecl, false);
3837 // Filter out any result that isn't a copy-assignment operator.
3838 LookupResult::Filter F = R.makeFilter();
3839 while (F.hasNext()) {
3840 NamedDecl *D = F.next();
3841 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3842 if (Method->isCopyAssignmentOperator())
3849 // Build a fake argument expression
3850 QualType ArgType = BaseType;
3851 QualType ThisType = BaseType;
3854 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3855 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3858 OverloadCandidateSet OCS((Loc));
3859 OverloadCandidateSet::iterator Best;
3861 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3863 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3868 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
3869 FE = RD->field_end();
3871 QualType FieldType = Context.getBaseElementType(FI->getType());
3873 // -- a non-static data member of reference type
3874 if (FieldType->isReferenceType())
3877 // -- a non-static data member of const non-class type (or array thereof)
3878 if (FieldType.isConstQualified() && !FieldType->isRecordType())
3881 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
3884 // This is an anonymous union
3885 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
3886 // Anonymous unions inside unions do not variant members create
3888 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
3889 UE = FieldRecord->field_end();
3891 QualType UnionFieldType = Context.getBaseElementType(UI->getType());
3892 CXXRecordDecl *UnionFieldRecord =
3893 UnionFieldType->getAsCXXRecordDecl();
3895 // -- a variant member with a non-trivial [copy] assignment operator
3896 // and X is a union-like class
3897 if (UnionFieldRecord &&
3898 !UnionFieldRecord->hasTrivialCopyAssignment())
3903 // Don't try to initalize an anonymous union
3905 // -- a variant member with a non-trivial [copy] assignment operator
3906 // and X is a union-like class
3907 } else if (Union && !FieldRecord->hasTrivialCopyAssignment()) {
3911 LookupQualifiedName(R, FieldRecord, false);
3913 // Filter out any result that isn't a copy-assignment operator.
3914 LookupResult::Filter F = R.makeFilter();
3915 while (F.hasNext()) {
3916 NamedDecl *D = F.next();
3917 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
3918 if (Method->isCopyAssignmentOperator())
3925 // Build a fake argument expression
3926 QualType ArgType = FieldType;
3927 QualType ThisType = FieldType;
3930 Expr *Args[] = { new (Context) OpaqueValueExpr(Loc, ThisType, VK_LValue)
3931 , new (Context) OpaqueValueExpr(Loc, ArgType, VK_LValue)
3934 OverloadCandidateSet OCS((Loc));
3935 OverloadCandidateSet::iterator Best;
3937 AddFunctionCandidates(R.asUnresolvedSet(), Args, 2, OCS);
3939 if (OCS.BestViableFunction(*this, Loc, Best, false) !=
3948 bool Sema::ShouldDeleteDestructor(CXXDestructorDecl *DD) {
3949 CXXRecordDecl *RD = DD->getParent();
3950 assert(!RD->isDependentType() && "do deletion after instantiation");
3951 if (!LangOpts.CPlusPlus0x)
3954 SourceLocation Loc = DD->getLocation();
3956 // Do access control from the destructor
3957 ContextRAII CtorContext(*this, DD);
3959 bool Union = RD->isUnion();
3961 // We do this because we should never actually use an anonymous
3962 // union's destructor.
3963 if (Union && RD->isAnonymousStructOrUnion())
3966 // C++0x [class.dtor]p5
3967 // A defaulted destructor for a class X is defined as deleted if:
3968 for (CXXRecordDecl::base_class_iterator BI = RD->bases_begin(),
3969 BE = RD->bases_end();
3971 // We'll handle this one later
3972 if (BI->isVirtual())
3975 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3976 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3977 assert(BaseDtor && "base has no destructor");
3979 // -- any direct or virtual base class has a deleted destructor or
3980 // a destructor that is inaccessible from the defaulted destructor
3981 if (BaseDtor->isDeleted())
3983 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
3988 for (CXXRecordDecl::base_class_iterator BI = RD->vbases_begin(),
3989 BE = RD->vbases_end();
3991 CXXRecordDecl *BaseDecl = BI->getType()->getAsCXXRecordDecl();
3992 CXXDestructorDecl *BaseDtor = LookupDestructor(BaseDecl);
3993 assert(BaseDtor && "base has no destructor");
3995 // -- any direct or virtual base class has a deleted destructor or
3996 // a destructor that is inaccessible from the defaulted destructor
3997 if (BaseDtor->isDeleted())
3999 if (CheckDestructorAccess(Loc, BaseDtor, PDiag()) !=
4004 for (CXXRecordDecl::field_iterator FI = RD->field_begin(),
4005 FE = RD->field_end();
4007 QualType FieldType = Context.getBaseElementType(FI->getType());
4008 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
4010 if (FieldRecord->isUnion() && FieldRecord->isAnonymousStructOrUnion()) {
4011 for (CXXRecordDecl::field_iterator UI = FieldRecord->field_begin(),
4012 UE = FieldRecord->field_end();
4014 QualType UnionFieldType = Context.getBaseElementType(FI->getType());
4015 CXXRecordDecl *UnionFieldRecord =
4016 UnionFieldType->getAsCXXRecordDecl();
4018 // -- X is a union-like class that has a variant member with a non-
4019 // trivial destructor.
4020 if (UnionFieldRecord && !UnionFieldRecord->hasTrivialDestructor())
4023 // Technically we are supposed to do this next check unconditionally.
4024 // But that makes absolutely no sense.
4026 CXXDestructorDecl *FieldDtor = LookupDestructor(FieldRecord);
4028 // -- any of the non-static data members has class type M (or array
4029 // thereof) and M has a deleted destructor or a destructor that is
4030 // inaccessible from the defaulted destructor
4031 if (FieldDtor->isDeleted())
4033 if (CheckDestructorAccess(Loc, FieldDtor, PDiag()) !=
4037 // -- X is a union-like class that has a variant member with a non-
4038 // trivial destructor.
4039 if (Union && !FieldDtor->isTrivial())
4045 if (DD->isVirtual()) {
4046 FunctionDecl *OperatorDelete = 0;
4047 DeclarationName Name =
4048 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4049 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete,
4058 /// \brief Data used with FindHiddenVirtualMethod
4060 struct FindHiddenVirtualMethodData {
4062 CXXMethodDecl *Method;
4063 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
4064 llvm::SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
4068 /// \brief Member lookup function that determines whether a given C++
4069 /// method overloads virtual methods in a base class without overriding any,
4070 /// to be used with CXXRecordDecl::lookupInBases().
4071 static bool FindHiddenVirtualMethod(const CXXBaseSpecifier *Specifier,
4074 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
4076 FindHiddenVirtualMethodData &Data
4077 = *static_cast<FindHiddenVirtualMethodData*>(UserData);
4079 DeclarationName Name = Data.Method->getDeclName();
4080 assert(Name.getNameKind() == DeclarationName::Identifier);
4082 bool foundSameNameMethod = false;
4083 llvm::SmallVector<CXXMethodDecl *, 8> overloadedMethods;
4084 for (Path.Decls = BaseRecord->lookup(Name);
4085 Path.Decls.first != Path.Decls.second;
4086 ++Path.Decls.first) {
4087 NamedDecl *D = *Path.Decls.first;
4088 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
4089 MD = MD->getCanonicalDecl();
4090 foundSameNameMethod = true;
4091 // Interested only in hidden virtual methods.
4092 if (!MD->isVirtual())
4094 // If the method we are checking overrides a method from its base
4095 // don't warn about the other overloaded methods.
4096 if (!Data.S->IsOverload(Data.Method, MD, false))
4098 // Collect the overload only if its hidden.
4099 if (!Data.OverridenAndUsingBaseMethods.count(MD))
4100 overloadedMethods.push_back(MD);
4104 if (foundSameNameMethod)
4105 Data.OverloadedMethods.append(overloadedMethods.begin(),
4106 overloadedMethods.end());
4107 return foundSameNameMethod;
4110 /// \brief See if a method overloads virtual methods in a base class without
4112 void Sema::DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
4113 if (Diags.getDiagnosticLevel(diag::warn_overloaded_virtual,
4114 MD->getLocation()) == Diagnostic::Ignored)
4116 if (MD->getDeclName().getNameKind() != DeclarationName::Identifier)
4119 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
4120 /*bool RecordPaths=*/false,
4121 /*bool DetectVirtual=*/false);
4122 FindHiddenVirtualMethodData Data;
4126 // Keep the base methods that were overriden or introduced in the subclass
4127 // by 'using' in a set. A base method not in this set is hidden.
4128 for (DeclContext::lookup_result res = DC->lookup(MD->getDeclName());
4129 res.first != res.second; ++res.first) {
4130 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(*res.first))
4131 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
4132 E = MD->end_overridden_methods();
4134 Data.OverridenAndUsingBaseMethods.insert((*I)->getCanonicalDecl());
4135 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*res.first))
4136 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(shad->getTargetDecl()))
4137 Data.OverridenAndUsingBaseMethods.insert(MD->getCanonicalDecl());
4140 if (DC->lookupInBases(&FindHiddenVirtualMethod, &Data, Paths) &&
4141 !Data.OverloadedMethods.empty()) {
4142 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
4143 << MD << (Data.OverloadedMethods.size() > 1);
4145 for (unsigned i = 0, e = Data.OverloadedMethods.size(); i != e; ++i) {
4146 CXXMethodDecl *overloadedMD = Data.OverloadedMethods[i];
4147 Diag(overloadedMD->getLocation(),
4148 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
4153 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
4155 SourceLocation LBrac,
4156 SourceLocation RBrac,
4157 AttributeList *AttrList) {
4161 AdjustDeclIfTemplate(TagDecl);
4163 ActOnFields(S, RLoc, TagDecl,
4164 // strict aliasing violation!
4165 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
4166 FieldCollector->getCurNumFields(), LBrac, RBrac, AttrList);
4168 CheckCompletedCXXClass(
4169 dyn_cast_or_null<CXXRecordDecl>(TagDecl));
4172 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
4173 /// special functions, such as the default constructor, copy
4174 /// constructor, or destructor, to the given C++ class (C++
4175 /// [special]p1). This routine can only be executed just before the
4176 /// definition of the class is complete.
4177 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
4178 if (!ClassDecl->hasUserDeclaredConstructor())
4179 ++ASTContext::NumImplicitDefaultConstructors;
4181 if (!ClassDecl->hasUserDeclaredCopyConstructor())
4182 ++ASTContext::NumImplicitCopyConstructors;
4184 if (!ClassDecl->hasUserDeclaredCopyAssignment()) {
4185 ++ASTContext::NumImplicitCopyAssignmentOperators;
4187 // If we have a dynamic class, then the copy assignment operator may be
4188 // virtual, so we have to declare it immediately. This ensures that, e.g.,
4189 // it shows up in the right place in the vtable and that we diagnose
4190 // problems with the implicit exception specification.
4191 if (ClassDecl->isDynamicClass())
4192 DeclareImplicitCopyAssignment(ClassDecl);
4195 if (!ClassDecl->hasUserDeclaredDestructor()) {
4196 ++ASTContext::NumImplicitDestructors;
4198 // If we have a dynamic class, then the destructor may be virtual, so we
4199 // have to declare the destructor immediately. This ensures that, e.g., it
4200 // shows up in the right place in the vtable and that we diagnose problems
4201 // with the implicit exception specification.
4202 if (ClassDecl->isDynamicClass())
4203 DeclareImplicitDestructor(ClassDecl);
4207 void Sema::ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D) {
4211 int NumParamList = D->getNumTemplateParameterLists();
4212 for (int i = 0; i < NumParamList; i++) {
4213 TemplateParameterList* Params = D->getTemplateParameterList(i);
4214 for (TemplateParameterList::iterator Param = Params->begin(),
4215 ParamEnd = Params->end();
4216 Param != ParamEnd; ++Param) {
4217 NamedDecl *Named = cast<NamedDecl>(*Param);
4218 if (Named->getDeclName()) {
4220 IdResolver.AddDecl(Named);
4226 void Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
4230 TemplateParameterList *Params = 0;
4231 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
4232 Params = Template->getTemplateParameters();
4233 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4234 = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
4235 Params = PartialSpec->getTemplateParameters();
4239 for (TemplateParameterList::iterator Param = Params->begin(),
4240 ParamEnd = Params->end();
4241 Param != ParamEnd; ++Param) {
4242 NamedDecl *Named = cast<NamedDecl>(*Param);
4243 if (Named->getDeclName()) {
4245 IdResolver.AddDecl(Named);
4250 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4251 if (!RecordD) return;
4252 AdjustDeclIfTemplate(RecordD);
4253 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
4254 PushDeclContext(S, Record);
4257 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
4258 if (!RecordD) return;
4262 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
4263 /// parsing a top-level (non-nested) C++ class, and we are now
4264 /// parsing those parts of the given Method declaration that could
4265 /// not be parsed earlier (C++ [class.mem]p2), such as default
4266 /// arguments. This action should enter the scope of the given
4267 /// Method declaration as if we had just parsed the qualified method
4268 /// name. However, it should not bring the parameters into scope;
4269 /// that will be performed by ActOnDelayedCXXMethodParameter.
4270 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4273 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
4274 /// C++ method declaration. We're (re-)introducing the given
4275 /// function parameter into scope for use in parsing later parts of
4276 /// the method declaration. For example, we could see an
4277 /// ActOnParamDefaultArgument event for this parameter.
4278 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
4282 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
4284 // If this parameter has an unparsed default argument, clear it out
4285 // to make way for the parsed default argument.
4286 if (Param->hasUnparsedDefaultArg())
4287 Param->setDefaultArg(0);
4290 if (Param->getDeclName())
4291 IdResolver.AddDecl(Param);
4294 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
4295 /// processing the delayed method declaration for Method. The method
4296 /// declaration is now considered finished. There may be a separate
4297 /// ActOnStartOfFunctionDef action later (not necessarily
4298 /// immediately!) for this method, if it was also defined inside the
4300 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
4304 AdjustDeclIfTemplate(MethodD);
4306 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
4308 // Now that we have our default arguments, check the constructor
4309 // again. It could produce additional diagnostics or affect whether
4310 // the class has implicitly-declared destructors, among other
4312 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
4313 CheckConstructor(Constructor);
4315 // Check the default arguments, which we may have added.
4316 if (!Method->isInvalidDecl())
4317 CheckCXXDefaultArguments(Method);
4320 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
4321 /// the well-formedness of the constructor declarator @p D with type @p
4322 /// R. If there are any errors in the declarator, this routine will
4323 /// emit diagnostics and set the invalid bit to true. In any case, the type
4324 /// will be updated to reflect a well-formed type for the constructor and
4326 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
4328 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
4330 // C++ [class.ctor]p3:
4331 // A constructor shall not be virtual (10.3) or static (9.4). A
4332 // constructor can be invoked for a const, volatile or const
4333 // volatile object. A constructor shall not be declared const,
4334 // volatile, or const volatile (9.3.2).
4336 if (!D.isInvalidType())
4337 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4338 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
4339 << SourceRange(D.getIdentifierLoc());
4342 if (SC == SC_Static) {
4343 if (!D.isInvalidType())
4344 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
4345 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4346 << SourceRange(D.getIdentifierLoc());
4351 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4352 if (FTI.TypeQuals != 0) {
4353 if (FTI.TypeQuals & Qualifiers::Const)
4354 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4355 << "const" << SourceRange(D.getIdentifierLoc());
4356 if (FTI.TypeQuals & Qualifiers::Volatile)
4357 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4358 << "volatile" << SourceRange(D.getIdentifierLoc());
4359 if (FTI.TypeQuals & Qualifiers::Restrict)
4360 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
4361 << "restrict" << SourceRange(D.getIdentifierLoc());
4365 // C++0x [class.ctor]p4:
4366 // A constructor shall not be declared with a ref-qualifier.
4367 if (FTI.hasRefQualifier()) {
4368 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
4369 << FTI.RefQualifierIsLValueRef
4370 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4374 // Rebuild the function type "R" without any type qualifiers (in
4375 // case any of the errors above fired) and with "void" as the
4376 // return type, since constructors don't have return types.
4377 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4378 if (Proto->getResultType() == Context.VoidTy && !D.isInvalidType())
4381 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4383 EPI.RefQualifier = RQ_None;
4385 return Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
4386 Proto->getNumArgs(), EPI);
4389 /// CheckConstructor - Checks a fully-formed constructor for
4390 /// well-formedness, issuing any diagnostics required. Returns true if
4391 /// the constructor declarator is invalid.
4392 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
4393 CXXRecordDecl *ClassDecl
4394 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
4396 return Constructor->setInvalidDecl();
4398 // C++ [class.copy]p3:
4399 // A declaration of a constructor for a class X is ill-formed if
4400 // its first parameter is of type (optionally cv-qualified) X and
4401 // either there are no other parameters or else all other
4402 // parameters have default arguments.
4403 if (!Constructor->isInvalidDecl() &&
4404 ((Constructor->getNumParams() == 1) ||
4405 (Constructor->getNumParams() > 1 &&
4406 Constructor->getParamDecl(1)->hasDefaultArg())) &&
4407 Constructor->getTemplateSpecializationKind()
4408 != TSK_ImplicitInstantiation) {
4409 QualType ParamType = Constructor->getParamDecl(0)->getType();
4410 QualType ClassTy = Context.getTagDeclType(ClassDecl);
4411 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
4412 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
4413 const char *ConstRef
4414 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
4416 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
4417 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
4419 // FIXME: Rather that making the constructor invalid, we should endeavor
4421 Constructor->setInvalidDecl();
4426 /// CheckDestructor - Checks a fully-formed destructor definition for
4427 /// well-formedness, issuing any diagnostics required. Returns true
4429 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
4430 CXXRecordDecl *RD = Destructor->getParent();
4432 if (Destructor->isVirtual()) {
4435 if (!Destructor->isImplicit())
4436 Loc = Destructor->getLocation();
4438 Loc = RD->getLocation();
4440 // If we have a virtual destructor, look up the deallocation function
4441 FunctionDecl *OperatorDelete = 0;
4442 DeclarationName Name =
4443 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
4444 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
4447 MarkDeclarationReferenced(Loc, OperatorDelete);
4449 Destructor->setOperatorDelete(OperatorDelete);
4456 FTIHasSingleVoidArgument(DeclaratorChunk::FunctionTypeInfo &FTI) {
4457 return (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4458 FTI.ArgInfo[0].Param &&
4459 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType());
4462 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
4463 /// the well-formednes of the destructor declarator @p D with type @p
4464 /// R. If there are any errors in the declarator, this routine will
4465 /// emit diagnostics and set the declarator to invalid. Even if this happens,
4466 /// will be updated to reflect a well-formed type for the destructor and
4468 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
4470 // C++ [class.dtor]p1:
4471 // [...] A typedef-name that names a class is a class-name
4472 // (7.1.3); however, a typedef-name that names a class shall not
4473 // be used as the identifier in the declarator for a destructor
4475 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
4476 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
4477 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4478 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
4479 else if (const TemplateSpecializationType *TST =
4480 DeclaratorType->getAs<TemplateSpecializationType>())
4481 if (TST->isTypeAlias())
4482 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
4483 << DeclaratorType << 1;
4485 // C++ [class.dtor]p2:
4486 // A destructor is used to destroy objects of its class type. A
4487 // destructor takes no parameters, and no return type can be
4488 // specified for it (not even void). The address of a destructor
4489 // shall not be taken. A destructor shall not be static. A
4490 // destructor can be invoked for a const, volatile or const
4491 // volatile object. A destructor shall not be declared const,
4492 // volatile or const volatile (9.3.2).
4493 if (SC == SC_Static) {
4494 if (!D.isInvalidType())
4495 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
4496 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4497 << SourceRange(D.getIdentifierLoc())
4498 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
4502 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4503 // Destructors don't have return types, but the parser will
4504 // happily parse something like:
4510 // The return type will be eliminated later.
4511 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
4512 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4513 << SourceRange(D.getIdentifierLoc());
4516 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4517 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
4518 if (FTI.TypeQuals & Qualifiers::Const)
4519 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4520 << "const" << SourceRange(D.getIdentifierLoc());
4521 if (FTI.TypeQuals & Qualifiers::Volatile)
4522 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4523 << "volatile" << SourceRange(D.getIdentifierLoc());
4524 if (FTI.TypeQuals & Qualifiers::Restrict)
4525 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
4526 << "restrict" << SourceRange(D.getIdentifierLoc());
4530 // C++0x [class.dtor]p2:
4531 // A destructor shall not be declared with a ref-qualifier.
4532 if (FTI.hasRefQualifier()) {
4533 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
4534 << FTI.RefQualifierIsLValueRef
4535 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
4539 // Make sure we don't have any parameters.
4540 if (FTI.NumArgs > 0 && !FTIHasSingleVoidArgument(FTI)) {
4541 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
4543 // Delete the parameters.
4548 // Make sure the destructor isn't variadic.
4549 if (FTI.isVariadic) {
4550 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
4554 // Rebuild the function type "R" without any type qualifiers or
4555 // parameters (in case any of the errors above fired) and with
4556 // "void" as the return type, since destructors don't have return
4558 if (!D.isInvalidType())
4561 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4562 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4563 EPI.Variadic = false;
4565 EPI.RefQualifier = RQ_None;
4566 return Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
4569 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
4570 /// well-formednes of the conversion function declarator @p D with
4571 /// type @p R. If there are any errors in the declarator, this routine
4572 /// will emit diagnostics and return true. Otherwise, it will return
4573 /// false. Either way, the type @p R will be updated to reflect a
4574 /// well-formed type for the conversion operator.
4575 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
4577 // C++ [class.conv.fct]p1:
4578 // Neither parameter types nor return type can be specified. The
4579 // type of a conversion function (8.3.5) is "function taking no
4580 // parameter returning conversion-type-id."
4581 if (SC == SC_Static) {
4582 if (!D.isInvalidType())
4583 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
4584 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
4585 << SourceRange(D.getIdentifierLoc());
4590 QualType ConvType = GetTypeFromParser(D.getName().ConversionFunctionId);
4592 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
4593 // Conversion functions don't have return types, but the parser will
4594 // happily parse something like:
4597 // float operator bool();
4600 // The return type will be changed later anyway.
4601 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
4602 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
4603 << SourceRange(D.getIdentifierLoc());
4607 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
4609 // Make sure we don't have any parameters.
4610 if (Proto->getNumArgs() > 0) {
4611 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
4613 // Delete the parameters.
4614 D.getFunctionTypeInfo().freeArgs();
4616 } else if (Proto->isVariadic()) {
4617 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
4621 // Diagnose "&operator bool()" and other such nonsense. This
4622 // is actually a gcc extension which we don't support.
4623 if (Proto->getResultType() != ConvType) {
4624 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
4625 << Proto->getResultType();
4627 ConvType = Proto->getResultType();
4630 // C++ [class.conv.fct]p4:
4631 // The conversion-type-id shall not represent a function type nor
4633 if (ConvType->isArrayType()) {
4634 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
4635 ConvType = Context.getPointerType(ConvType);
4637 } else if (ConvType->isFunctionType()) {
4638 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
4639 ConvType = Context.getPointerType(ConvType);
4643 // Rebuild the function type "R" without any parameters (in case any
4644 // of the errors above fired) and with the conversion type as the
4646 if (D.isInvalidType())
4647 R = Context.getFunctionType(ConvType, 0, 0, Proto->getExtProtoInfo());
4649 // C++0x explicit conversion operators.
4650 if (D.getDeclSpec().isExplicitSpecified() && !getLangOptions().CPlusPlus0x)
4651 Diag(D.getDeclSpec().getExplicitSpecLoc(),
4652 diag::warn_explicit_conversion_functions)
4653 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
4656 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
4657 /// the declaration of the given C++ conversion function. This routine
4658 /// is responsible for recording the conversion function in the C++
4659 /// class, if possible.
4660 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
4661 assert(Conversion && "Expected to receive a conversion function declaration");
4663 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
4665 // Make sure we aren't redeclaring the conversion function.
4666 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
4668 // C++ [class.conv.fct]p1:
4669 // [...] A conversion function is never used to convert a
4670 // (possibly cv-qualified) object to the (possibly cv-qualified)
4671 // same object type (or a reference to it), to a (possibly
4672 // cv-qualified) base class of that type (or a reference to it),
4673 // or to (possibly cv-qualified) void.
4674 // FIXME: Suppress this warning if the conversion function ends up being a
4675 // virtual function that overrides a virtual function in a base class.
4677 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
4678 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
4679 ConvType = ConvTypeRef->getPointeeType();
4680 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
4681 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
4682 /* Suppress diagnostics for instantiations. */;
4683 else if (ConvType->isRecordType()) {
4684 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
4685 if (ConvType == ClassType)
4686 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
4688 else if (IsDerivedFrom(ClassType, ConvType))
4689 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
4690 << ClassType << ConvType;
4691 } else if (ConvType->isVoidType()) {
4692 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
4693 << ClassType << ConvType;
4696 if (FunctionTemplateDecl *ConversionTemplate
4697 = Conversion->getDescribedFunctionTemplate())
4698 return ConversionTemplate;
4703 //===----------------------------------------------------------------------===//
4704 // Namespace Handling
4705 //===----------------------------------------------------------------------===//
4709 /// ActOnStartNamespaceDef - This is called at the start of a namespace
4711 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
4712 SourceLocation InlineLoc,
4713 SourceLocation NamespaceLoc,
4714 SourceLocation IdentLoc,
4716 SourceLocation LBrace,
4717 AttributeList *AttrList) {
4718 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
4719 // For anonymous namespace, take the location of the left brace.
4720 SourceLocation Loc = II ? IdentLoc : LBrace;
4721 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext,
4723 Namespc->setInline(InlineLoc.isValid());
4725 Scope *DeclRegionScope = NamespcScope->getParent();
4727 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
4729 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
4730 PushNamespaceVisibilityAttr(Attr);
4733 // C++ [namespace.def]p2:
4734 // The identifier in an original-namespace-definition shall not
4735 // have been previously defined in the declarative region in
4736 // which the original-namespace-definition appears. The
4737 // identifier in an original-namespace-definition is the name of
4738 // the namespace. Subsequently in that declarative region, it is
4739 // treated as an original-namespace-name.
4741 // Since namespace names are unique in their scope, and we don't
4742 // look through using directives, just look for any ordinary names.
4744 const unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Member |
4745 Decl::IDNS_Type | Decl::IDNS_Using | Decl::IDNS_Tag |
4746 Decl::IDNS_Namespace;
4747 NamedDecl *PrevDecl = 0;
4748 for (DeclContext::lookup_result R
4749 = CurContext->getRedeclContext()->lookup(II);
4750 R.first != R.second; ++R.first) {
4751 if ((*R.first)->getIdentifierNamespace() & IDNS) {
4752 PrevDecl = *R.first;
4757 if (NamespaceDecl *OrigNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl)) {
4758 // This is an extended namespace definition.
4759 if (Namespc->isInline() != OrigNS->isInline()) {
4760 // inline-ness must match
4761 if (OrigNS->isInline()) {
4762 // The user probably just forgot the 'inline', so suggest that it
4764 Diag(Namespc->getLocation(),
4765 diag::warn_inline_namespace_reopened_noninline)
4766 << FixItHint::CreateInsertion(NamespaceLoc, "inline ");
4768 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4769 << Namespc->isInline();
4771 Diag(OrigNS->getLocation(), diag::note_previous_definition);
4773 // Recover by ignoring the new namespace's inline status.
4774 Namespc->setInline(OrigNS->isInline());
4777 // Attach this namespace decl to the chain of extended namespace
4779 OrigNS->setNextNamespace(Namespc);
4780 Namespc->setOriginalNamespace(OrigNS->getOriginalNamespace());
4782 // Remove the previous declaration from the scope.
4783 if (DeclRegionScope->isDeclScope(OrigNS)) {
4784 IdResolver.RemoveDecl(OrigNS);
4785 DeclRegionScope->RemoveDecl(OrigNS);
4787 } else if (PrevDecl) {
4788 // This is an invalid name redefinition.
4789 Diag(Namespc->getLocation(), diag::err_redefinition_different_kind)
4790 << Namespc->getDeclName();
4791 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4792 Namespc->setInvalidDecl();
4793 // Continue on to push Namespc as current DeclContext and return it.
4794 } else if (II->isStr("std") &&
4795 CurContext->getRedeclContext()->isTranslationUnit()) {
4796 // This is the first "real" definition of the namespace "std", so update
4797 // our cache of the "std" namespace to point at this definition.
4798 if (NamespaceDecl *StdNS = getStdNamespace()) {
4799 // We had already defined a dummy namespace "std". Link this new
4800 // namespace definition to the dummy namespace "std".
4801 StdNS->setNextNamespace(Namespc);
4802 StdNS->setLocation(IdentLoc);
4803 Namespc->setOriginalNamespace(StdNS->getOriginalNamespace());
4806 // Make our StdNamespace cache point at the first real definition of the
4808 StdNamespace = Namespc;
4811 PushOnScopeChains(Namespc, DeclRegionScope);
4813 // Anonymous namespaces.
4814 assert(Namespc->isAnonymousNamespace());
4816 // Link the anonymous namespace into its parent.
4817 NamespaceDecl *PrevDecl;
4818 DeclContext *Parent = CurContext->getRedeclContext();
4819 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
4820 PrevDecl = TU->getAnonymousNamespace();
4821 TU->setAnonymousNamespace(Namespc);
4823 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
4824 PrevDecl = ND->getAnonymousNamespace();
4825 ND->setAnonymousNamespace(Namespc);
4828 // Link the anonymous namespace with its previous declaration.
4830 assert(PrevDecl->isAnonymousNamespace());
4831 assert(!PrevDecl->getNextNamespace());
4832 Namespc->setOriginalNamespace(PrevDecl->getOriginalNamespace());
4833 PrevDecl->setNextNamespace(Namespc);
4835 if (Namespc->isInline() != PrevDecl->isInline()) {
4836 // inline-ness must match
4837 Diag(Namespc->getLocation(), diag::err_inline_namespace_mismatch)
4838 << Namespc->isInline();
4839 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
4840 Namespc->setInvalidDecl();
4841 // Recover by ignoring the new namespace's inline status.
4842 Namespc->setInline(PrevDecl->isInline());
4846 CurContext->addDecl(Namespc);
4848 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
4849 // behaves as if it were replaced by
4850 // namespace unique { /* empty body */ }
4851 // using namespace unique;
4852 // namespace unique { namespace-body }
4853 // where all occurrences of 'unique' in a translation unit are
4854 // replaced by the same identifier and this identifier differs
4855 // from all other identifiers in the entire program.
4857 // We just create the namespace with an empty name and then add an
4858 // implicit using declaration, just like the standard suggests.
4860 // CodeGen enforces the "universally unique" aspect by giving all
4861 // declarations semantically contained within an anonymous
4862 // namespace internal linkage.
4865 UsingDirectiveDecl* UD
4866 = UsingDirectiveDecl::Create(Context, CurContext,
4867 /* 'using' */ LBrace,
4868 /* 'namespace' */ SourceLocation(),
4869 /* qualifier */ NestedNameSpecifierLoc(),
4870 /* identifier */ SourceLocation(),
4872 /* Ancestor */ CurContext);
4874 CurContext->addDecl(UD);
4878 // Although we could have an invalid decl (i.e. the namespace name is a
4879 // redefinition), push it as current DeclContext and try to continue parsing.
4880 // FIXME: We should be able to push Namespc here, so that the each DeclContext
4881 // for the namespace has the declarations that showed up in that particular
4882 // namespace definition.
4883 PushDeclContext(NamespcScope, Namespc);
4887 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
4888 /// is a namespace alias, returns the namespace it points to.
4889 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
4890 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
4891 return AD->getNamespace();
4892 return dyn_cast_or_null<NamespaceDecl>(D);
4895 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
4896 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
4897 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
4898 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
4899 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
4900 Namespc->setRBraceLoc(RBrace);
4902 if (Namespc->hasAttr<VisibilityAttr>())
4903 PopPragmaVisibility();
4906 CXXRecordDecl *Sema::getStdBadAlloc() const {
4907 return cast_or_null<CXXRecordDecl>(
4908 StdBadAlloc.get(Context.getExternalSource()));
4911 NamespaceDecl *Sema::getStdNamespace() const {
4912 return cast_or_null<NamespaceDecl>(
4913 StdNamespace.get(Context.getExternalSource()));
4916 /// \brief Retrieve the special "std" namespace, which may require us to
4917 /// implicitly define the namespace.
4918 NamespaceDecl *Sema::getOrCreateStdNamespace() {
4919 if (!StdNamespace) {
4920 // The "std" namespace has not yet been defined, so build one implicitly.
4921 StdNamespace = NamespaceDecl::Create(Context,
4922 Context.getTranslationUnitDecl(),
4923 SourceLocation(), SourceLocation(),
4924 &PP.getIdentifierTable().get("std"));
4925 getStdNamespace()->setImplicit(true);
4928 return getStdNamespace();
4931 /// \brief Determine whether a using statement is in a context where it will be
4932 /// apply in all contexts.
4933 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
4934 switch (CurContext->getDeclKind()) {
4935 case Decl::TranslationUnit:
4937 case Decl::LinkageSpec:
4938 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
4944 Decl *Sema::ActOnUsingDirective(Scope *S,
4945 SourceLocation UsingLoc,
4946 SourceLocation NamespcLoc,
4948 SourceLocation IdentLoc,
4949 IdentifierInfo *NamespcName,
4950 AttributeList *AttrList) {
4951 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
4952 assert(NamespcName && "Invalid NamespcName.");
4953 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
4955 // This can only happen along a recovery path.
4956 while (S->getFlags() & Scope::TemplateParamScope)
4958 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
4960 UsingDirectiveDecl *UDir = 0;
4961 NestedNameSpecifier *Qualifier = 0;
4963 Qualifier = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4965 // Lookup namespace name.
4966 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
4967 LookupParsedName(R, S, &SS);
4968 if (R.isAmbiguous())
4972 // Allow "using namespace std;" or "using namespace ::std;" even if
4973 // "std" hasn't been defined yet, for GCC compatibility.
4974 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
4975 NamespcName->isStr("std")) {
4976 Diag(IdentLoc, diag::ext_using_undefined_std);
4977 R.addDecl(getOrCreateStdNamespace());
4980 // Otherwise, attempt typo correction.
4981 else if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
4982 CTC_NoKeywords, 0)) {
4983 if (R.getAsSingle<NamespaceDecl>() ||
4984 R.getAsSingle<NamespaceAliasDecl>()) {
4985 if (DeclContext *DC = computeDeclContext(SS, false))
4986 Diag(IdentLoc, diag::err_using_directive_member_suggest)
4987 << NamespcName << DC << Corrected << SS.getRange()
4988 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4990 Diag(IdentLoc, diag::err_using_directive_suggest)
4991 << NamespcName << Corrected
4992 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
4993 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
4996 NamespcName = Corrected.getAsIdentifierInfo();
4999 R.setLookupName(NamespcName);
5005 NamedDecl *Named = R.getFoundDecl();
5006 assert((isa<NamespaceDecl>(Named) || isa<NamespaceAliasDecl>(Named))
5007 && "expected namespace decl");
5008 // C++ [namespace.udir]p1:
5009 // A using-directive specifies that the names in the nominated
5010 // namespace can be used in the scope in which the
5011 // using-directive appears after the using-directive. During
5012 // unqualified name lookup (3.4.1), the names appear as if they
5013 // were declared in the nearest enclosing namespace which
5014 // contains both the using-directive and the nominated
5015 // namespace. [Note: in this context, "contains" means "contains
5016 // directly or indirectly". ]
5018 // Find enclosing context containing both using-directive and
5019 // nominated namespace.
5020 NamespaceDecl *NS = getNamespaceDecl(Named);
5021 DeclContext *CommonAncestor = cast<DeclContext>(NS);
5022 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
5023 CommonAncestor = CommonAncestor->getParent();
5025 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
5026 SS.getWithLocInContext(Context),
5027 IdentLoc, Named, CommonAncestor);
5029 if (IsUsingDirectiveInToplevelContext(CurContext) &&
5030 !SourceMgr.isFromMainFile(SourceMgr.getInstantiationLoc(IdentLoc))) {
5031 Diag(IdentLoc, diag::warn_using_directive_in_header);
5034 PushUsingDirective(S, UDir);
5036 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
5039 // FIXME: We ignore attributes for now.
5043 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
5044 // If scope has associated entity, then using directive is at namespace
5045 // or translation unit scope. We add UsingDirectiveDecls, into
5046 // it's lookup structure.
5047 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
5050 // Otherwise it is block-sope. using-directives will affect lookup
5051 // only to the end of scope.
5052 S->PushUsingDirective(UDir);
5056 Decl *Sema::ActOnUsingDeclaration(Scope *S,
5058 bool HasUsingKeyword,
5059 SourceLocation UsingLoc,
5061 UnqualifiedId &Name,
5062 AttributeList *AttrList,
5064 SourceLocation TypenameLoc) {
5065 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
5067 switch (Name.getKind()) {
5068 case UnqualifiedId::IK_Identifier:
5069 case UnqualifiedId::IK_OperatorFunctionId:
5070 case UnqualifiedId::IK_LiteralOperatorId:
5071 case UnqualifiedId::IK_ConversionFunctionId:
5074 case UnqualifiedId::IK_ConstructorName:
5075 case UnqualifiedId::IK_ConstructorTemplateId:
5076 // C++0x inherited constructors.
5077 if (getLangOptions().CPlusPlus0x) break;
5079 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_constructor)
5083 case UnqualifiedId::IK_DestructorName:
5084 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_destructor)
5088 case UnqualifiedId::IK_TemplateId:
5089 Diag(Name.getSourceRange().getBegin(), diag::err_using_decl_template_id)
5090 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
5094 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
5095 DeclarationName TargetName = TargetNameInfo.getName();
5099 // Warn about using declarations.
5100 // TODO: store that the declaration was written without 'using' and
5101 // talk about access decls instead of using decls in the
5103 if (!HasUsingKeyword) {
5104 UsingLoc = Name.getSourceRange().getBegin();
5106 Diag(UsingLoc, diag::warn_access_decl_deprecated)
5107 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
5110 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
5111 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
5114 NamedDecl *UD = BuildUsingDeclaration(S, AS, UsingLoc, SS,
5115 TargetNameInfo, AttrList,
5116 /* IsInstantiation */ false,
5117 IsTypeName, TypenameLoc);
5119 PushOnScopeChains(UD, S, /*AddToContext*/ false);
5124 /// \brief Determine whether a using declaration considers the given
5125 /// declarations as "equivalent", e.g., if they are redeclarations of
5126 /// the same entity or are both typedefs of the same type.
5128 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2,
5129 bool &SuppressRedeclaration) {
5130 if (D1->getCanonicalDecl() == D2->getCanonicalDecl()) {
5131 SuppressRedeclaration = false;
5135 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
5136 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2)) {
5137 SuppressRedeclaration = true;
5138 return Context.hasSameType(TD1->getUnderlyingType(),
5139 TD2->getUnderlyingType());
5146 /// Determines whether to create a using shadow decl for a particular
5147 /// decl, given the set of decls existing prior to this using lookup.
5148 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
5149 const LookupResult &Previous) {
5150 // Diagnose finding a decl which is not from a base class of the
5151 // current class. We do this now because there are cases where this
5152 // function will silently decide not to build a shadow decl, which
5153 // will pre-empt further diagnostics.
5155 // We don't need to do this in C++0x because we do the check once on
5158 // FIXME: diagnose the following if we care enough:
5159 // struct A { int foo; };
5160 // struct B : A { using A::foo; };
5161 // template <class T> struct C : A {};
5162 // template <class T> struct D : C<T> { using B::foo; } // <---
5163 // This is invalid (during instantiation) in C++03 because B::foo
5164 // resolves to the using decl in B, which is not a base class of D<T>.
5165 // We can't diagnose it immediately because C<T> is an unknown
5166 // specialization. The UsingShadowDecl in D<T> then points directly
5167 // to A::foo, which will look well-formed when we instantiate.
5168 // The right solution is to not collapse the shadow-decl chain.
5169 if (!getLangOptions().CPlusPlus0x && CurContext->isRecord()) {
5170 DeclContext *OrigDC = Orig->getDeclContext();
5172 // Handle enums and anonymous structs.
5173 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
5174 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
5175 while (OrigRec->isAnonymousStructOrUnion())
5176 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
5178 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
5179 if (OrigDC == CurContext) {
5180 Diag(Using->getLocation(),
5181 diag::err_using_decl_nested_name_specifier_is_current_class)
5182 << Using->getQualifierLoc().getSourceRange();
5183 Diag(Orig->getLocation(), diag::note_using_decl_target);
5187 Diag(Using->getQualifierLoc().getBeginLoc(),
5188 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5189 << Using->getQualifier()
5190 << cast<CXXRecordDecl>(CurContext)
5191 << Using->getQualifierLoc().getSourceRange();
5192 Diag(Orig->getLocation(), diag::note_using_decl_target);
5197 if (Previous.empty()) return false;
5199 NamedDecl *Target = Orig;
5200 if (isa<UsingShadowDecl>(Target))
5201 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5203 // If the target happens to be one of the previous declarations, we
5204 // don't have a conflict.
5206 // FIXME: but we might be increasing its access, in which case we
5207 // should redeclare it.
5208 NamedDecl *NonTag = 0, *Tag = 0;
5209 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5211 NamedDecl *D = (*I)->getUnderlyingDecl();
5213 if (IsEquivalentForUsingDecl(Context, D, Target, Result))
5216 (isa<TagDecl>(D) ? Tag : NonTag) = D;
5219 if (Target->isFunctionOrFunctionTemplate()) {
5221 if (isa<FunctionTemplateDecl>(Target))
5222 FD = cast<FunctionTemplateDecl>(Target)->getTemplatedDecl();
5224 FD = cast<FunctionDecl>(Target);
5226 NamedDecl *OldDecl = 0;
5227 switch (CheckOverload(0, FD, Previous, OldDecl, /*IsForUsingDecl*/ true)) {
5231 case Ovl_NonFunction:
5232 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5235 // We found a decl with the exact signature.
5237 // If we're in a record, we want to hide the target, so we
5238 // return true (without a diagnostic) to tell the caller not to
5239 // build a shadow decl.
5240 if (CurContext->isRecord())
5243 // If we're not in a record, this is an error.
5244 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5248 Diag(Target->getLocation(), diag::note_using_decl_target);
5249 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
5253 // Target is not a function.
5255 if (isa<TagDecl>(Target)) {
5256 // No conflict between a tag and a non-tag.
5257 if (!Tag) return false;
5259 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5260 Diag(Target->getLocation(), diag::note_using_decl_target);
5261 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
5265 // No conflict between a tag and a non-tag.
5266 if (!NonTag) return false;
5268 Diag(Using->getLocation(), diag::err_using_decl_conflict);
5269 Diag(Target->getLocation(), diag::note_using_decl_target);
5270 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
5274 /// Builds a shadow declaration corresponding to a 'using' declaration.
5275 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
5279 // If we resolved to another shadow declaration, just coalesce them.
5280 NamedDecl *Target = Orig;
5281 if (isa<UsingShadowDecl>(Target)) {
5282 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
5283 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
5286 UsingShadowDecl *Shadow
5287 = UsingShadowDecl::Create(Context, CurContext,
5288 UD->getLocation(), UD, Target);
5289 UD->addShadowDecl(Shadow);
5291 Shadow->setAccess(UD->getAccess());
5292 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
5293 Shadow->setInvalidDecl();
5296 PushOnScopeChains(Shadow, S);
5298 CurContext->addDecl(Shadow);
5304 /// Hides a using shadow declaration. This is required by the current
5305 /// using-decl implementation when a resolvable using declaration in a
5306 /// class is followed by a declaration which would hide or override
5307 /// one or more of the using decl's targets; for example:
5309 /// struct Base { void foo(int); };
5310 /// struct Derived : Base {
5311 /// using Base::foo;
5315 /// The governing language is C++03 [namespace.udecl]p12:
5317 /// When a using-declaration brings names from a base class into a
5318 /// derived class scope, member functions in the derived class
5319 /// override and/or hide member functions with the same name and
5320 /// parameter types in a base class (rather than conflicting).
5322 /// There are two ways to implement this:
5323 /// (1) optimistically create shadow decls when they're not hidden
5324 /// by existing declarations, or
5325 /// (2) don't create any shadow decls (or at least don't make them
5326 /// visible) until we've fully parsed/instantiated the class.
5327 /// The problem with (1) is that we might have to retroactively remove
5328 /// a shadow decl, which requires several O(n) operations because the
5329 /// decl structures are (very reasonably) not designed for removal.
5330 /// (2) avoids this but is very fiddly and phase-dependent.
5331 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
5332 if (Shadow->getDeclName().getNameKind() ==
5333 DeclarationName::CXXConversionFunctionName)
5334 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
5336 // Remove it from the DeclContext...
5337 Shadow->getDeclContext()->removeDecl(Shadow);
5339 // ...and the scope, if applicable...
5341 S->RemoveDecl(Shadow);
5342 IdResolver.RemoveDecl(Shadow);
5345 // ...and the using decl.
5346 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
5348 // TODO: complain somehow if Shadow was used. It shouldn't
5349 // be possible for this to happen, because...?
5352 /// Builds a using declaration.
5354 /// \param IsInstantiation - Whether this call arises from an
5355 /// instantiation of an unresolved using declaration. We treat
5356 /// the lookup differently for these declarations.
5357 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
5358 SourceLocation UsingLoc,
5360 const DeclarationNameInfo &NameInfo,
5361 AttributeList *AttrList,
5362 bool IsInstantiation,
5364 SourceLocation TypenameLoc) {
5365 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
5366 SourceLocation IdentLoc = NameInfo.getLoc();
5367 assert(IdentLoc.isValid() && "Invalid TargetName location.");
5369 // FIXME: We ignore attributes for now.
5372 Diag(IdentLoc, diag::err_using_requires_qualname);
5376 // Do the redeclaration lookup in the current scope.
5377 LookupResult Previous(*this, NameInfo, LookupUsingDeclName,
5379 Previous.setHideTags(false);
5381 LookupName(Previous, S);
5383 // It is really dumb that we have to do this.
5384 LookupResult::Filter F = Previous.makeFilter();
5385 while (F.hasNext()) {
5386 NamedDecl *D = F.next();
5387 if (!isDeclInScope(D, CurContext, S))
5392 assert(IsInstantiation && "no scope in non-instantiation");
5393 assert(CurContext->isRecord() && "scope not record in instantiation");
5394 LookupQualifiedName(Previous, CurContext);
5397 // Check for invalid redeclarations.
5398 if (CheckUsingDeclRedeclaration(UsingLoc, IsTypeName, SS, IdentLoc, Previous))
5401 // Check for bad qualifiers.
5402 if (CheckUsingDeclQualifier(UsingLoc, SS, IdentLoc))
5405 DeclContext *LookupContext = computeDeclContext(SS);
5407 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
5408 if (!LookupContext) {
5410 // FIXME: not all declaration name kinds are legal here
5411 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
5412 UsingLoc, TypenameLoc,
5414 IdentLoc, NameInfo.getName());
5416 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
5417 QualifierLoc, NameInfo);
5420 D = UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
5421 NameInfo, IsTypeName);
5424 CurContext->addDecl(D);
5426 if (!LookupContext) return D;
5427 UsingDecl *UD = cast<UsingDecl>(D);
5429 if (RequireCompleteDeclContext(SS, LookupContext)) {
5430 UD->setInvalidDecl();
5434 // Constructor inheriting using decls get special treatment.
5435 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
5436 if (CheckInheritedConstructorUsingDecl(UD))
5437 UD->setInvalidDecl();
5441 // Otherwise, look up the target name.
5443 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5444 R.setUsingDeclaration(true);
5446 // Unlike most lookups, we don't always want to hide tag
5447 // declarations: tag names are visible through the using declaration
5448 // even if hidden by ordinary names, *except* in a dependent context
5449 // where it's important for the sanity of two-phase lookup.
5450 if (!IsInstantiation)
5451 R.setHideTags(false);
5453 LookupQualifiedName(R, LookupContext);
5456 Diag(IdentLoc, diag::err_no_member)
5457 << NameInfo.getName() << LookupContext << SS.getRange();
5458 UD->setInvalidDecl();
5462 if (R.isAmbiguous()) {
5463 UD->setInvalidDecl();
5468 // If we asked for a typename and got a non-type decl, error out.
5469 if (!R.getAsSingle<TypeDecl>()) {
5470 Diag(IdentLoc, diag::err_using_typename_non_type);
5471 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
5472 Diag((*I)->getUnderlyingDecl()->getLocation(),
5473 diag::note_using_decl_target);
5474 UD->setInvalidDecl();
5478 // If we asked for a non-typename and we got a type, error out,
5479 // but only if this is an instantiation of an unresolved using
5480 // decl. Otherwise just silently find the type name.
5481 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
5482 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
5483 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
5484 UD->setInvalidDecl();
5489 // C++0x N2914 [namespace.udecl]p6:
5490 // A using-declaration shall not name a namespace.
5491 if (R.getAsSingle<NamespaceDecl>()) {
5492 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
5494 UD->setInvalidDecl();
5498 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5499 if (!CheckUsingShadowDecl(UD, *I, Previous))
5500 BuildUsingShadowDecl(S, UD, *I);
5506 /// Additional checks for a using declaration referring to a constructor name.
5507 bool Sema::CheckInheritedConstructorUsingDecl(UsingDecl *UD) {
5508 if (UD->isTypeName()) {
5509 // FIXME: Cannot specify typename when specifying constructor
5513 const Type *SourceType = UD->getQualifier()->getAsType();
5514 assert(SourceType &&
5515 "Using decl naming constructor doesn't have type in scope spec.");
5516 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
5518 // Check whether the named type is a direct base class.
5519 CanQualType CanonicalSourceType = SourceType->getCanonicalTypeUnqualified();
5520 CXXRecordDecl::base_class_iterator BaseIt, BaseE;
5521 for (BaseIt = TargetClass->bases_begin(), BaseE = TargetClass->bases_end();
5522 BaseIt != BaseE; ++BaseIt) {
5523 CanQualType BaseType = BaseIt->getType()->getCanonicalTypeUnqualified();
5524 if (CanonicalSourceType == BaseType)
5528 if (BaseIt == BaseE) {
5529 // Did not find SourceType in the bases.
5530 Diag(UD->getUsingLocation(),
5531 diag::err_using_decl_constructor_not_in_direct_base)
5532 << UD->getNameInfo().getSourceRange()
5533 << QualType(SourceType, 0) << TargetClass;
5537 BaseIt->setInheritConstructors();
5542 /// Checks that the given using declaration is not an invalid
5543 /// redeclaration. Note that this is checking only for the using decl
5544 /// itself, not for any ill-formedness among the UsingShadowDecls.
5545 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5547 const CXXScopeSpec &SS,
5548 SourceLocation NameLoc,
5549 const LookupResult &Prev) {
5550 // C++03 [namespace.udecl]p8:
5551 // C++0x [namespace.udecl]p10:
5552 // A using-declaration is a declaration and can therefore be used
5553 // repeatedly where (and only where) multiple declarations are
5556 // That's in non-member contexts.
5557 if (!CurContext->getRedeclContext()->isRecord())
5560 NestedNameSpecifier *Qual
5561 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5563 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
5567 NestedNameSpecifier *DQual;
5568 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
5569 DTypename = UD->isTypeName();
5570 DQual = UD->getQualifier();
5571 } else if (UnresolvedUsingValueDecl *UD
5572 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
5574 DQual = UD->getQualifier();
5575 } else if (UnresolvedUsingTypenameDecl *UD
5576 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
5578 DQual = UD->getQualifier();
5581 // using decls differ if one says 'typename' and the other doesn't.
5582 // FIXME: non-dependent using decls?
5583 if (isTypeName != DTypename) continue;
5585 // using decls differ if they name different scopes (but note that
5586 // template instantiation can cause this check to trigger when it
5587 // didn't before instantiation).
5588 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
5589 Context.getCanonicalNestedNameSpecifier(DQual))
5592 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
5593 Diag(D->getLocation(), diag::note_using_decl) << 1;
5601 /// Checks that the given nested-name qualifier used in a using decl
5602 /// in the current context is appropriately related to the current
5603 /// scope. If an error is found, diagnoses it and returns true.
5604 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
5605 const CXXScopeSpec &SS,
5606 SourceLocation NameLoc) {
5607 DeclContext *NamedContext = computeDeclContext(SS);
5609 if (!CurContext->isRecord()) {
5610 // C++03 [namespace.udecl]p3:
5611 // C++0x [namespace.udecl]p8:
5612 // A using-declaration for a class member shall be a member-declaration.
5614 // If we weren't able to compute a valid scope, it must be a
5615 // dependent class scope.
5616 if (!NamedContext || NamedContext->isRecord()) {
5617 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
5622 // Otherwise, everything is known to be fine.
5626 // The current scope is a record.
5628 // If the named context is dependent, we can't decide much.
5629 if (!NamedContext) {
5630 // FIXME: in C++0x, we can diagnose if we can prove that the
5631 // nested-name-specifier does not refer to a base class, which is
5632 // still possible in some cases.
5634 // Otherwise we have to conservatively report that things might be
5639 if (!NamedContext->isRecord()) {
5640 // Ideally this would point at the last name in the specifier,
5641 // but we don't have that level of source info.
5642 Diag(SS.getRange().getBegin(),
5643 diag::err_using_decl_nested_name_specifier_is_not_class)
5644 << (NestedNameSpecifier*) SS.getScopeRep() << SS.getRange();
5648 if (!NamedContext->isDependentContext() &&
5649 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
5652 if (getLangOptions().CPlusPlus0x) {
5653 // C++0x [namespace.udecl]p3:
5654 // In a using-declaration used as a member-declaration, the
5655 // nested-name-specifier shall name a base class of the class
5658 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
5659 cast<CXXRecordDecl>(NamedContext))) {
5660 if (CurContext == NamedContext) {
5662 diag::err_using_decl_nested_name_specifier_is_current_class)
5667 Diag(SS.getRange().getBegin(),
5668 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5669 << (NestedNameSpecifier*) SS.getScopeRep()
5670 << cast<CXXRecordDecl>(CurContext)
5678 // C++03 [namespace.udecl]p4:
5679 // A using-declaration used as a member-declaration shall refer
5680 // to a member of a base class of the class being defined [etc.].
5682 // Salient point: SS doesn't have to name a base class as long as
5683 // lookup only finds members from base classes. Therefore we can
5684 // diagnose here only if we can prove that that can't happen,
5685 // i.e. if the class hierarchies provably don't intersect.
5687 // TODO: it would be nice if "definitely valid" results were cached
5688 // in the UsingDecl and UsingShadowDecl so that these checks didn't
5689 // need to be repeated.
5692 llvm::DenseSet<const CXXRecordDecl*> Bases;
5694 static bool collect(const CXXRecordDecl *Base, void *OpaqueData) {
5695 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5696 Data->Bases.insert(Base);
5700 bool hasDependentBases(const CXXRecordDecl *Class) {
5701 return !Class->forallBases(collect, this);
5704 /// Returns true if the base is dependent or is one of the
5705 /// accumulated base classes.
5706 static bool doesNotContain(const CXXRecordDecl *Base, void *OpaqueData) {
5707 UserData *Data = reinterpret_cast<UserData*>(OpaqueData);
5708 return !Data->Bases.count(Base);
5711 bool mightShareBases(const CXXRecordDecl *Class) {
5712 return Bases.count(Class) || !Class->forallBases(doesNotContain, this);
5718 // Returns false if we find a dependent base.
5719 if (Data.hasDependentBases(cast<CXXRecordDecl>(CurContext)))
5722 // Returns false if the class has a dependent base or if it or one
5723 // of its bases is present in the base set of the current context.
5724 if (Data.mightShareBases(cast<CXXRecordDecl>(NamedContext)))
5727 Diag(SS.getRange().getBegin(),
5728 diag::err_using_decl_nested_name_specifier_is_not_base_class)
5729 << (NestedNameSpecifier*) SS.getScopeRep()
5730 << cast<CXXRecordDecl>(CurContext)
5736 Decl *Sema::ActOnAliasDeclaration(Scope *S,
5738 MultiTemplateParamsArg TemplateParamLists,
5739 SourceLocation UsingLoc,
5740 UnqualifiedId &Name,
5742 // Skip up to the relevant declaration scope.
5743 while (S->getFlags() & Scope::TemplateParamScope)
5745 assert((S->getFlags() & Scope::DeclScope) &&
5746 "got alias-declaration outside of declaration scope");
5748 if (Type.isInvalid())
5751 bool Invalid = false;
5752 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
5753 TypeSourceInfo *TInfo = 0;
5754 GetTypeFromParser(Type.get(), &TInfo);
5756 if (DiagnoseClassNameShadow(CurContext, NameInfo))
5759 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
5760 UPPC_DeclarationType)) {
5762 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
5763 TInfo->getTypeLoc().getBeginLoc());
5766 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, ForRedeclaration);
5767 LookupName(Previous, S);
5769 // Warn about shadowing the name of a template parameter.
5770 if (Previous.isSingleResult() &&
5771 Previous.getFoundDecl()->isTemplateParameter()) {
5772 if (DiagnoseTemplateParameterShadow(Name.StartLocation,
5773 Previous.getFoundDecl()))
5778 assert(Name.Kind == UnqualifiedId::IK_Identifier &&
5779 "name in alias declaration must be an identifier");
5780 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
5782 Name.Identifier, TInfo);
5784 NewTD->setAccess(AS);
5787 NewTD->setInvalidDecl();
5789 CheckTypedefForVariablyModifiedType(S, NewTD);
5790 Invalid |= NewTD->isInvalidDecl();
5792 bool Redeclaration = false;
5795 if (TemplateParamLists.size()) {
5796 TypeAliasTemplateDecl *OldDecl = 0;
5797 TemplateParameterList *OldTemplateParams = 0;
5799 if (TemplateParamLists.size() != 1) {
5800 Diag(UsingLoc, diag::err_alias_template_extra_headers)
5801 << SourceRange(TemplateParamLists.get()[1]->getTemplateLoc(),
5802 TemplateParamLists.get()[TemplateParamLists.size()-1]->getRAngleLoc());
5804 TemplateParameterList *TemplateParams = TemplateParamLists.get()[0];
5806 // Only consider previous declarations in the same scope.
5807 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
5808 /*ExplicitInstantiationOrSpecialization*/false);
5809 if (!Previous.empty()) {
5810 Redeclaration = true;
5812 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
5813 if (!OldDecl && !Invalid) {
5814 Diag(UsingLoc, diag::err_redefinition_different_kind)
5817 NamedDecl *OldD = Previous.getRepresentativeDecl();
5818 if (OldD->getLocation().isValid())
5819 Diag(OldD->getLocation(), diag::note_previous_definition);
5824 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
5825 if (TemplateParameterListsAreEqual(TemplateParams,
5826 OldDecl->getTemplateParameters(),
5829 OldTemplateParams = OldDecl->getTemplateParameters();
5833 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
5835 !Context.hasSameType(OldTD->getUnderlyingType(),
5836 NewTD->getUnderlyingType())) {
5837 // FIXME: The C++0x standard does not clearly say this is ill-formed,
5838 // but we can't reasonably accept it.
5839 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
5840 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
5841 if (OldTD->getLocation().isValid())
5842 Diag(OldTD->getLocation(), diag::note_previous_definition);
5848 // Merge any previous default template arguments into our parameters,
5849 // and check the parameter list.
5850 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
5851 TPC_TypeAliasTemplate))
5854 TypeAliasTemplateDecl *NewDecl =
5855 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
5856 Name.Identifier, TemplateParams,
5859 NewDecl->setAccess(AS);
5862 NewDecl->setInvalidDecl();
5864 NewDecl->setPreviousDeclaration(OldDecl);
5868 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
5873 PushOnScopeChains(NewND, S);
5878 Decl *Sema::ActOnNamespaceAliasDef(Scope *S,
5879 SourceLocation NamespaceLoc,
5880 SourceLocation AliasLoc,
5881 IdentifierInfo *Alias,
5883 SourceLocation IdentLoc,
5884 IdentifierInfo *Ident) {
5886 // Lookup the namespace name.
5887 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
5888 LookupParsedName(R, S, &SS);
5890 // Check if we have a previous declaration with the same name.
5892 = LookupSingleName(S, Alias, AliasLoc, LookupOrdinaryName,
5894 if (PrevDecl && !isDeclInScope(PrevDecl, CurContext, S))
5898 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
5899 // We already have an alias with the same name that points to the same
5900 // namespace, so don't create a new one.
5901 // FIXME: At some point, we'll want to create the (redundant)
5902 // declaration to maintain better source information.
5903 if (!R.isAmbiguous() && !R.empty() &&
5904 AD->getNamespace()->Equals(getNamespaceDecl(R.getFoundDecl())))
5908 unsigned DiagID = isa<NamespaceDecl>(PrevDecl) ? diag::err_redefinition :
5909 diag::err_redefinition_different_kind;
5910 Diag(AliasLoc, DiagID) << Alias;
5911 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
5915 if (R.isAmbiguous())
5919 if (DeclarationName Corrected = CorrectTypo(R, S, &SS, 0, false,
5920 CTC_NoKeywords, 0)) {
5921 if (R.getAsSingle<NamespaceDecl>() ||
5922 R.getAsSingle<NamespaceAliasDecl>()) {
5923 if (DeclContext *DC = computeDeclContext(SS, false))
5924 Diag(IdentLoc, diag::err_using_directive_member_suggest)
5925 << Ident << DC << Corrected << SS.getRange()
5926 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5928 Diag(IdentLoc, diag::err_using_directive_suggest)
5929 << Ident << Corrected
5930 << FixItHint::CreateReplacement(IdentLoc, Corrected.getAsString());
5932 Diag(R.getFoundDecl()->getLocation(), diag::note_namespace_defined_here)
5935 Ident = Corrected.getAsIdentifierInfo();
5938 R.setLookupName(Ident);
5943 Diag(NamespaceLoc, diag::err_expected_namespace_name) << SS.getRange();
5948 NamespaceAliasDecl *AliasDecl =
5949 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
5950 Alias, SS.getWithLocInContext(Context),
5951 IdentLoc, R.getFoundDecl());
5953 PushOnScopeChains(AliasDecl, S);
5958 /// \brief Scoped object used to handle the state changes required in Sema
5959 /// to implicitly define the body of a C++ member function;
5960 class ImplicitlyDefinedFunctionScope {
5962 Sema::ContextRAII SavedContext;
5965 ImplicitlyDefinedFunctionScope(Sema &S, CXXMethodDecl *Method)
5966 : S(S), SavedContext(S, Method)
5968 S.PushFunctionScope();
5969 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
5972 ~ImplicitlyDefinedFunctionScope() {
5973 S.PopExpressionEvaluationContext();
5974 S.PopFunctionOrBlockScope();
5979 Sema::ImplicitExceptionSpecification
5980 Sema::ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl) {
5981 // C++ [except.spec]p14:
5982 // An implicitly declared special member function (Clause 12) shall have an
5983 // exception-specification. [...]
5984 ImplicitExceptionSpecification ExceptSpec(Context);
5986 // Direct base-class constructors.
5987 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
5988 BEnd = ClassDecl->bases_end();
5990 if (B->isVirtual()) // Handled below.
5993 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
5994 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
5995 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
5996 // If this is a deleted function, add it anyway. This might be conformant
5997 // with the standard. This might not. I'm not sure. It might not matter.
5999 ExceptSpec.CalledDecl(Constructor);
6003 // Virtual base-class constructors.
6004 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6005 BEnd = ClassDecl->vbases_end();
6007 if (const RecordType *BaseType = B->getType()->getAs<RecordType>()) {
6008 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6009 CXXConstructorDecl *Constructor = LookupDefaultConstructor(BaseClassDecl);
6010 // If this is a deleted function, add it anyway. This might be conformant
6011 // with the standard. This might not. I'm not sure. It might not matter.
6013 ExceptSpec.CalledDecl(Constructor);
6017 // Field constructors.
6018 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6019 FEnd = ClassDecl->field_end();
6021 if (F->hasInClassInitializer()) {
6022 if (Expr *E = F->getInClassInitializer())
6023 ExceptSpec.CalledExpr(E);
6024 else if (!F->isInvalidDecl())
6025 ExceptSpec.SetDelayed();
6026 } else if (const RecordType *RecordTy
6027 = Context.getBaseElementType(F->getType())->getAs<RecordType>()) {
6028 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6029 CXXConstructorDecl *Constructor = LookupDefaultConstructor(FieldRecDecl);
6030 // If this is a deleted function, add it anyway. This might be conformant
6031 // with the standard. This might not. I'm not sure. It might not matter.
6032 // In particular, the problem is that this function never gets called. It
6033 // might just be ill-formed because this function attempts to refer to
6034 // a deleted function here.
6036 ExceptSpec.CalledDecl(Constructor);
6043 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
6044 CXXRecordDecl *ClassDecl) {
6045 // C++ [class.ctor]p5:
6046 // A default constructor for a class X is a constructor of class X
6047 // that can be called without an argument. If there is no
6048 // user-declared constructor for class X, a default constructor is
6049 // implicitly declared. An implicitly-declared default constructor
6050 // is an inline public member of its class.
6051 assert(!ClassDecl->hasUserDeclaredConstructor() &&
6052 "Should not build implicit default constructor!");
6054 ImplicitExceptionSpecification Spec =
6055 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6056 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6058 // Create the actual constructor declaration.
6059 CanQualType ClassType
6060 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6061 SourceLocation ClassLoc = ClassDecl->getLocation();
6062 DeclarationName Name
6063 = Context.DeclarationNames.getCXXConstructorName(ClassType);
6064 DeclarationNameInfo NameInfo(Name, ClassLoc);
6065 CXXConstructorDecl *DefaultCon
6066 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6067 Context.getFunctionType(Context.VoidTy,
6070 /*isExplicit=*/false,
6072 /*isImplicitlyDeclared=*/true);
6073 DefaultCon->setAccess(AS_public);
6074 DefaultCon->setDefaulted();
6075 DefaultCon->setImplicit();
6076 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
6078 // Note that we have declared this constructor.
6079 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
6081 if (Scope *S = getScopeForContext(ClassDecl))
6082 PushOnScopeChains(DefaultCon, S, false);
6083 ClassDecl->addDecl(DefaultCon);
6085 if (ShouldDeleteDefaultConstructor(DefaultCon))
6086 DefaultCon->setDeletedAsWritten();
6091 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6092 CXXConstructorDecl *Constructor) {
6093 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
6094 !Constructor->doesThisDeclarationHaveABody() &&
6095 !Constructor->isDeleted()) &&
6096 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
6098 CXXRecordDecl *ClassDecl = Constructor->getParent();
6099 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
6101 ImplicitlyDefinedFunctionScope Scope(*this, Constructor);
6102 DiagnosticErrorTrap Trap(Diags);
6103 if (SetCtorInitializers(Constructor, 0, 0, /*AnyErrors=*/false) ||
6104 Trap.hasErrorOccurred()) {
6105 Diag(CurrentLocation, diag::note_member_synthesized_at)
6106 << CXXDefaultConstructor << Context.getTagDeclType(ClassDecl);
6107 Constructor->setInvalidDecl();
6111 SourceLocation Loc = Constructor->getLocation();
6112 Constructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6114 Constructor->setUsed();
6115 MarkVTableUsed(CurrentLocation, ClassDecl);
6117 if (ASTMutationListener *L = getASTMutationListener()) {
6118 L->CompletedImplicitDefinition(Constructor);
6122 /// Get any existing defaulted default constructor for the given class. Do not
6123 /// implicitly define one if it does not exist.
6124 static CXXConstructorDecl *getDefaultedDefaultConstructorUnsafe(Sema &Self,
6126 ASTContext &Context = Self.Context;
6127 QualType ClassType = Context.getTypeDeclType(D);
6128 DeclarationName ConstructorName
6129 = Context.DeclarationNames.getCXXConstructorName(
6130 Context.getCanonicalType(ClassType.getUnqualifiedType()));
6132 DeclContext::lookup_const_iterator Con, ConEnd;
6133 for (llvm::tie(Con, ConEnd) = D->lookup(ConstructorName);
6134 Con != ConEnd; ++Con) {
6135 // A function template cannot be defaulted.
6136 if (isa<FunctionTemplateDecl>(*Con))
6139 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
6140 if (Constructor->isDefaultConstructor())
6141 return Constructor->isDefaulted() ? Constructor : 0;
6146 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
6148 AdjustDeclIfTemplate(D);
6150 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D);
6151 CXXConstructorDecl *CtorDecl
6152 = getDefaultedDefaultConstructorUnsafe(*this, ClassDecl);
6154 if (!CtorDecl) return;
6156 // Compute the exception specification for the default constructor.
6157 const FunctionProtoType *CtorTy =
6158 CtorDecl->getType()->castAs<FunctionProtoType>();
6159 if (CtorTy->getExceptionSpecType() == EST_Delayed) {
6160 ImplicitExceptionSpecification Spec =
6161 ComputeDefaultedDefaultCtorExceptionSpec(ClassDecl);
6162 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6163 assert(EPI.ExceptionSpecType != EST_Delayed);
6165 CtorDecl->setType(Context.getFunctionType(Context.VoidTy, 0, 0, EPI));
6168 // If the default constructor is explicitly defaulted, checking the exception
6169 // specification is deferred until now.
6170 if (!CtorDecl->isInvalidDecl() && CtorDecl->isExplicitlyDefaulted() &&
6171 !ClassDecl->isDependentType())
6172 CheckExplicitlyDefaultedDefaultConstructor(CtorDecl);
6175 void Sema::DeclareInheritedConstructors(CXXRecordDecl *ClassDecl) {
6176 // We start with an initial pass over the base classes to collect those that
6177 // inherit constructors from. If there are none, we can forgo all further
6179 typedef llvm::SmallVector<const RecordType *, 4> BasesVector;
6180 BasesVector BasesToInheritFrom;
6181 for (CXXRecordDecl::base_class_iterator BaseIt = ClassDecl->bases_begin(),
6182 BaseE = ClassDecl->bases_end();
6183 BaseIt != BaseE; ++BaseIt) {
6184 if (BaseIt->getInheritConstructors()) {
6185 QualType Base = BaseIt->getType();
6186 if (Base->isDependentType()) {
6187 // If we inherit constructors from anything that is dependent, just
6188 // abort processing altogether. We'll get another chance for the
6192 BasesToInheritFrom.push_back(Base->castAs<RecordType>());
6195 if (BasesToInheritFrom.empty())
6198 // Now collect the constructors that we already have in the current class.
6199 // Those take precedence over inherited constructors.
6200 // C++0x [class.inhctor]p3: [...] a constructor is implicitly declared [...]
6201 // unless there is a user-declared constructor with the same signature in
6202 // the class where the using-declaration appears.
6203 llvm::SmallSet<const Type *, 8> ExistingConstructors;
6204 for (CXXRecordDecl::ctor_iterator CtorIt = ClassDecl->ctor_begin(),
6205 CtorE = ClassDecl->ctor_end();
6206 CtorIt != CtorE; ++CtorIt) {
6207 ExistingConstructors.insert(
6208 Context.getCanonicalType(CtorIt->getType()).getTypePtr());
6211 Scope *S = getScopeForContext(ClassDecl);
6212 DeclarationName CreatedCtorName =
6213 Context.DeclarationNames.getCXXConstructorName(
6214 ClassDecl->getTypeForDecl()->getCanonicalTypeUnqualified());
6216 // Now comes the true work.
6217 // First, we keep a map from constructor types to the base that introduced
6218 // them. Needed for finding conflicting constructors. We also keep the
6219 // actually inserted declarations in there, for pretty diagnostics.
6220 typedef std::pair<CanQualType, CXXConstructorDecl *> ConstructorInfo;
6221 typedef llvm::DenseMap<const Type *, ConstructorInfo> ConstructorToSourceMap;
6222 ConstructorToSourceMap InheritedConstructors;
6223 for (BasesVector::iterator BaseIt = BasesToInheritFrom.begin(),
6224 BaseE = BasesToInheritFrom.end();
6225 BaseIt != BaseE; ++BaseIt) {
6226 const RecordType *Base = *BaseIt;
6227 CanQualType CanonicalBase = Base->getCanonicalTypeUnqualified();
6228 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(Base->getDecl());
6229 for (CXXRecordDecl::ctor_iterator CtorIt = BaseDecl->ctor_begin(),
6230 CtorE = BaseDecl->ctor_end();
6231 CtorIt != CtorE; ++CtorIt) {
6232 // Find the using declaration for inheriting this base's constructors.
6233 DeclarationName Name =
6234 Context.DeclarationNames.getCXXConstructorName(CanonicalBase);
6235 UsingDecl *UD = dyn_cast_or_null<UsingDecl>(
6236 LookupSingleName(S, Name,SourceLocation(), LookupUsingDeclName));
6237 SourceLocation UsingLoc = UD ? UD->getLocation() :
6238 ClassDecl->getLocation();
6240 // C++0x [class.inhctor]p1: The candidate set of inherited constructors
6241 // from the class X named in the using-declaration consists of actual
6242 // constructors and notional constructors that result from the
6243 // transformation of defaulted parameters as follows:
6244 // - all non-template default constructors of X, and
6245 // - for each non-template constructor of X that has at least one
6246 // parameter with a default argument, the set of constructors that
6247 // results from omitting any ellipsis parameter specification and
6248 // successively omitting parameters with a default argument from the
6249 // end of the parameter-type-list.
6250 CXXConstructorDecl *BaseCtor = *CtorIt;
6251 bool CanBeCopyOrMove = BaseCtor->isCopyOrMoveConstructor();
6252 const FunctionProtoType *BaseCtorType =
6253 BaseCtor->getType()->getAs<FunctionProtoType>();
6255 for (unsigned params = BaseCtor->getMinRequiredArguments(),
6256 maxParams = BaseCtor->getNumParams();
6257 params <= maxParams; ++params) {
6258 // Skip default constructors. They're never inherited.
6261 // Skip copy and move constructors for the same reason.
6262 if (CanBeCopyOrMove && params == 1)
6265 // Build up a function type for this particular constructor.
6266 // FIXME: The working paper does not consider that the exception spec
6267 // for the inheriting constructor might be larger than that of the
6268 // source. This code doesn't yet, either. When it does, this code will
6269 // need to be delayed until after exception specifications and in-class
6270 // member initializers are attached.
6271 const Type *NewCtorType;
6272 if (params == maxParams)
6273 NewCtorType = BaseCtorType;
6275 llvm::SmallVector<QualType, 16> Args;
6276 for (unsigned i = 0; i < params; ++i) {
6277 Args.push_back(BaseCtorType->getArgType(i));
6279 FunctionProtoType::ExtProtoInfo ExtInfo =
6280 BaseCtorType->getExtProtoInfo();
6281 ExtInfo.Variadic = false;
6282 NewCtorType = Context.getFunctionType(BaseCtorType->getResultType(),
6283 Args.data(), params, ExtInfo)
6286 const Type *CanonicalNewCtorType =
6287 Context.getCanonicalType(NewCtorType);
6289 // Now that we have the type, first check if the class already has a
6290 // constructor with this signature.
6291 if (ExistingConstructors.count(CanonicalNewCtorType))
6294 // Then we check if we have already declared an inherited constructor
6295 // with this signature.
6296 std::pair<ConstructorToSourceMap::iterator, bool> result =
6297 InheritedConstructors.insert(std::make_pair(
6298 CanonicalNewCtorType,
6299 std::make_pair(CanonicalBase, (CXXConstructorDecl*)0)));
6300 if (!result.second) {
6301 // Already in the map. If it came from a different class, that's an
6302 // error. Not if it's from the same.
6303 CanQualType PreviousBase = result.first->second.first;
6304 if (CanonicalBase != PreviousBase) {
6305 const CXXConstructorDecl *PrevCtor = result.first->second.second;
6306 const CXXConstructorDecl *PrevBaseCtor =
6307 PrevCtor->getInheritedConstructor();
6308 assert(PrevBaseCtor && "Conflicting constructor was not inherited");
6310 Diag(UsingLoc, diag::err_using_decl_constructor_conflict);
6311 Diag(BaseCtor->getLocation(),
6312 diag::note_using_decl_constructor_conflict_current_ctor);
6313 Diag(PrevBaseCtor->getLocation(),
6314 diag::note_using_decl_constructor_conflict_previous_ctor);
6315 Diag(PrevCtor->getLocation(),
6316 diag::note_using_decl_constructor_conflict_previous_using);
6321 // OK, we're there, now add the constructor.
6322 // C++0x [class.inhctor]p8: [...] that would be performed by a
6323 // user-writtern inline constructor [...]
6324 DeclarationNameInfo DNI(CreatedCtorName, UsingLoc);
6325 CXXConstructorDecl *NewCtor = CXXConstructorDecl::Create(
6326 Context, ClassDecl, UsingLoc, DNI, QualType(NewCtorType, 0),
6327 /*TInfo=*/0, BaseCtor->isExplicit(), /*Inline=*/true,
6328 /*ImplicitlyDeclared=*/true);
6329 NewCtor->setAccess(BaseCtor->getAccess());
6331 // Build up the parameter decls and add them.
6332 llvm::SmallVector<ParmVarDecl *, 16> ParamDecls;
6333 for (unsigned i = 0; i < params; ++i) {
6334 ParamDecls.push_back(ParmVarDecl::Create(Context, NewCtor,
6336 /*IdentifierInfo=*/0,
6337 BaseCtorType->getArgType(i),
6338 /*TInfo=*/0, SC_None,
6339 SC_None, /*DefaultArg=*/0));
6341 NewCtor->setParams(ParamDecls.data(), ParamDecls.size());
6342 NewCtor->setInheritedConstructor(BaseCtor);
6344 PushOnScopeChains(NewCtor, S, false);
6345 ClassDecl->addDecl(NewCtor);
6346 result.first->second.second = NewCtor;
6352 Sema::ImplicitExceptionSpecification
6353 Sema::ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl) {
6354 // C++ [except.spec]p14:
6355 // An implicitly declared special member function (Clause 12) shall have
6356 // an exception-specification.
6357 ImplicitExceptionSpecification ExceptSpec(Context);
6359 // Direct base-class destructors.
6360 for (CXXRecordDecl::base_class_iterator B = ClassDecl->bases_begin(),
6361 BEnd = ClassDecl->bases_end();
6363 if (B->isVirtual()) // Handled below.
6366 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6367 ExceptSpec.CalledDecl(
6368 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6371 // Virtual base-class destructors.
6372 for (CXXRecordDecl::base_class_iterator B = ClassDecl->vbases_begin(),
6373 BEnd = ClassDecl->vbases_end();
6375 if (const RecordType *BaseType = B->getType()->getAs<RecordType>())
6376 ExceptSpec.CalledDecl(
6377 LookupDestructor(cast<CXXRecordDecl>(BaseType->getDecl())));
6380 // Field destructors.
6381 for (RecordDecl::field_iterator F = ClassDecl->field_begin(),
6382 FEnd = ClassDecl->field_end();
6384 if (const RecordType *RecordTy
6385 = Context.getBaseElementType(F->getType())->getAs<RecordType>())
6386 ExceptSpec.CalledDecl(
6387 LookupDestructor(cast<CXXRecordDecl>(RecordTy->getDecl())));
6393 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
6394 // C++ [class.dtor]p2:
6395 // If a class has no user-declared destructor, a destructor is
6396 // declared implicitly. An implicitly-declared destructor is an
6397 // inline public member of its class.
6399 ImplicitExceptionSpecification Spec =
6400 ComputeDefaultedDtorExceptionSpec(ClassDecl);
6401 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6403 // Create the actual destructor declaration.
6404 QualType Ty = Context.getFunctionType(Context.VoidTy, 0, 0, EPI);
6406 CanQualType ClassType
6407 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
6408 SourceLocation ClassLoc = ClassDecl->getLocation();
6409 DeclarationName Name
6410 = Context.DeclarationNames.getCXXDestructorName(ClassType);
6411 DeclarationNameInfo NameInfo(Name, ClassLoc);
6412 CXXDestructorDecl *Destructor
6413 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, Ty, 0,
6415 /*isImplicitlyDeclared=*/true);
6416 Destructor->setAccess(AS_public);
6417 Destructor->setDefaulted();
6418 Destructor->setImplicit();
6419 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
6421 // Note that we have declared this destructor.
6422 ++ASTContext::NumImplicitDestructorsDeclared;
6424 // Introduce this destructor into its scope.
6425 if (Scope *S = getScopeForContext(ClassDecl))
6426 PushOnScopeChains(Destructor, S, false);
6427 ClassDecl->addDecl(Destructor);
6429 // This could be uniqued if it ever proves significant.
6430 Destructor->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(Ty));
6432 if (ShouldDeleteDestructor(Destructor))
6433 Destructor->setDeletedAsWritten();
6435 AddOverriddenMethods(ClassDecl, Destructor);
6440 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
6441 CXXDestructorDecl *Destructor) {
6442 assert((Destructor->isDefaulted() &&
6443 !Destructor->doesThisDeclarationHaveABody()) &&
6444 "DefineImplicitDestructor - call it for implicit default dtor");
6445 CXXRecordDecl *ClassDecl = Destructor->getParent();
6446 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
6448 if (Destructor->isInvalidDecl())
6451 ImplicitlyDefinedFunctionScope Scope(*this, Destructor);
6453 DiagnosticErrorTrap Trap(Diags);
6454 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
6455 Destructor->getParent());
6457 if (CheckDestructor(Destructor) || Trap.hasErrorOccurred()) {
6458 Diag(CurrentLocation, diag::note_member_synthesized_at)
6459 << CXXDestructor << Context.getTagDeclType(ClassDecl);
6461 Destructor->setInvalidDecl();
6465 SourceLocation Loc = Destructor->getLocation();
6466 Destructor->setBody(new (Context) CompoundStmt(Context, 0, 0, Loc, Loc));
6468 Destructor->setUsed();
6469 MarkVTableUsed(CurrentLocation, ClassDecl);
6471 if (ASTMutationListener *L = getASTMutationListener()) {
6472 L->CompletedImplicitDefinition(Destructor);
6476 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *classDecl,
6477 CXXDestructorDecl *destructor) {
6478 // C++11 [class.dtor]p3:
6479 // A declaration of a destructor that does not have an exception-
6480 // specification is implicitly considered to have the same exception-
6481 // specification as an implicit declaration.
6482 const FunctionProtoType *dtorType = destructor->getType()->
6483 getAs<FunctionProtoType>();
6484 if (dtorType->hasExceptionSpec())
6487 ImplicitExceptionSpecification exceptSpec =
6488 ComputeDefaultedDtorExceptionSpec(classDecl);
6490 // Replace the destructor's type.
6491 FunctionProtoType::ExtProtoInfo epi;
6492 epi.ExceptionSpecType = exceptSpec.getExceptionSpecType();
6493 epi.NumExceptions = exceptSpec.size();
6494 epi.Exceptions = exceptSpec.data();
6495 QualType ty = Context.getFunctionType(Context.VoidTy, 0, 0, epi);
6497 destructor->setType(ty);
6499 // FIXME: If the destructor has a body that could throw, and the newly created
6500 // spec doesn't allow exceptions, we should emit a warning, because this
6501 // change in behavior can break conforming C++03 programs at runtime.
6502 // However, we don't have a body yet, so it needs to be done somewhere else.
6505 /// \brief Builds a statement that copies the given entity from \p From to
6508 /// This routine is used to copy the members of a class with an
6509 /// implicitly-declared copy assignment operator. When the entities being
6510 /// copied are arrays, this routine builds for loops to copy them.
6512 /// \param S The Sema object used for type-checking.
6514 /// \param Loc The location where the implicit copy is being generated.
6516 /// \param T The type of the expressions being copied. Both expressions must
6519 /// \param To The expression we are copying to.
6521 /// \param From The expression we are copying from.
6523 /// \param CopyingBaseSubobject Whether we're copying a base subobject.
6524 /// Otherwise, it's a non-static member subobject.
6526 /// \param Depth Internal parameter recording the depth of the recursion.
6528 /// \returns A statement or a loop that copies the expressions.
6530 BuildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
6531 Expr *To, Expr *From,
6532 bool CopyingBaseSubobject, unsigned Depth = 0) {
6533 // C++0x [class.copy]p30:
6534 // Each subobject is assigned in the manner appropriate to its type:
6536 // - if the subobject is of class type, the copy assignment operator
6537 // for the class is used (as if by explicit qualification; that is,
6538 // ignoring any possible virtual overriding functions in more derived
6540 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
6541 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6543 // Look for operator=.
6544 DeclarationName Name
6545 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6546 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
6547 S.LookupQualifiedName(OpLookup, ClassDecl, false);
6549 // Filter out any result that isn't a copy-assignment operator.
6550 LookupResult::Filter F = OpLookup.makeFilter();
6551 while (F.hasNext()) {
6552 NamedDecl *D = F.next();
6553 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
6554 if (Method->isCopyAssignmentOperator())
6561 // Suppress the protected check (C++ [class.protected]) for each of the
6562 // assignment operators we found. This strange dance is required when
6563 // we're assigning via a base classes's copy-assignment operator. To
6564 // ensure that we're getting the right base class subobject (without
6565 // ambiguities), we need to cast "this" to that subobject type; to
6566 // ensure that we don't go through the virtual call mechanism, we need
6567 // to qualify the operator= name with the base class (see below). However,
6568 // this means that if the base class has a protected copy assignment
6569 // operator, the protected member access check will fail. So, we
6570 // rewrite "protected" access to "public" access in this case, since we
6571 // know by construction that we're calling from a derived class.
6572 if (CopyingBaseSubobject) {
6573 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
6575 if (L.getAccess() == AS_protected)
6576 L.setAccess(AS_public);
6580 // Create the nested-name-specifier that will be used to qualify the
6581 // reference to operator=; this is required to suppress the virtual
6584 SS.MakeTrivial(S.Context,
6585 NestedNameSpecifier::Create(S.Context, 0, false,
6589 // Create the reference to operator=.
6590 ExprResult OpEqualRef
6591 = S.BuildMemberReferenceExpr(To, T, Loc, /*isArrow=*/false, SS,
6592 /*FirstQualifierInScope=*/0, OpLookup,
6594 /*SuppressQualifierCheck=*/true);
6595 if (OpEqualRef.isInvalid())
6598 // Build the call to the assignment operator.
6600 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/0,
6601 OpEqualRef.takeAs<Expr>(),
6602 Loc, &From, 1, Loc);
6603 if (Call.isInvalid())
6606 return S.Owned(Call.takeAs<Stmt>());
6609 // - if the subobject is of scalar type, the built-in assignment
6610 // operator is used.
6611 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
6613 ExprResult Assignment = S.CreateBuiltinBinOp(Loc, BO_Assign, To, From);
6614 if (Assignment.isInvalid())
6617 return S.Owned(Assignment.takeAs<Stmt>());
6620 // - if the subobject is an array, each element is assigned, in the
6621 // manner appropriate to the element type;
6623 // Construct a loop over the array bounds, e.g.,
6625 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
6627 // that will copy each of the array elements.
6628 QualType SizeType = S.Context.getSizeType();
6630 // Create the iteration variable.
6631 IdentifierInfo *IterationVarName = 0;
6633 llvm::SmallString<8> Str;
6634 llvm::raw_svector_ostream OS(Str);
6635 OS << "__i" << Depth;
6636 IterationVarName = &S.Context.Idents.get(OS.str());
6638 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
6639 IterationVarName, SizeType,
6640 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
6643 // Initialize the iteration variable to zero.
6644 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
6645 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
6647 // Create a reference to the iteration variable; we'll use this several
6648 // times throughout.
6649 Expr *IterationVarRef
6650 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_RValue, Loc).take();
6651 assert(IterationVarRef && "Reference to invented variable cannot fail!");
6653 // Create the DeclStmt that holds the iteration variable.
6654 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
6656 // Create the comparison against the array bound.
6658 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
6660 = new (S.Context) BinaryOperator(IterationVarRef,
6661 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
6662 BO_NE, S.Context.BoolTy,
6663 VK_RValue, OK_Ordinary, Loc);
6665 // Create the pre-increment of the iteration variable.
6667 = new (S.Context) UnaryOperator(IterationVarRef, UO_PreInc, SizeType,
6668 VK_LValue, OK_Ordinary, Loc);
6670 // Subscript the "from" and "to" expressions with the iteration variable.
6671 From = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(From, Loc,
6672 IterationVarRef, Loc));
6673 To = AssertSuccess(S.CreateBuiltinArraySubscriptExpr(To, Loc,
6674 IterationVarRef, Loc));
6676 // Build the copy for an individual element of the array.
6677 StmtResult Copy = BuildSingleCopyAssign(S, Loc, ArrayTy->getElementType(),
6678 To, From, CopyingBaseSubobject,
6680 if (Copy.isInvalid())
6683 // Construct the loop that copies all elements of this array.
6684 return S.ActOnForStmt(Loc, Loc, InitStmt,
6685 S.MakeFullExpr(Comparison),
6686 0, S.MakeFullExpr(Increment),
6690 /// \brief Determine whether the given class has a copy assignment operator
6691 /// that accepts a const-qualified argument.
6692 static bool hasConstCopyAssignment(Sema &S, const CXXRecordDecl *CClass) {
6693 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(CClass);
6695 if (!Class->hasDeclaredCopyAssignment())
6696 S.DeclareImplicitCopyAssignment(Class);
6698 QualType ClassType = S.Context.getCanonicalType(S.Context.getTypeDeclType(Class));
6699 DeclarationName OpName
6700 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6702 DeclContext::lookup_const_iterator Op, OpEnd;
6703 for (llvm::tie(Op, OpEnd) = Class->lookup(OpName); Op != OpEnd; ++Op) {
6704 // C++ [class.copy]p9:
6705 // A user-declared copy assignment operator is a non-static non-template
6706 // member function of class X with exactly one parameter of type X, X&,
6707 // const X&, volatile X& or const volatile X&.
6708 const CXXMethodDecl* Method = dyn_cast<CXXMethodDecl>(*Op);
6712 if (Method->isStatic())
6714 if (Method->getPrimaryTemplate())
6716 const FunctionProtoType *FnType =
6717 Method->getType()->getAs<FunctionProtoType>();
6718 assert(FnType && "Overloaded operator has no prototype.");
6719 // Don't assert on this; an invalid decl might have been left in the AST.
6720 if (FnType->getNumArgs() != 1 || FnType->isVariadic())
6722 bool AcceptsConst = true;
6723 QualType ArgType = FnType->getArgType(0);
6724 if (const LValueReferenceType *Ref = ArgType->getAs<LValueReferenceType>()){
6725 ArgType = Ref->getPointeeType();
6726 // Is it a non-const lvalue reference?
6727 if (!ArgType.isConstQualified())
6728 AcceptsConst = false;
6730 if (!S.Context.hasSameUnqualifiedType(ArgType, ClassType))
6733 // We have a single argument of type cv X or cv X&, i.e. we've found the
6734 // copy assignment operator. Return whether it accepts const arguments.
6735 return AcceptsConst;
6737 assert(Class->isInvalidDecl() &&
6738 "No copy assignment operator declared in valid code.");
6742 std::pair<Sema::ImplicitExceptionSpecification, bool>
6743 Sema::ComputeDefaultedCopyAssignmentExceptionSpecAndConst(
6744 CXXRecordDecl *ClassDecl) {
6745 // C++ [class.copy]p10:
6746 // If the class definition does not explicitly declare a copy
6747 // assignment operator, one is declared implicitly.
6748 // The implicitly-defined copy assignment operator for a class X
6749 // will have the form
6751 // X& X::operator=(const X&)
6754 bool HasConstCopyAssignment = true;
6756 // -- each direct base class B of X has a copy assignment operator
6757 // whose parameter is of type const B&, const volatile B& or B,
6759 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6760 BaseEnd = ClassDecl->bases_end();
6761 HasConstCopyAssignment && Base != BaseEnd; ++Base) {
6762 assert(!Base->getType()->isDependentType() &&
6763 "Cannot generate implicit members for class with dependent bases.");
6764 const CXXRecordDecl *BaseClassDecl
6765 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6766 HasConstCopyAssignment = hasConstCopyAssignment(*this, BaseClassDecl);
6769 // -- for all the nonstatic data members of X that are of a class
6770 // type M (or array thereof), each such class type has a copy
6771 // assignment operator whose parameter is of type const M&,
6772 // const volatile M& or M.
6773 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6774 FieldEnd = ClassDecl->field_end();
6775 HasConstCopyAssignment && Field != FieldEnd;
6777 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6778 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6779 const CXXRecordDecl *FieldClassDecl
6780 = cast<CXXRecordDecl>(FieldClassType->getDecl());
6781 HasConstCopyAssignment = hasConstCopyAssignment(*this, FieldClassDecl);
6785 // Otherwise, the implicitly declared copy assignment operator will
6788 // X& X::operator=(X&)
6790 // C++ [except.spec]p14:
6791 // An implicitly declared special member function (Clause 12) shall have an
6792 // exception-specification. [...]
6793 ImplicitExceptionSpecification ExceptSpec(Context);
6794 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6795 BaseEnd = ClassDecl->bases_end();
6796 Base != BaseEnd; ++Base) {
6797 CXXRecordDecl *BaseClassDecl
6798 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
6800 if (!BaseClassDecl->hasDeclaredCopyAssignment())
6801 DeclareImplicitCopyAssignment(BaseClassDecl);
6803 if (CXXMethodDecl *CopyAssign
6804 = BaseClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6805 ExceptSpec.CalledDecl(CopyAssign);
6807 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6808 FieldEnd = ClassDecl->field_end();
6811 QualType FieldType = Context.getBaseElementType((*Field)->getType());
6812 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) {
6813 CXXRecordDecl *FieldClassDecl
6814 = cast<CXXRecordDecl>(FieldClassType->getDecl());
6816 if (!FieldClassDecl->hasDeclaredCopyAssignment())
6817 DeclareImplicitCopyAssignment(FieldClassDecl);
6819 if (CXXMethodDecl *CopyAssign
6820 = FieldClassDecl->getCopyAssignmentOperator(HasConstCopyAssignment))
6821 ExceptSpec.CalledDecl(CopyAssign);
6825 return std::make_pair(ExceptSpec, HasConstCopyAssignment);
6828 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
6829 // Note: The following rules are largely analoguous to the copy
6830 // constructor rules. Note that virtual bases are not taken into account
6831 // for determining the argument type of the operator. Note also that
6832 // operators taking an object instead of a reference are allowed.
6834 ImplicitExceptionSpecification Spec(Context);
6836 llvm::tie(Spec, Const) =
6837 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(ClassDecl);
6839 QualType ArgType = Context.getTypeDeclType(ClassDecl);
6840 QualType RetType = Context.getLValueReferenceType(ArgType);
6842 ArgType = ArgType.withConst();
6843 ArgType = Context.getLValueReferenceType(ArgType);
6845 // An implicitly-declared copy assignment operator is an inline public
6846 // member of its class.
6847 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
6848 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
6849 SourceLocation ClassLoc = ClassDecl->getLocation();
6850 DeclarationNameInfo NameInfo(Name, ClassLoc);
6851 CXXMethodDecl *CopyAssignment
6852 = CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
6853 Context.getFunctionType(RetType, &ArgType, 1, EPI),
6854 /*TInfo=*/0, /*isStatic=*/false,
6855 /*StorageClassAsWritten=*/SC_None,
6858 CopyAssignment->setAccess(AS_public);
6859 CopyAssignment->setDefaulted();
6860 CopyAssignment->setImplicit();
6861 CopyAssignment->setTrivial(ClassDecl->hasTrivialCopyAssignment());
6863 // Add the parameter to the operator.
6864 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
6865 ClassLoc, ClassLoc, /*Id=*/0,
6866 ArgType, /*TInfo=*/0,
6869 CopyAssignment->setParams(&FromParam, 1);
6871 // Note that we have added this copy-assignment operator.
6872 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
6874 if (Scope *S = getScopeForContext(ClassDecl))
6875 PushOnScopeChains(CopyAssignment, S, false);
6876 ClassDecl->addDecl(CopyAssignment);
6878 if (ShouldDeleteCopyAssignmentOperator(CopyAssignment))
6879 CopyAssignment->setDeletedAsWritten();
6881 AddOverriddenMethods(ClassDecl, CopyAssignment);
6882 return CopyAssignment;
6885 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6886 CXXMethodDecl *CopyAssignOperator) {
6887 assert((CopyAssignOperator->isDefaulted() &&
6888 CopyAssignOperator->isOverloadedOperator() &&
6889 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
6890 !CopyAssignOperator->doesThisDeclarationHaveABody()) &&
6891 "DefineImplicitCopyAssignment called for wrong function");
6893 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
6895 if (ClassDecl->isInvalidDecl() || CopyAssignOperator->isInvalidDecl()) {
6896 CopyAssignOperator->setInvalidDecl();
6900 CopyAssignOperator->setUsed();
6902 ImplicitlyDefinedFunctionScope Scope(*this, CopyAssignOperator);
6903 DiagnosticErrorTrap Trap(Diags);
6905 // C++0x [class.copy]p30:
6906 // The implicitly-defined or explicitly-defaulted copy assignment operator
6907 // for a non-union class X performs memberwise copy assignment of its
6908 // subobjects. The direct base classes of X are assigned first, in the
6909 // order of their declaration in the base-specifier-list, and then the
6910 // immediate non-static data members of X are assigned, in the order in
6911 // which they were declared in the class definition.
6913 // The statements that form the synthesized function body.
6914 ASTOwningVector<Stmt*> Statements(*this);
6916 // The parameter for the "other" object, which we are copying from.
6917 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
6918 Qualifiers OtherQuals = Other->getType().getQualifiers();
6919 QualType OtherRefType = Other->getType();
6920 if (const LValueReferenceType *OtherRef
6921 = OtherRefType->getAs<LValueReferenceType>()) {
6922 OtherRefType = OtherRef->getPointeeType();
6923 OtherQuals = OtherRefType.getQualifiers();
6926 // Our location for everything implicitly-generated.
6927 SourceLocation Loc = CopyAssignOperator->getLocation();
6929 // Construct a reference to the "other" object. We'll be using this
6930 // throughout the generated ASTs.
6931 Expr *OtherRef = BuildDeclRefExpr(Other, OtherRefType, VK_LValue, Loc).take();
6932 assert(OtherRef && "Reference to parameter cannot fail!");
6934 // Construct the "this" pointer. We'll be using this throughout the generated
6936 Expr *This = ActOnCXXThis(Loc).takeAs<Expr>();
6937 assert(This && "Reference to this cannot fail!");
6939 // Assign base classes.
6940 bool Invalid = false;
6941 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
6942 E = ClassDecl->bases_end(); Base != E; ++Base) {
6943 // Form the assignment:
6944 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
6945 QualType BaseType = Base->getType().getUnqualifiedType();
6946 if (!BaseType->isRecordType()) {
6951 CXXCastPath BasePath;
6952 BasePath.push_back(Base);
6954 // Construct the "from" expression, which is an implicit cast to the
6955 // appropriately-qualified base type.
6956 Expr *From = OtherRef;
6957 From = ImpCastExprToType(From, Context.getQualifiedType(BaseType, OtherQuals),
6958 CK_UncheckedDerivedToBase,
6959 VK_LValue, &BasePath).take();
6961 // Dereference "this".
6962 ExprResult To = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
6964 // Implicitly cast "this" to the appropriately-qualified base type.
6965 To = ImpCastExprToType(To.take(),
6966 Context.getCVRQualifiedType(BaseType,
6967 CopyAssignOperator->getTypeQualifiers()),
6968 CK_UncheckedDerivedToBase,
6969 VK_LValue, &BasePath);
6972 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, BaseType,
6974 /*CopyingBaseSubobject=*/true);
6975 if (Copy.isInvalid()) {
6976 Diag(CurrentLocation, diag::note_member_synthesized_at)
6977 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
6978 CopyAssignOperator->setInvalidDecl();
6982 // Success! Record the copy.
6983 Statements.push_back(Copy.takeAs<Expr>());
6986 // \brief Reference to the __builtin_memcpy function.
6987 Expr *BuiltinMemCpyRef = 0;
6988 // \brief Reference to the __builtin_objc_memmove_collectable function.
6989 Expr *CollectableMemCpyRef = 0;
6991 // Assign non-static members.
6992 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
6993 FieldEnd = ClassDecl->field_end();
6994 Field != FieldEnd; ++Field) {
6995 // Check for members of reference type; we can't copy those.
6996 if (Field->getType()->isReferenceType()) {
6997 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
6998 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
6999 Diag(Field->getLocation(), diag::note_declared_at);
7000 Diag(CurrentLocation, diag::note_member_synthesized_at)
7001 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7006 // Check for members of const-qualified, non-class type.
7007 QualType BaseType = Context.getBaseElementType(Field->getType());
7008 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
7009 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
7010 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
7011 Diag(Field->getLocation(), diag::note_declared_at);
7012 Diag(CurrentLocation, diag::note_member_synthesized_at)
7013 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7018 QualType FieldType = Field->getType().getNonReferenceType();
7019 if (FieldType->isIncompleteArrayType()) {
7020 assert(ClassDecl->hasFlexibleArrayMember() &&
7021 "Incomplete array type is not valid");
7025 // Build references to the field in the object we're copying from and to.
7026 CXXScopeSpec SS; // Intentionally empty
7027 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
7029 MemberLookup.addDecl(*Field);
7030 MemberLookup.resolveKind();
7031 ExprResult From = BuildMemberReferenceExpr(OtherRef, OtherRefType,
7032 Loc, /*IsArrow=*/false,
7033 SS, 0, MemberLookup, 0);
7034 ExprResult To = BuildMemberReferenceExpr(This, This->getType(),
7035 Loc, /*IsArrow=*/true,
7036 SS, 0, MemberLookup, 0);
7037 assert(!From.isInvalid() && "Implicit field reference cannot fail");
7038 assert(!To.isInvalid() && "Implicit field reference cannot fail");
7040 // If the field should be copied with __builtin_memcpy rather than via
7041 // explicit assignments, do so. This optimization only applies for arrays
7042 // of scalars and arrays of class type with trivial copy-assignment
7044 if (FieldType->isArrayType() &&
7045 (!BaseType->isRecordType() ||
7046 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl())
7047 ->hasTrivialCopyAssignment())) {
7048 // Compute the size of the memory buffer to be copied.
7049 QualType SizeType = Context.getSizeType();
7050 llvm::APInt Size(Context.getTypeSize(SizeType),
7051 Context.getTypeSizeInChars(BaseType).getQuantity());
7052 for (const ConstantArrayType *Array
7053 = Context.getAsConstantArrayType(FieldType);
7055 Array = Context.getAsConstantArrayType(Array->getElementType())) {
7056 llvm::APInt ArraySize
7057 = Array->getSize().zextOrTrunc(Size.getBitWidth());
7061 // Take the address of the field references for "from" and "to".
7062 From = CreateBuiltinUnaryOp(Loc, UO_AddrOf, From.get());
7063 To = CreateBuiltinUnaryOp(Loc, UO_AddrOf, To.get());
7065 bool NeedsCollectableMemCpy =
7066 (BaseType->isRecordType() &&
7067 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember());
7069 if (NeedsCollectableMemCpy) {
7070 if (!CollectableMemCpyRef) {
7071 // Create a reference to the __builtin_objc_memmove_collectable function.
7072 LookupResult R(*this,
7073 &Context.Idents.get("__builtin_objc_memmove_collectable"),
7074 Loc, LookupOrdinaryName);
7075 LookupName(R, TUScope, true);
7077 FunctionDecl *CollectableMemCpy = R.getAsSingle<FunctionDecl>();
7078 if (!CollectableMemCpy) {
7079 // Something went horribly wrong earlier, and we will have
7080 // complained about it.
7085 CollectableMemCpyRef = BuildDeclRefExpr(CollectableMemCpy,
7086 CollectableMemCpy->getType(),
7087 VK_LValue, Loc, 0).take();
7088 assert(CollectableMemCpyRef && "Builtin reference cannot fail");
7091 // Create a reference to the __builtin_memcpy builtin function.
7092 else if (!BuiltinMemCpyRef) {
7093 LookupResult R(*this, &Context.Idents.get("__builtin_memcpy"), Loc,
7094 LookupOrdinaryName);
7095 LookupName(R, TUScope, true);
7097 FunctionDecl *BuiltinMemCpy = R.getAsSingle<FunctionDecl>();
7098 if (!BuiltinMemCpy) {
7099 // Something went horribly wrong earlier, and we will have complained
7105 BuiltinMemCpyRef = BuildDeclRefExpr(BuiltinMemCpy,
7106 BuiltinMemCpy->getType(),
7107 VK_LValue, Loc, 0).take();
7108 assert(BuiltinMemCpyRef && "Builtin reference cannot fail");
7111 ASTOwningVector<Expr*> CallArgs(*this);
7112 CallArgs.push_back(To.takeAs<Expr>());
7113 CallArgs.push_back(From.takeAs<Expr>());
7114 CallArgs.push_back(IntegerLiteral::Create(Context, Size, SizeType, Loc));
7115 ExprResult Call = ExprError();
7116 if (NeedsCollectableMemCpy)
7117 Call = ActOnCallExpr(/*Scope=*/0,
7118 CollectableMemCpyRef,
7119 Loc, move_arg(CallArgs),
7122 Call = ActOnCallExpr(/*Scope=*/0,
7124 Loc, move_arg(CallArgs),
7127 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
7128 Statements.push_back(Call.takeAs<Expr>());
7132 // Build the copy of this field.
7133 StmtResult Copy = BuildSingleCopyAssign(*this, Loc, FieldType,
7134 To.get(), From.get(),
7135 /*CopyingBaseSubobject=*/false);
7136 if (Copy.isInvalid()) {
7137 Diag(CurrentLocation, diag::note_member_synthesized_at)
7138 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7139 CopyAssignOperator->setInvalidDecl();
7143 // Success! Record the copy.
7144 Statements.push_back(Copy.takeAs<Stmt>());
7148 // Add a "return *this;"
7149 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
7151 StmtResult Return = ActOnReturnStmt(Loc, ThisObj.get());
7152 if (Return.isInvalid())
7155 Statements.push_back(Return.takeAs<Stmt>());
7157 if (Trap.hasErrorOccurred()) {
7158 Diag(CurrentLocation, diag::note_member_synthesized_at)
7159 << CXXCopyAssignment << Context.getTagDeclType(ClassDecl);
7166 CopyAssignOperator->setInvalidDecl();
7170 StmtResult Body = ActOnCompoundStmt(Loc, Loc, move_arg(Statements),
7171 /*isStmtExpr=*/false);
7172 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
7173 CopyAssignOperator->setBody(Body.takeAs<Stmt>());
7175 if (ASTMutationListener *L = getASTMutationListener()) {
7176 L->CompletedImplicitDefinition(CopyAssignOperator);
7180 std::pair<Sema::ImplicitExceptionSpecification, bool>
7181 Sema::ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl) {
7182 // C++ [class.copy]p5:
7183 // The implicitly-declared copy constructor for a class X will
7189 // FIXME: It ought to be possible to store this on the record.
7190 bool HasConstCopyConstructor = true;
7192 // -- each direct or virtual base class B of X has a copy
7193 // constructor whose first parameter is of type const B& or
7194 // const volatile B&, and
7195 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7196 BaseEnd = ClassDecl->bases_end();
7197 HasConstCopyConstructor && Base != BaseEnd;
7199 // Virtual bases are handled below.
7200 if (Base->isVirtual())
7203 CXXRecordDecl *BaseClassDecl
7204 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7205 LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7206 &HasConstCopyConstructor);
7209 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7210 BaseEnd = ClassDecl->vbases_end();
7211 HasConstCopyConstructor && Base != BaseEnd;
7213 CXXRecordDecl *BaseClassDecl
7214 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7215 LookupCopyConstructor(BaseClassDecl, Qualifiers::Const,
7216 &HasConstCopyConstructor);
7219 // -- for all the nonstatic data members of X that are of a
7220 // class type M (or array thereof), each such class type
7221 // has a copy constructor whose first parameter is of type
7222 // const M& or const volatile M&.
7223 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7224 FieldEnd = ClassDecl->field_end();
7225 HasConstCopyConstructor && Field != FieldEnd;
7227 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7228 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7229 LookupCopyConstructor(FieldClassDecl, Qualifiers::Const,
7230 &HasConstCopyConstructor);
7233 // Otherwise, the implicitly declared copy constructor will have
7238 // C++ [except.spec]p14:
7239 // An implicitly declared special member function (Clause 12) shall have an
7240 // exception-specification. [...]
7241 ImplicitExceptionSpecification ExceptSpec(Context);
7242 unsigned Quals = HasConstCopyConstructor? Qualifiers::Const : 0;
7243 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(),
7244 BaseEnd = ClassDecl->bases_end();
7247 // Virtual bases are handled below.
7248 if (Base->isVirtual())
7251 CXXRecordDecl *BaseClassDecl
7252 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7253 if (CXXConstructorDecl *CopyConstructor =
7254 LookupCopyConstructor(BaseClassDecl, Quals))
7255 ExceptSpec.CalledDecl(CopyConstructor);
7257 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->vbases_begin(),
7258 BaseEnd = ClassDecl->vbases_end();
7261 CXXRecordDecl *BaseClassDecl
7262 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
7263 if (CXXConstructorDecl *CopyConstructor =
7264 LookupCopyConstructor(BaseClassDecl, Quals))
7265 ExceptSpec.CalledDecl(CopyConstructor);
7267 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(),
7268 FieldEnd = ClassDecl->field_end();
7271 QualType FieldType = Context.getBaseElementType((*Field)->getType());
7272 if (CXXRecordDecl *FieldClassDecl = FieldType->getAsCXXRecordDecl()) {
7273 if (CXXConstructorDecl *CopyConstructor =
7274 LookupCopyConstructor(FieldClassDecl, Quals))
7275 ExceptSpec.CalledDecl(CopyConstructor);
7279 return std::make_pair(ExceptSpec, HasConstCopyConstructor);
7282 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
7283 CXXRecordDecl *ClassDecl) {
7284 // C++ [class.copy]p4:
7285 // If the class definition does not explicitly declare a copy
7286 // constructor, one is declared implicitly.
7288 ImplicitExceptionSpecification Spec(Context);
7290 llvm::tie(Spec, Const) =
7291 ComputeDefaultedCopyCtorExceptionSpecAndConst(ClassDecl);
7293 QualType ClassType = Context.getTypeDeclType(ClassDecl);
7294 QualType ArgType = ClassType;
7296 ArgType = ArgType.withConst();
7297 ArgType = Context.getLValueReferenceType(ArgType);
7299 FunctionProtoType::ExtProtoInfo EPI = Spec.getEPI();
7301 DeclarationName Name
7302 = Context.DeclarationNames.getCXXConstructorName(
7303 Context.getCanonicalType(ClassType));
7304 SourceLocation ClassLoc = ClassDecl->getLocation();
7305 DeclarationNameInfo NameInfo(Name, ClassLoc);
7307 // An implicitly-declared copy constructor is an inline public
7308 // member of its class.
7309 CXXConstructorDecl *CopyConstructor
7310 = CXXConstructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
7311 Context.getFunctionType(Context.VoidTy,
7314 /*isExplicit=*/false,
7316 /*isImplicitlyDeclared=*/true);
7317 CopyConstructor->setAccess(AS_public);
7318 CopyConstructor->setDefaulted();
7319 CopyConstructor->setTrivial(ClassDecl->hasTrivialCopyConstructor());
7321 // Note that we have declared this constructor.
7322 ++ASTContext::NumImplicitCopyConstructorsDeclared;
7324 // Add the parameter to the constructor.
7325 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
7327 /*IdentifierInfo=*/0,
7328 ArgType, /*TInfo=*/0,
7331 CopyConstructor->setParams(&FromParam, 1);
7333 if (Scope *S = getScopeForContext(ClassDecl))
7334 PushOnScopeChains(CopyConstructor, S, false);
7335 ClassDecl->addDecl(CopyConstructor);
7337 if (ShouldDeleteCopyConstructor(CopyConstructor))
7338 CopyConstructor->setDeletedAsWritten();
7340 return CopyConstructor;
7343 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
7344 CXXConstructorDecl *CopyConstructor) {
7345 assert((CopyConstructor->isDefaulted() &&
7346 CopyConstructor->isCopyConstructor() &&
7347 !CopyConstructor->doesThisDeclarationHaveABody()) &&
7348 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
7350 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
7351 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
7353 ImplicitlyDefinedFunctionScope Scope(*this, CopyConstructor);
7354 DiagnosticErrorTrap Trap(Diags);
7356 if (SetCtorInitializers(CopyConstructor, 0, 0, /*AnyErrors=*/false) ||
7357 Trap.hasErrorOccurred()) {
7358 Diag(CurrentLocation, diag::note_member_synthesized_at)
7359 << CXXCopyConstructor << Context.getTagDeclType(ClassDecl);
7360 CopyConstructor->setInvalidDecl();
7362 CopyConstructor->setBody(ActOnCompoundStmt(CopyConstructor->getLocation(),
7363 CopyConstructor->getLocation(),
7364 MultiStmtArg(*this, 0, 0),
7365 /*isStmtExpr=*/false)
7369 CopyConstructor->setUsed();
7371 if (ASTMutationListener *L = getASTMutationListener()) {
7372 L->CompletedImplicitDefinition(CopyConstructor);
7377 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7378 CXXConstructorDecl *Constructor,
7379 MultiExprArg ExprArgs,
7380 bool RequiresZeroInit,
7381 unsigned ConstructKind,
7382 SourceRange ParenRange) {
7383 bool Elidable = false;
7385 // C++0x [class.copy]p34:
7386 // When certain criteria are met, an implementation is allowed to
7387 // omit the copy/move construction of a class object, even if the
7388 // copy/move constructor and/or destructor for the object have
7389 // side effects. [...]
7390 // - when a temporary class object that has not been bound to a
7391 // reference (12.2) would be copied/moved to a class object
7392 // with the same cv-unqualified type, the copy/move operation
7393 // can be omitted by constructing the temporary object
7394 // directly into the target of the omitted copy/move
7395 if (ConstructKind == CXXConstructExpr::CK_Complete &&
7396 Constructor->isCopyOrMoveConstructor() && ExprArgs.size() >= 1) {
7397 Expr *SubExpr = ((Expr **)ExprArgs.get())[0];
7398 Elidable = SubExpr->isTemporaryObject(Context, Constructor->getParent());
7401 return BuildCXXConstructExpr(ConstructLoc, DeclInitType, Constructor,
7402 Elidable, move(ExprArgs), RequiresZeroInit,
7403 ConstructKind, ParenRange);
7406 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
7407 /// including handling of its default argument expressions.
7409 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
7410 CXXConstructorDecl *Constructor, bool Elidable,
7411 MultiExprArg ExprArgs,
7412 bool RequiresZeroInit,
7413 unsigned ConstructKind,
7414 SourceRange ParenRange) {
7415 unsigned NumExprs = ExprArgs.size();
7416 Expr **Exprs = (Expr **)ExprArgs.release();
7418 for (specific_attr_iterator<NonNullAttr>
7419 i = Constructor->specific_attr_begin<NonNullAttr>(),
7420 e = Constructor->specific_attr_end<NonNullAttr>(); i != e; ++i) {
7421 const NonNullAttr *NonNull = *i;
7422 CheckNonNullArguments(NonNull, ExprArgs.get(), ConstructLoc);
7425 MarkDeclarationReferenced(ConstructLoc, Constructor);
7426 return Owned(CXXConstructExpr::Create(Context, DeclInitType, ConstructLoc,
7427 Constructor, Elidable, Exprs, NumExprs,
7429 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
7433 bool Sema::InitializeVarWithConstructor(VarDecl *VD,
7434 CXXConstructorDecl *Constructor,
7435 MultiExprArg Exprs) {
7436 // FIXME: Provide the correct paren SourceRange when available.
7437 ExprResult TempResult =
7438 BuildCXXConstructExpr(VD->getLocation(), VD->getType(), Constructor,
7439 move(Exprs), false, CXXConstructExpr::CK_Complete,
7441 if (TempResult.isInvalid())
7444 Expr *Temp = TempResult.takeAs<Expr>();
7445 CheckImplicitConversions(Temp, VD->getLocation());
7446 MarkDeclarationReferenced(VD->getLocation(), Constructor);
7447 Temp = MaybeCreateExprWithCleanups(Temp);
7453 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
7454 if (VD->isInvalidDecl()) return;
7456 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
7457 if (ClassDecl->isInvalidDecl()) return;
7458 if (ClassDecl->hasTrivialDestructor()) return;
7459 if (ClassDecl->isDependentContext()) return;
7461 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7462 MarkDeclarationReferenced(VD->getLocation(), Destructor);
7463 CheckDestructorAccess(VD->getLocation(), Destructor,
7464 PDiag(diag::err_access_dtor_var)
7465 << VD->getDeclName()
7468 if (!VD->hasGlobalStorage()) return;
7470 // Emit warning for non-trivial dtor in global scope (a real global,
7471 // class-static, function-static).
7472 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
7474 // TODO: this should be re-enabled for static locals by !CXAAtExit
7475 if (!VD->isStaticLocal())
7476 Diag(VD->getLocation(), diag::warn_global_destructor);
7479 /// AddCXXDirectInitializerToDecl - This action is called immediately after
7480 /// ActOnDeclarator, when a C++ direct initializer is present.
7481 /// e.g: "int x(1);"
7482 void Sema::AddCXXDirectInitializerToDecl(Decl *RealDecl,
7483 SourceLocation LParenLoc,
7485 SourceLocation RParenLoc,
7486 bool TypeMayContainAuto) {
7487 assert(Exprs.size() != 0 && Exprs.get() && "missing expressions");
7489 // If there is no declaration, there was an error parsing it. Just ignore
7494 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
7496 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
7497 RealDecl->setInvalidDecl();
7501 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
7502 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) {
7503 // FIXME: n3225 doesn't actually seem to indicate this is ill-formed
7504 if (Exprs.size() > 1) {
7505 Diag(Exprs.get()[1]->getSourceRange().getBegin(),
7506 diag::err_auto_var_init_multiple_expressions)
7507 << VDecl->getDeclName() << VDecl->getType()
7508 << VDecl->getSourceRange();
7509 RealDecl->setInvalidDecl();
7513 Expr *Init = Exprs.get()[0];
7514 TypeSourceInfo *DeducedType = 0;
7515 if (!DeduceAutoType(VDecl->getTypeSourceInfo(), Init, DeducedType))
7516 Diag(VDecl->getLocation(), diag::err_auto_var_deduction_failure)
7517 << VDecl->getDeclName() << VDecl->getType() << Init->getType()
7518 << Init->getSourceRange();
7520 RealDecl->setInvalidDecl();
7523 VDecl->setTypeSourceInfo(DeducedType);
7524 VDecl->setType(DeducedType->getType());
7526 // If this is a redeclaration, check that the type we just deduced matches
7527 // the previously declared type.
7528 if (VarDecl *Old = VDecl->getPreviousDeclaration())
7529 MergeVarDeclTypes(VDecl, Old);
7532 // We will represent direct-initialization similarly to copy-initialization:
7533 // int x(1); -as-> int x = 1;
7534 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
7536 // Clients that want to distinguish between the two forms, can check for
7537 // direct initializer using VarDecl::hasCXXDirectInitializer().
7538 // A major benefit is that clients that don't particularly care about which
7539 // exactly form was it (like the CodeGen) can handle both cases without
7540 // special case code.
7543 // The form of initialization (using parentheses or '=') is generally
7544 // insignificant, but does matter when the entity being initialized has a
7547 if (!VDecl->getType()->isDependentType() &&
7548 RequireCompleteType(VDecl->getLocation(), VDecl->getType(),
7549 diag::err_typecheck_decl_incomplete_type)) {
7550 VDecl->setInvalidDecl();
7554 // The variable can not have an abstract class type.
7555 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
7556 diag::err_abstract_type_in_decl,
7557 AbstractVariableType))
7558 VDecl->setInvalidDecl();
7561 if ((Def = VDecl->getDefinition()) && Def != VDecl) {
7562 Diag(VDecl->getLocation(), diag::err_redefinition)
7563 << VDecl->getDeclName();
7564 Diag(Def->getLocation(), diag::note_previous_definition);
7565 VDecl->setInvalidDecl();
7569 // C++ [class.static.data]p4
7570 // If a static data member is of const integral or const
7571 // enumeration type, its declaration in the class definition can
7572 // specify a constant-initializer which shall be an integral
7573 // constant expression (5.19). In that case, the member can appear
7574 // in integral constant expressions. The member shall still be
7575 // defined in a namespace scope if it is used in the program and the
7576 // namespace scope definition shall not contain an initializer.
7578 // We already performed a redefinition check above, but for static
7579 // data members we also need to check whether there was an in-class
7580 // declaration with an initializer.
7581 const VarDecl* PrevInit = 0;
7582 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) {
7583 Diag(VDecl->getLocation(), diag::err_redefinition) << VDecl->getDeclName();
7584 Diag(PrevInit->getLocation(), diag::note_previous_definition);
7588 bool IsDependent = false;
7589 for (unsigned I = 0, N = Exprs.size(); I != N; ++I) {
7590 if (DiagnoseUnexpandedParameterPack(Exprs.get()[I], UPPC_Expression)) {
7591 VDecl->setInvalidDecl();
7595 if (Exprs.get()[I]->isTypeDependent())
7599 // If either the declaration has a dependent type or if any of the
7600 // expressions is type-dependent, we represent the initialization
7601 // via a ParenListExpr for later use during template instantiation.
7602 if (VDecl->getType()->isDependentType() || IsDependent) {
7603 // Let clients know that initialization was done with a direct initializer.
7604 VDecl->setCXXDirectInitializer(true);
7606 // Store the initialization expressions as a ParenListExpr.
7607 unsigned NumExprs = Exprs.size();
7608 VDecl->setInit(new (Context) ParenListExpr(Context, LParenLoc,
7609 (Expr **)Exprs.release(),
7610 NumExprs, RParenLoc));
7614 // Capture the variable that is being initialized and the style of
7616 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
7618 // FIXME: Poor source location information.
7619 InitializationKind Kind
7620 = InitializationKind::CreateDirect(VDecl->getLocation(),
7621 LParenLoc, RParenLoc);
7623 InitializationSequence InitSeq(*this, Entity, Kind,
7624 Exprs.get(), Exprs.size());
7625 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(Exprs));
7626 if (Result.isInvalid()) {
7627 VDecl->setInvalidDecl();
7631 CheckImplicitConversions(Result.get(), LParenLoc);
7633 Result = MaybeCreateExprWithCleanups(Result);
7634 VDecl->setInit(Result.takeAs<Expr>());
7635 VDecl->setCXXDirectInitializer(true);
7637 CheckCompleteVariableDeclaration(VDecl);
7640 /// \brief Given a constructor and the set of arguments provided for the
7641 /// constructor, convert the arguments and add any required default arguments
7642 /// to form a proper call to this constructor.
7644 /// \returns true if an error occurred, false otherwise.
7646 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
7647 MultiExprArg ArgsPtr,
7649 ASTOwningVector<Expr*> &ConvertedArgs) {
7650 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
7651 unsigned NumArgs = ArgsPtr.size();
7652 Expr **Args = (Expr **)ArgsPtr.get();
7654 const FunctionProtoType *Proto
7655 = Constructor->getType()->getAs<FunctionProtoType>();
7656 assert(Proto && "Constructor without a prototype?");
7657 unsigned NumArgsInProto = Proto->getNumArgs();
7659 // If too few arguments are available, we'll fill in the rest with defaults.
7660 if (NumArgs < NumArgsInProto)
7661 ConvertedArgs.reserve(NumArgsInProto);
7663 ConvertedArgs.reserve(NumArgs);
7665 VariadicCallType CallType =
7666 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
7667 llvm::SmallVector<Expr *, 8> AllArgs;
7668 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
7669 Proto, 0, Args, NumArgs, AllArgs,
7671 for (unsigned i =0, size = AllArgs.size(); i < size; i++)
7672 ConvertedArgs.push_back(AllArgs[i]);
7677 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
7678 const FunctionDecl *FnDecl) {
7679 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
7680 if (isa<NamespaceDecl>(DC)) {
7681 return SemaRef.Diag(FnDecl->getLocation(),
7682 diag::err_operator_new_delete_declared_in_namespace)
7683 << FnDecl->getDeclName();
7686 if (isa<TranslationUnitDecl>(DC) &&
7687 FnDecl->getStorageClass() == SC_Static) {
7688 return SemaRef.Diag(FnDecl->getLocation(),
7689 diag::err_operator_new_delete_declared_static)
7690 << FnDecl->getDeclName();
7697 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
7698 CanQualType ExpectedResultType,
7699 CanQualType ExpectedFirstParamType,
7700 unsigned DependentParamTypeDiag,
7701 unsigned InvalidParamTypeDiag) {
7702 QualType ResultType =
7703 FnDecl->getType()->getAs<FunctionType>()->getResultType();
7705 // Check that the result type is not dependent.
7706 if (ResultType->isDependentType())
7707 return SemaRef.Diag(FnDecl->getLocation(),
7708 diag::err_operator_new_delete_dependent_result_type)
7709 << FnDecl->getDeclName() << ExpectedResultType;
7711 // Check that the result type is what we expect.
7712 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
7713 return SemaRef.Diag(FnDecl->getLocation(),
7714 diag::err_operator_new_delete_invalid_result_type)
7715 << FnDecl->getDeclName() << ExpectedResultType;
7717 // A function template must have at least 2 parameters.
7718 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
7719 return SemaRef.Diag(FnDecl->getLocation(),
7720 diag::err_operator_new_delete_template_too_few_parameters)
7721 << FnDecl->getDeclName();
7723 // The function decl must have at least 1 parameter.
7724 if (FnDecl->getNumParams() == 0)
7725 return SemaRef.Diag(FnDecl->getLocation(),
7726 diag::err_operator_new_delete_too_few_parameters)
7727 << FnDecl->getDeclName();
7729 // Check the the first parameter type is not dependent.
7730 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
7731 if (FirstParamType->isDependentType())
7732 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
7733 << FnDecl->getDeclName() << ExpectedFirstParamType;
7735 // Check that the first parameter type is what we expect.
7736 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
7737 ExpectedFirstParamType)
7738 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
7739 << FnDecl->getDeclName() << ExpectedFirstParamType;
7745 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7746 // C++ [basic.stc.dynamic.allocation]p1:
7747 // A program is ill-formed if an allocation function is declared in a
7748 // namespace scope other than global scope or declared static in global
7750 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7753 CanQualType SizeTy =
7754 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
7756 // C++ [basic.stc.dynamic.allocation]p1:
7757 // The return type shall be void*. The first parameter shall have type
7759 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
7761 diag::err_operator_new_dependent_param_type,
7762 diag::err_operator_new_param_type))
7765 // C++ [basic.stc.dynamic.allocation]p1:
7766 // The first parameter shall not have an associated default argument.
7767 if (FnDecl->getParamDecl(0)->hasDefaultArg())
7768 return SemaRef.Diag(FnDecl->getLocation(),
7769 diag::err_operator_new_default_arg)
7770 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
7776 CheckOperatorDeleteDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
7777 // C++ [basic.stc.dynamic.deallocation]p1:
7778 // A program is ill-formed if deallocation functions are declared in a
7779 // namespace scope other than global scope or declared static in global
7781 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
7784 // C++ [basic.stc.dynamic.deallocation]p2:
7785 // Each deallocation function shall return void and its first parameter
7787 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidTy,
7788 SemaRef.Context.VoidPtrTy,
7789 diag::err_operator_delete_dependent_param_type,
7790 diag::err_operator_delete_param_type))
7796 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
7797 /// of this overloaded operator is well-formed. If so, returns false;
7798 /// otherwise, emits appropriate diagnostics and returns true.
7799 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
7800 assert(FnDecl && FnDecl->isOverloadedOperator() &&
7801 "Expected an overloaded operator declaration");
7803 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
7805 // C++ [over.oper]p5:
7806 // The allocation and deallocation functions, operator new,
7807 // operator new[], operator delete and operator delete[], are
7808 // described completely in 3.7.3. The attributes and restrictions
7809 // found in the rest of this subclause do not apply to them unless
7810 // explicitly stated in 3.7.3.
7811 if (Op == OO_Delete || Op == OO_Array_Delete)
7812 return CheckOperatorDeleteDeclaration(*this, FnDecl);
7814 if (Op == OO_New || Op == OO_Array_New)
7815 return CheckOperatorNewDeclaration(*this, FnDecl);
7817 // C++ [over.oper]p6:
7818 // An operator function shall either be a non-static member
7819 // function or be a non-member function and have at least one
7820 // parameter whose type is a class, a reference to a class, an
7821 // enumeration, or a reference to an enumeration.
7822 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
7823 if (MethodDecl->isStatic())
7824 return Diag(FnDecl->getLocation(),
7825 diag::err_operator_overload_static) << FnDecl->getDeclName();
7827 bool ClassOrEnumParam = false;
7828 for (FunctionDecl::param_iterator Param = FnDecl->param_begin(),
7829 ParamEnd = FnDecl->param_end();
7830 Param != ParamEnd; ++Param) {
7831 QualType ParamType = (*Param)->getType().getNonReferenceType();
7832 if (ParamType->isDependentType() || ParamType->isRecordType() ||
7833 ParamType->isEnumeralType()) {
7834 ClassOrEnumParam = true;
7839 if (!ClassOrEnumParam)
7840 return Diag(FnDecl->getLocation(),
7841 diag::err_operator_overload_needs_class_or_enum)
7842 << FnDecl->getDeclName();
7845 // C++ [over.oper]p8:
7846 // An operator function cannot have default arguments (8.3.6),
7847 // except where explicitly stated below.
7849 // Only the function-call operator allows default arguments
7850 // (C++ [over.call]p1).
7851 if (Op != OO_Call) {
7852 for (FunctionDecl::param_iterator Param = FnDecl->param_begin();
7853 Param != FnDecl->param_end(); ++Param) {
7854 if ((*Param)->hasDefaultArg())
7855 return Diag((*Param)->getLocation(),
7856 diag::err_operator_overload_default_arg)
7857 << FnDecl->getDeclName() << (*Param)->getDefaultArgRange();
7861 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
7862 { false, false, false }
7863 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
7864 , { Unary, Binary, MemberOnly }
7865 #include "clang/Basic/OperatorKinds.def"
7868 bool CanBeUnaryOperator = OperatorUses[Op][0];
7869 bool CanBeBinaryOperator = OperatorUses[Op][1];
7870 bool MustBeMemberOperator = OperatorUses[Op][2];
7872 // C++ [over.oper]p8:
7873 // [...] Operator functions cannot have more or fewer parameters
7874 // than the number required for the corresponding operator, as
7875 // described in the rest of this subclause.
7876 unsigned NumParams = FnDecl->getNumParams()
7877 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
7878 if (Op != OO_Call &&
7879 ((NumParams == 1 && !CanBeUnaryOperator) ||
7880 (NumParams == 2 && !CanBeBinaryOperator) ||
7881 (NumParams < 1) || (NumParams > 2))) {
7882 // We have the wrong number of parameters.
7884 if (CanBeUnaryOperator && CanBeBinaryOperator) {
7885 ErrorKind = 2; // 2 -> unary or binary.
7886 } else if (CanBeUnaryOperator) {
7887 ErrorKind = 0; // 0 -> unary
7889 assert(CanBeBinaryOperator &&
7890 "All non-call overloaded operators are unary or binary!");
7891 ErrorKind = 1; // 1 -> binary
7894 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
7895 << FnDecl->getDeclName() << NumParams << ErrorKind;
7898 // Overloaded operators other than operator() cannot be variadic.
7899 if (Op != OO_Call &&
7900 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
7901 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
7902 << FnDecl->getDeclName();
7905 // Some operators must be non-static member functions.
7906 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
7907 return Diag(FnDecl->getLocation(),
7908 diag::err_operator_overload_must_be_member)
7909 << FnDecl->getDeclName();
7912 // C++ [over.inc]p1:
7913 // The user-defined function called operator++ implements the
7914 // prefix and postfix ++ operator. If this function is a member
7915 // function with no parameters, or a non-member function with one
7916 // parameter of class or enumeration type, it defines the prefix
7917 // increment operator ++ for objects of that type. If the function
7918 // is a member function with one parameter (which shall be of type
7919 // int) or a non-member function with two parameters (the second
7920 // of which shall be of type int), it defines the postfix
7921 // increment operator ++ for objects of that type.
7922 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
7923 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
7924 bool ParamIsInt = false;
7925 if (const BuiltinType *BT = LastParam->getType()->getAs<BuiltinType>())
7926 ParamIsInt = BT->getKind() == BuiltinType::Int;
7929 return Diag(LastParam->getLocation(),
7930 diag::err_operator_overload_post_incdec_must_be_int)
7931 << LastParam->getType() << (Op == OO_MinusMinus);
7937 /// CheckLiteralOperatorDeclaration - Check whether the declaration
7938 /// of this literal operator function is well-formed. If so, returns
7939 /// false; otherwise, emits appropriate diagnostics and returns true.
7940 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
7941 DeclContext *DC = FnDecl->getDeclContext();
7942 Decl::Kind Kind = DC->getDeclKind();
7943 if (Kind != Decl::TranslationUnit && Kind != Decl::Namespace &&
7944 Kind != Decl::LinkageSpec) {
7945 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
7946 << FnDecl->getDeclName();
7952 // template <char...> type operator "" name() is the only valid template
7953 // signature, and the only valid signature with no parameters.
7954 if (FnDecl->param_size() == 0) {
7955 if (FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate()) {
7956 // Must have only one template parameter
7957 TemplateParameterList *Params = TpDecl->getTemplateParameters();
7958 if (Params->size() == 1) {
7959 NonTypeTemplateParmDecl *PmDecl =
7960 cast<NonTypeTemplateParmDecl>(Params->getParam(0));
7962 // The template parameter must be a char parameter pack.
7963 if (PmDecl && PmDecl->isTemplateParameterPack() &&
7964 Context.hasSameType(PmDecl->getType(), Context.CharTy))
7969 // Check the first parameter
7970 FunctionDecl::param_iterator Param = FnDecl->param_begin();
7972 QualType T = (*Param)->getType();
7974 // unsigned long long int, long double, and any character type are allowed
7975 // as the only parameters.
7976 if (Context.hasSameType(T, Context.UnsignedLongLongTy) ||
7977 Context.hasSameType(T, Context.LongDoubleTy) ||
7978 Context.hasSameType(T, Context.CharTy) ||
7979 Context.hasSameType(T, Context.WCharTy) ||
7980 Context.hasSameType(T, Context.Char16Ty) ||
7981 Context.hasSameType(T, Context.Char32Ty)) {
7982 if (++Param == FnDecl->param_end())
7984 goto FinishedParams;
7987 // Otherwise it must be a pointer to const; let's strip those qualifiers.
7988 const PointerType *PT = T->getAs<PointerType>();
7990 goto FinishedParams;
7991 T = PT->getPointeeType();
7992 if (!T.isConstQualified())
7993 goto FinishedParams;
7994 T = T.getUnqualifiedType();
7996 // Move on to the second parameter;
7999 // If there is no second parameter, the first must be a const char *
8000 if (Param == FnDecl->param_end()) {
8001 if (Context.hasSameType(T, Context.CharTy))
8003 goto FinishedParams;
8006 // const char *, const wchar_t*, const char16_t*, and const char32_t*
8007 // are allowed as the first parameter to a two-parameter function
8008 if (!(Context.hasSameType(T, Context.CharTy) ||
8009 Context.hasSameType(T, Context.WCharTy) ||
8010 Context.hasSameType(T, Context.Char16Ty) ||
8011 Context.hasSameType(T, Context.Char32Ty)))
8012 goto FinishedParams;
8014 // The second and final parameter must be an std::size_t
8015 T = (*Param)->getType().getUnqualifiedType();
8016 if (Context.hasSameType(T, Context.getSizeType()) &&
8017 ++Param == FnDecl->param_end())
8021 // FIXME: This diagnostic is absolutely terrible.
8024 Diag(FnDecl->getLocation(), diag::err_literal_operator_params)
8025 << FnDecl->getDeclName();
8032 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
8033 /// linkage specification, including the language and (if present)
8034 /// the '{'. ExternLoc is the location of the 'extern', LangLoc is
8035 /// the location of the language string literal, which is provided
8036 /// by Lang/StrSize. LBraceLoc, if valid, provides the location of
8037 /// the '{' brace. Otherwise, this linkage specification does not
8038 /// have any braces.
8039 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
8040 SourceLocation LangLoc,
8041 llvm::StringRef Lang,
8042 SourceLocation LBraceLoc) {
8043 LinkageSpecDecl::LanguageIDs Language;
8044 if (Lang == "\"C\"")
8045 Language = LinkageSpecDecl::lang_c;
8046 else if (Lang == "\"C++\"")
8047 Language = LinkageSpecDecl::lang_cxx;
8049 Diag(LangLoc, diag::err_bad_language);
8053 // FIXME: Add all the various semantics of linkage specifications
8055 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext,
8056 ExternLoc, LangLoc, Language);
8057 CurContext->addDecl(D);
8058 PushDeclContext(S, D);
8062 /// ActOnFinishLinkageSpecification - Complete the definition of
8063 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
8064 /// valid, it's the position of the closing '}' brace in a linkage
8065 /// specification that uses braces.
8066 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
8068 SourceLocation RBraceLoc) {
8070 if (RBraceLoc.isValid()) {
8071 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
8072 LSDecl->setRBraceLoc(RBraceLoc);
8079 /// \brief Perform semantic analysis for the variable declaration that
8080 /// occurs within a C++ catch clause, returning the newly-created
8082 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
8083 TypeSourceInfo *TInfo,
8084 SourceLocation StartLoc,
8086 IdentifierInfo *Name) {
8087 bool Invalid = false;
8088 QualType ExDeclType = TInfo->getType();
8090 // Arrays and functions decay.
8091 if (ExDeclType->isArrayType())
8092 ExDeclType = Context.getArrayDecayedType(ExDeclType);
8093 else if (ExDeclType->isFunctionType())
8094 ExDeclType = Context.getPointerType(ExDeclType);
8096 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
8097 // The exception-declaration shall not denote a pointer or reference to an
8098 // incomplete type, other than [cv] void*.
8099 // N2844 forbids rvalue references.
8100 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
8101 Diag(Loc, diag::err_catch_rvalue_ref);
8105 // GCC allows catching pointers and references to incomplete types
8106 // as an extension; so do we, but we warn by default.
8108 QualType BaseType = ExDeclType;
8109 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
8110 unsigned DK = diag::err_catch_incomplete;
8111 bool IncompleteCatchIsInvalid = true;
8112 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
8113 BaseType = Ptr->getPointeeType();
8115 DK = diag::ext_catch_incomplete_ptr;
8116 IncompleteCatchIsInvalid = false;
8117 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
8118 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
8119 BaseType = Ref->getPointeeType();
8121 DK = diag::ext_catch_incomplete_ref;
8122 IncompleteCatchIsInvalid = false;
8124 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
8125 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK) &&
8126 IncompleteCatchIsInvalid)
8129 if (!Invalid && !ExDeclType->isDependentType() &&
8130 RequireNonAbstractType(Loc, ExDeclType,
8131 diag::err_abstract_type_in_decl,
8132 AbstractVariableType))
8135 // Only the non-fragile NeXT runtime currently supports C++ catches
8136 // of ObjC types, and no runtime supports catching ObjC types by value.
8137 if (!Invalid && getLangOptions().ObjC1) {
8138 QualType T = ExDeclType;
8139 if (const ReferenceType *RT = T->getAs<ReferenceType>())
8140 T = RT->getPointeeType();
8142 if (T->isObjCObjectType()) {
8143 Diag(Loc, diag::err_objc_object_catch);
8145 } else if (T->isObjCObjectPointerType()) {
8146 if (!getLangOptions().ObjCNonFragileABI) {
8147 Diag(Loc, diag::err_objc_pointer_cxx_catch_fragile);
8153 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
8154 ExDeclType, TInfo, SC_None, SC_None);
8155 ExDecl->setExceptionVariable(true);
8158 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
8159 // C++ [except.handle]p16:
8160 // The object declared in an exception-declaration or, if the
8161 // exception-declaration does not specify a name, a temporary (12.2) is
8162 // copy-initialized (8.5) from the exception object. [...]
8163 // The object is destroyed when the handler exits, after the destruction
8164 // of any automatic objects initialized within the handler.
8166 // We just pretend to initialize the object with itself, then make sure
8167 // it can be destroyed later.
8168 QualType initType = ExDeclType;
8170 InitializedEntity entity =
8171 InitializedEntity::InitializeVariable(ExDecl);
8172 InitializationKind initKind =
8173 InitializationKind::CreateCopy(Loc, SourceLocation());
8176 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
8177 InitializationSequence sequence(*this, entity, initKind, &opaqueValue, 1);
8178 ExprResult result = sequence.Perform(*this, entity, initKind,
8179 MultiExprArg(&opaqueValue, 1));
8180 if (result.isInvalid())
8183 // If the constructor used was non-trivial, set this as the
8185 CXXConstructExpr *construct = cast<CXXConstructExpr>(result.take());
8186 if (!construct->getConstructor()->isTrivial()) {
8187 Expr *init = MaybeCreateExprWithCleanups(construct);
8188 ExDecl->setInit(init);
8191 // And make sure it's destructable.
8192 FinalizeVarWithDestructor(ExDecl, recordType);
8198 ExDecl->setInvalidDecl();
8203 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
8205 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
8206 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8207 bool Invalid = D.isInvalidType();
8209 // Check for unexpanded parameter packs.
8210 if (TInfo && DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
8211 UPPC_ExceptionType)) {
8212 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
8213 D.getIdentifierLoc());
8217 IdentifierInfo *II = D.getIdentifier();
8218 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
8220 ForRedeclaration)) {
8221 // The scope should be freshly made just for us. There is just no way
8222 // it contains any previous declaration.
8223 assert(!S->isDeclScope(PrevDecl));
8224 if (PrevDecl->isTemplateParameter()) {
8225 // Maybe we will complain about the shadowed template parameter.
8226 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
8230 if (D.getCXXScopeSpec().isSet() && !Invalid) {
8231 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
8232 << D.getCXXScopeSpec().getRange();
8236 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
8237 D.getSourceRange().getBegin(),
8238 D.getIdentifierLoc(),
8241 ExDecl->setInvalidDecl();
8243 // Add the exception declaration into this scope.
8245 PushOnScopeChains(ExDecl, S);
8247 CurContext->addDecl(ExDecl);
8249 ProcessDeclAttributes(S, ExDecl, D);
8253 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
8255 Expr *AssertMessageExpr_,
8256 SourceLocation RParenLoc) {
8257 StringLiteral *AssertMessage = cast<StringLiteral>(AssertMessageExpr_);
8259 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent()) {
8260 llvm::APSInt Value(32);
8261 if (!AssertExpr->isIntegerConstantExpr(Value, Context)) {
8262 Diag(StaticAssertLoc,
8263 diag::err_static_assert_expression_is_not_constant) <<
8264 AssertExpr->getSourceRange();
8269 Diag(StaticAssertLoc, diag::err_static_assert_failed)
8270 << AssertMessage->getString() << AssertExpr->getSourceRange();
8274 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
8277 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
8278 AssertExpr, AssertMessage, RParenLoc);
8280 CurContext->addDecl(Decl);
8284 /// \brief Perform semantic analysis of the given friend type declaration.
8286 /// \returns A friend declaration that.
8287 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation FriendLoc,
8288 TypeSourceInfo *TSInfo) {
8289 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
8291 QualType T = TSInfo->getType();
8292 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
8294 if (!getLangOptions().CPlusPlus0x) {
8295 // C++03 [class.friend]p2:
8296 // An elaborated-type-specifier shall be used in a friend declaration
8299 // * The class-key of the elaborated-type-specifier is required.
8300 if (!ActiveTemplateInstantiations.empty()) {
8301 // Do not complain about the form of friend template types during
8302 // template instantiation; we will already have complained when the
8303 // template was declared.
8304 } else if (!T->isElaboratedTypeSpecifier()) {
8305 // If we evaluated the type to a record type, suggest putting
8307 if (const RecordType *RT = T->getAs<RecordType>()) {
8308 RecordDecl *RD = RT->getDecl();
8310 std::string InsertionText = std::string(" ") + RD->getKindName();
8312 Diag(TypeRange.getBegin(), diag::ext_unelaborated_friend_type)
8313 << (unsigned) RD->getTagKind()
8315 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(FriendLoc),
8318 Diag(FriendLoc, diag::ext_nonclass_type_friend)
8320 << SourceRange(FriendLoc, TypeRange.getEnd());
8322 } else if (T->getAs<EnumType>()) {
8323 Diag(FriendLoc, diag::ext_enum_friend)
8325 << SourceRange(FriendLoc, TypeRange.getEnd());
8329 // C++0x [class.friend]p3:
8330 // If the type specifier in a friend declaration designates a (possibly
8331 // cv-qualified) class type, that class is declared as a friend; otherwise,
8332 // the friend declaration is ignored.
8334 // FIXME: C++0x has some syntactic restrictions on friend type declarations
8335 // in [class.friend]p3 that we do not implement.
8337 return FriendDecl::Create(Context, CurContext, FriendLoc, TSInfo, FriendLoc);
8340 /// Handle a friend tag declaration where the scope specifier was
8342 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
8343 unsigned TagSpec, SourceLocation TagLoc,
8345 IdentifierInfo *Name, SourceLocation NameLoc,
8346 AttributeList *Attr,
8347 MultiTemplateParamsArg TempParamLists) {
8348 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8350 bool isExplicitSpecialization = false;
8351 bool Invalid = false;
8353 if (TemplateParameterList *TemplateParams
8354 = MatchTemplateParametersToScopeSpecifier(TagLoc, NameLoc, SS,
8355 TempParamLists.get(),
8356 TempParamLists.size(),
8358 isExplicitSpecialization,
8360 if (TemplateParams->size() > 0) {
8361 // This is a declaration of a class template.
8365 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc,
8366 SS, Name, NameLoc, Attr,
8367 TemplateParams, AS_public,
8368 TempParamLists.size() - 1,
8369 (TemplateParameterList**) TempParamLists.release()).take();
8371 // The "template<>" header is extraneous.
8372 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
8373 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
8374 isExplicitSpecialization = true;
8378 if (Invalid) return 0;
8380 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
8382 bool isAllExplicitSpecializations = true;
8383 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
8384 if (TempParamLists.get()[I]->size()) {
8385 isAllExplicitSpecializations = false;
8390 // FIXME: don't ignore attributes.
8392 // If it's explicit specializations all the way down, just forget
8393 // about the template header and build an appropriate non-templated
8394 // friend. TODO: for source fidelity, remember the headers.
8395 if (isAllExplicitSpecializations) {
8396 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8397 ElaboratedTypeKeyword Keyword
8398 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8399 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
8404 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8405 if (isa<DependentNameType>(T)) {
8406 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8407 TL.setKeywordLoc(TagLoc);
8408 TL.setQualifierLoc(QualifierLoc);
8409 TL.setNameLoc(NameLoc);
8411 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
8412 TL.setKeywordLoc(TagLoc);
8413 TL.setQualifierLoc(QualifierLoc);
8414 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(NameLoc);
8417 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8419 Friend->setAccess(AS_public);
8420 CurContext->addDecl(Friend);
8424 // Handle the case of a templated-scope friend class. e.g.
8425 // template <class T> class A<T>::B;
8426 // FIXME: we don't support these right now.
8427 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8428 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
8429 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8430 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
8431 TL.setKeywordLoc(TagLoc);
8432 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8433 TL.setNameLoc(NameLoc);
8435 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
8437 Friend->setAccess(AS_public);
8438 Friend->setUnsupportedFriend(true);
8439 CurContext->addDecl(Friend);
8444 /// Handle a friend type declaration. This works in tandem with
8447 /// Notes on friend class templates:
8449 /// We generally treat friend class declarations as if they were
8450 /// declaring a class. So, for example, the elaborated type specifier
8451 /// in a friend declaration is required to obey the restrictions of a
8452 /// class-head (i.e. no typedefs in the scope chain), template
8453 /// parameters are required to match up with simple template-ids, &c.
8454 /// However, unlike when declaring a template specialization, it's
8455 /// okay to refer to a template specialization without an empty
8456 /// template parameter declaration, e.g.
8457 /// friend class A<T>::B<unsigned>;
8458 /// We permit this as a special case; if there are any template
8459 /// parameters present at all, require proper matching, i.e.
8460 /// template <> template <class T> friend class A<int>::B;
8461 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
8462 MultiTemplateParamsArg TempParams) {
8463 SourceLocation Loc = DS.getSourceRange().getBegin();
8465 assert(DS.isFriendSpecified());
8466 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8468 // Try to convert the decl specifier to a type. This works for
8469 // friend templates because ActOnTag never produces a ClassTemplateDecl
8470 // for a TUK_Friend.
8471 Declarator TheDeclarator(DS, Declarator::MemberContext);
8472 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
8473 QualType T = TSI->getType();
8474 if (TheDeclarator.isInvalidType())
8477 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
8480 // This is definitely an error in C++98. It's probably meant to
8481 // be forbidden in C++0x, too, but the specification is just
8484 // The problem is with declarations like the following:
8485 // template <T> friend A<T>::foo;
8486 // where deciding whether a class C is a friend or not now hinges
8487 // on whether there exists an instantiation of A that causes
8488 // 'foo' to equal C. There are restrictions on class-heads
8489 // (which we declare (by fiat) elaborated friend declarations to
8490 // be) that makes this tractable.
8492 // FIXME: handle "template <> friend class A<T>;", which
8493 // is possibly well-formed? Who even knows?
8494 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
8495 Diag(Loc, diag::err_tagless_friend_type_template)
8496 << DS.getSourceRange();
8500 // C++98 [class.friend]p1: A friend of a class is a function
8501 // or class that is not a member of the class . . .
8502 // This is fixed in DR77, which just barely didn't make the C++03
8503 // deadline. It's also a very silly restriction that seriously
8504 // affects inner classes and which nobody else seems to implement;
8505 // thus we never diagnose it, not even in -pedantic.
8507 // But note that we could warn about it: it's always useless to
8508 // friend one of your own members (it's not, however, worthless to
8509 // friend a member of an arbitrary specialization of your template).
8512 if (unsigned NumTempParamLists = TempParams.size())
8513 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
8515 TempParams.release(),
8517 DS.getFriendSpecLoc());
8519 D = CheckFriendTypeDecl(DS.getFriendSpecLoc(), TSI);
8524 D->setAccess(AS_public);
8525 CurContext->addDecl(D);
8530 Decl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D, bool IsDefinition,
8531 MultiTemplateParamsArg TemplateParams) {
8532 const DeclSpec &DS = D.getDeclSpec();
8534 assert(DS.isFriendSpecified());
8535 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
8537 SourceLocation Loc = D.getIdentifierLoc();
8538 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
8539 QualType T = TInfo->getType();
8541 // C++ [class.friend]p1
8542 // A friend of a class is a function or class....
8543 // Note that this sees through typedefs, which is intended.
8544 // It *doesn't* see through dependent types, which is correct
8545 // according to [temp.arg.type]p3:
8546 // If a declaration acquires a function type through a
8547 // type dependent on a template-parameter and this causes
8548 // a declaration that does not use the syntactic form of a
8549 // function declarator to have a function type, the program
8551 if (!T->isFunctionType()) {
8552 Diag(Loc, diag::err_unexpected_friend);
8554 // It might be worthwhile to try to recover by creating an
8555 // appropriate declaration.
8559 // C++ [namespace.memdef]p3
8560 // - If a friend declaration in a non-local class first declares a
8561 // class or function, the friend class or function is a member
8562 // of the innermost enclosing namespace.
8563 // - The name of the friend is not found by simple name lookup
8564 // until a matching declaration is provided in that namespace
8565 // scope (either before or after the class declaration granting
8567 // - If a friend function is called, its name may be found by the
8568 // name lookup that considers functions from namespaces and
8569 // classes associated with the types of the function arguments.
8570 // - When looking for a prior declaration of a class or a function
8571 // declared as a friend, scopes outside the innermost enclosing
8572 // namespace scope are not considered.
8574 CXXScopeSpec &SS = D.getCXXScopeSpec();
8575 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8576 DeclarationName Name = NameInfo.getName();
8579 // Check for unexpanded parameter packs.
8580 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
8581 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
8582 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
8585 // The context we found the declaration in, or in which we should
8586 // create the declaration.
8589 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8592 // FIXME: there are different rules in local classes
8594 // There are four cases here.
8595 // - There's no scope specifier, in which case we just go to the
8596 // appropriate scope and look for a function or function template
8597 // there as appropriate.
8598 // Recover from invalid scope qualifiers as if they just weren't there.
8599 if (SS.isInvalid() || !SS.isSet()) {
8600 // C++0x [namespace.memdef]p3:
8601 // If the name in a friend declaration is neither qualified nor
8602 // a template-id and the declaration is a function or an
8603 // elaborated-type-specifier, the lookup to determine whether
8604 // the entity has been previously declared shall not consider
8605 // any scopes outside the innermost enclosing namespace.
8606 // C++0x [class.friend]p11:
8607 // If a friend declaration appears in a local class and the name
8608 // specified is an unqualified name, a prior declaration is
8609 // looked up without considering scopes that are outside the
8610 // innermost enclosing non-class scope. For a friend function
8611 // declaration, if there is no prior declaration, the program is
8613 bool isLocal = cast<CXXRecordDecl>(CurContext)->isLocalClass();
8614 bool isTemplateId = D.getName().getKind() == UnqualifiedId::IK_TemplateId;
8616 // Find the appropriate context according to the above.
8619 // Skip class contexts. If someone can cite chapter and verse
8620 // for this behavior, that would be nice --- it's what GCC and
8621 // EDG do, and it seems like a reasonable intent, but the spec
8622 // really only says that checks for unqualified existing
8623 // declarations should stop at the nearest enclosing namespace,
8624 // not that they should only consider the nearest enclosing
8626 while (DC->isRecord())
8627 DC = DC->getParent();
8629 LookupQualifiedName(Previous, DC);
8631 // TODO: decide what we think about using declarations.
8632 if (isLocal || !Previous.empty())
8636 if (isa<TranslationUnitDecl>(DC)) break;
8638 if (DC->isFileContext()) break;
8640 DC = DC->getParent();
8643 // C++ [class.friend]p1: A friend of a class is a function or
8644 // class that is not a member of the class . . .
8645 // C++0x changes this for both friend types and functions.
8646 // Most C++ 98 compilers do seem to give an error here, so
8648 if (!Previous.empty() && DC->Equals(CurContext)
8649 && !getLangOptions().CPlusPlus0x)
8650 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8652 DCScope = getScopeForDeclContext(S, DC);
8654 // - There's a non-dependent scope specifier, in which case we
8655 // compute it and do a previous lookup there for a function
8656 // or function template.
8657 } else if (!SS.getScopeRep()->isDependent()) {
8658 DC = computeDeclContext(SS);
8661 if (RequireCompleteDeclContext(SS, DC)) return 0;
8663 LookupQualifiedName(Previous, DC);
8665 // Ignore things found implicitly in the wrong scope.
8666 // TODO: better diagnostics for this case. Suggesting the right
8667 // qualified scope would be nice...
8668 LookupResult::Filter F = Previous.makeFilter();
8669 while (F.hasNext()) {
8670 NamedDecl *D = F.next();
8671 if (!DC->InEnclosingNamespaceSetOf(
8672 D->getDeclContext()->getRedeclContext()))
8677 if (Previous.empty()) {
8679 Diag(Loc, diag::err_qualified_friend_not_found) << Name << T;
8683 // C++ [class.friend]p1: A friend of a class is a function or
8684 // class that is not a member of the class . . .
8685 if (DC->Equals(CurContext))
8686 Diag(DS.getFriendSpecLoc(), diag::err_friend_is_member);
8688 // - There's a scope specifier that does not match any template
8689 // parameter lists, in which case we use some arbitrary context,
8690 // create a method or method template, and wait for instantiation.
8691 // - There's a scope specifier that does match some template
8692 // parameter lists, which we don't handle right now.
8695 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
8698 if (!DC->isRecord()) {
8699 // This implies that it has to be an operator or function.
8700 if (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ||
8701 D.getName().getKind() == UnqualifiedId::IK_DestructorName ||
8702 D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId) {
8703 Diag(Loc, diag::err_introducing_special_friend) <<
8704 (D.getName().getKind() == UnqualifiedId::IK_ConstructorName ? 0 :
8705 D.getName().getKind() == UnqualifiedId::IK_DestructorName ? 1 : 2);
8710 bool Redeclaration = false;
8711 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, T, TInfo, Previous,
8712 move(TemplateParams),
8717 assert(ND->getDeclContext() == DC);
8718 assert(ND->getLexicalDeclContext() == CurContext);
8720 // Add the function declaration to the appropriate lookup tables,
8721 // adjusting the redeclarations list as necessary. We don't
8722 // want to do this yet if the friending class is dependent.
8724 // Also update the scope-based lookup if the target context's
8725 // lookup context is in lexical scope.
8726 if (!CurContext->isDependentContext()) {
8727 DC = DC->getRedeclContext();
8728 DC->makeDeclVisibleInContext(ND, /* Recoverable=*/ false);
8729 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
8730 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
8733 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
8734 D.getIdentifierLoc(), ND,
8735 DS.getFriendSpecLoc());
8736 FrD->setAccess(AS_public);
8737 CurContext->addDecl(FrD);
8739 if (ND->isInvalidDecl())
8740 FrD->setInvalidDecl();
8743 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
8744 FD = FTD->getTemplatedDecl();
8746 FD = cast<FunctionDecl>(ND);
8748 // Mark templated-scope function declarations as unsupported.
8749 if (FD->getNumTemplateParameterLists())
8750 FrD->setUnsupportedFriend(true);
8756 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
8757 AdjustDeclIfTemplate(Dcl);
8759 FunctionDecl *Fn = dyn_cast<FunctionDecl>(Dcl);
8761 Diag(DelLoc, diag::err_deleted_non_function);
8764 if (const FunctionDecl *Prev = Fn->getPreviousDeclaration()) {
8765 Diag(DelLoc, diag::err_deleted_decl_not_first);
8766 Diag(Prev->getLocation(), diag::note_previous_declaration);
8767 // If the declaration wasn't the first, we delete the function anyway for
8770 Fn->setDeletedAsWritten();
8773 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
8774 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Dcl);
8777 if (MD->getParent()->isDependentType()) {
8779 MD->setExplicitlyDefaulted();
8783 CXXSpecialMember Member = getSpecialMember(MD);
8784 if (Member == CXXInvalid) {
8785 Diag(DefaultLoc, diag::err_default_special_members);
8790 MD->setExplicitlyDefaulted();
8792 // If this definition appears within the record, do the checking when
8793 // the record is complete.
8794 const FunctionDecl *Primary = MD;
8795 if (MD->getTemplatedKind() != FunctionDecl::TK_NonTemplate)
8796 // Find the uninstantiated declaration that actually had the '= default'
8798 MD->getTemplateInstantiationPattern()->isDefined(Primary);
8800 if (Primary == Primary->getCanonicalDecl())
8804 case CXXDefaultConstructor: {
8805 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8806 CheckExplicitlyDefaultedDefaultConstructor(CD);
8807 if (!CD->isInvalidDecl())
8808 DefineImplicitDefaultConstructor(DefaultLoc, CD);
8812 case CXXCopyConstructor: {
8813 CXXConstructorDecl *CD = cast<CXXConstructorDecl>(MD);
8814 CheckExplicitlyDefaultedCopyConstructor(CD);
8815 if (!CD->isInvalidDecl())
8816 DefineImplicitCopyConstructor(DefaultLoc, CD);
8820 case CXXCopyAssignment: {
8821 CheckExplicitlyDefaultedCopyAssignment(MD);
8822 if (!MD->isInvalidDecl())
8823 DefineImplicitCopyAssignment(DefaultLoc, MD);
8827 case CXXDestructor: {
8828 CXXDestructorDecl *DD = cast<CXXDestructorDecl>(MD);
8829 CheckExplicitlyDefaultedDestructor(DD);
8830 if (!DD->isInvalidDecl())
8831 DefineImplicitDestructor(DefaultLoc, DD);
8835 case CXXMoveConstructor:
8836 case CXXMoveAssignment:
8837 Diag(Dcl->getLocation(), diag::err_defaulted_move_unsupported);
8841 // FIXME: Do the rest once we have move functions
8845 Diag(DefaultLoc, diag::err_default_special_members);
8849 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
8850 for (Stmt::child_range CI = S->children(); CI; ++CI) {
8851 Stmt *SubStmt = *CI;
8854 if (isa<ReturnStmt>(SubStmt))
8855 Self.Diag(SubStmt->getSourceRange().getBegin(),
8856 diag::err_return_in_constructor_handler);
8857 if (!isa<Expr>(SubStmt))
8858 SearchForReturnInStmt(Self, SubStmt);
8862 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
8863 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
8864 CXXCatchStmt *Handler = TryBlock->getHandler(I);
8865 SearchForReturnInStmt(*this, Handler);
8869 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
8870 const CXXMethodDecl *Old) {
8871 QualType NewTy = New->getType()->getAs<FunctionType>()->getResultType();
8872 QualType OldTy = Old->getType()->getAs<FunctionType>()->getResultType();
8874 if (Context.hasSameType(NewTy, OldTy) ||
8875 NewTy->isDependentType() || OldTy->isDependentType())
8878 // Check if the return types are covariant
8879 QualType NewClassTy, OldClassTy;
8881 /// Both types must be pointers or references to classes.
8882 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
8883 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
8884 NewClassTy = NewPT->getPointeeType();
8885 OldClassTy = OldPT->getPointeeType();
8887 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
8888 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
8889 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
8890 NewClassTy = NewRT->getPointeeType();
8891 OldClassTy = OldRT->getPointeeType();
8896 // The return types aren't either both pointers or references to a class type.
8897 if (NewClassTy.isNull()) {
8898 Diag(New->getLocation(),
8899 diag::err_different_return_type_for_overriding_virtual_function)
8900 << New->getDeclName() << NewTy << OldTy;
8901 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8906 // C++ [class.virtual]p6:
8907 // If the return type of D::f differs from the return type of B::f, the
8908 // class type in the return type of D::f shall be complete at the point of
8909 // declaration of D::f or shall be the class type D.
8910 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
8911 if (!RT->isBeingDefined() &&
8912 RequireCompleteType(New->getLocation(), NewClassTy,
8913 PDiag(diag::err_covariant_return_incomplete)
8914 << New->getDeclName()))
8918 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
8919 // Check if the new class derives from the old class.
8920 if (!IsDerivedFrom(NewClassTy, OldClassTy)) {
8921 Diag(New->getLocation(),
8922 diag::err_covariant_return_not_derived)
8923 << New->getDeclName() << NewTy << OldTy;
8924 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8928 // Check if we the conversion from derived to base is valid.
8929 if (CheckDerivedToBaseConversion(NewClassTy, OldClassTy,
8930 diag::err_covariant_return_inaccessible_base,
8931 diag::err_covariant_return_ambiguous_derived_to_base_conv,
8932 // FIXME: Should this point to the return type?
8933 New->getLocation(), SourceRange(), New->getDeclName(), 0)) {
8934 // FIXME: this note won't trigger for delayed access control
8935 // diagnostics, and it's impossible to get an undelayed error
8936 // here from access control during the original parse because
8937 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
8938 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8943 // The qualifiers of the return types must be the same.
8944 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
8945 Diag(New->getLocation(),
8946 diag::err_covariant_return_type_different_qualifications)
8947 << New->getDeclName() << NewTy << OldTy;
8948 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8953 // The new class type must have the same or less qualifiers as the old type.
8954 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
8955 Diag(New->getLocation(),
8956 diag::err_covariant_return_type_class_type_more_qualified)
8957 << New->getDeclName() << NewTy << OldTy;
8958 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
8965 /// \brief Mark the given method pure.
8967 /// \param Method the method to be marked pure.
8969 /// \param InitRange the source range that covers the "0" initializer.
8970 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
8971 SourceLocation EndLoc = InitRange.getEnd();
8972 if (EndLoc.isValid())
8973 Method->setRangeEnd(EndLoc);
8975 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
8980 if (!Method->isInvalidDecl())
8981 Diag(Method->getLocation(), diag::err_non_virtual_pure)
8982 << Method->getDeclName() << InitRange;
8986 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse
8987 /// an initializer for the out-of-line declaration 'Dcl'. The scope
8988 /// is a fresh scope pushed for just this purpose.
8990 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
8991 /// static data member of class X, names should be looked up in the scope of
8993 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
8994 // If there is no declaration, there was an error parsing it.
8995 if (D == 0 || D->isInvalidDecl()) return;
8997 // We should only get called for declarations with scope specifiers, like:
8999 assert(D->isOutOfLine());
9000 EnterDeclaratorContext(S, D->getDeclContext());
9003 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
9004 /// initializer for the out-of-line declaration 'D'.
9005 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
9006 // If there is no declaration, there was an error parsing it.
9007 if (D == 0 || D->isInvalidDecl()) return;
9009 assert(D->isOutOfLine());
9010 ExitDeclaratorContext(S);
9013 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
9014 /// C++ if/switch/while/for statement.
9015 /// e.g: "if (int x = f()) {...}"
9016 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
9018 // The declarator shall not specify a function or an array.
9019 // The type-specifier-seq shall not contain typedef and shall not declare a
9020 // new class or enumeration.
9021 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
9022 "Parser allowed 'typedef' as storage class of condition decl.");
9024 TagDecl *OwnedTag = 0;
9025 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
9026 QualType Ty = TInfo->getType();
9028 if (Ty->isFunctionType()) { // The declarator shall not specify a function...
9029 // We exit without creating a CXXConditionDeclExpr because a FunctionDecl
9030 // would be created and CXXConditionDeclExpr wants a VarDecl.
9031 Diag(D.getIdentifierLoc(), diag::err_invalid_use_of_function_type)
9032 << D.getSourceRange();
9033 return DeclResult();
9034 } else if (OwnedTag && OwnedTag->isDefinition()) {
9035 // The type-specifier-seq shall not declare a new class or enumeration.
9036 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_condition);
9039 Decl *Dcl = ActOnDeclarator(S, D);
9041 return DeclResult();
9046 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
9047 bool DefinitionRequired) {
9048 // Ignore any vtable uses in unevaluated operands or for classes that do
9049 // not have a vtable.
9050 if (!Class->isDynamicClass() || Class->isDependentContext() ||
9051 CurContext->isDependentContext() ||
9052 ExprEvalContexts.back().Context == Unevaluated)
9055 // Try to insert this class into the map.
9056 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9057 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
9058 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
9060 // If we already had an entry, check to see if we are promoting this vtable
9061 // to required a definition. If so, we need to reappend to the VTableUses
9062 // list, since we may have already processed the first entry.
9063 if (DefinitionRequired && !Pos.first->second) {
9064 Pos.first->second = true;
9066 // Otherwise, we can early exit.
9071 // Local classes need to have their virtual members marked
9072 // immediately. For all other classes, we mark their virtual members
9073 // at the end of the translation unit.
9074 if (Class->isLocalClass())
9075 MarkVirtualMembersReferenced(Loc, Class);
9077 VTableUses.push_back(std::make_pair(Class, Loc));
9080 bool Sema::DefineUsedVTables() {
9081 if (VTableUses.empty())
9084 // Note: The VTableUses vector could grow as a result of marking
9085 // the members of a class as "used", so we check the size each
9086 // time through the loop and prefer indices (with are stable) to
9087 // iterators (which are not).
9088 bool DefinedAnything = false;
9089 for (unsigned I = 0; I != VTableUses.size(); ++I) {
9090 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
9094 SourceLocation Loc = VTableUses[I].second;
9096 // If this class has a key function, but that key function is
9097 // defined in another translation unit, we don't need to emit the
9098 // vtable even though we're using it.
9099 const CXXMethodDecl *KeyFunction = Context.getKeyFunction(Class);
9100 if (KeyFunction && !KeyFunction->hasBody()) {
9101 switch (KeyFunction->getTemplateSpecializationKind()) {
9102 case TSK_Undeclared:
9103 case TSK_ExplicitSpecialization:
9104 case TSK_ExplicitInstantiationDeclaration:
9105 // The key function is in another translation unit.
9108 case TSK_ExplicitInstantiationDefinition:
9109 case TSK_ImplicitInstantiation:
9110 // We will be instantiating the key function.
9113 } else if (!KeyFunction) {
9114 // If we have a class with no key function that is the subject
9115 // of an explicit instantiation declaration, suppress the
9116 // vtable; it will live with the explicit instantiation
9118 bool IsExplicitInstantiationDeclaration
9119 = Class->getTemplateSpecializationKind()
9120 == TSK_ExplicitInstantiationDeclaration;
9121 for (TagDecl::redecl_iterator R = Class->redecls_begin(),
9122 REnd = Class->redecls_end();
9124 TemplateSpecializationKind TSK
9125 = cast<CXXRecordDecl>(*R)->getTemplateSpecializationKind();
9126 if (TSK == TSK_ExplicitInstantiationDeclaration)
9127 IsExplicitInstantiationDeclaration = true;
9128 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9129 IsExplicitInstantiationDeclaration = false;
9134 if (IsExplicitInstantiationDeclaration)
9138 // Mark all of the virtual members of this class as referenced, so
9139 // that we can build a vtable. Then, tell the AST consumer that a
9140 // vtable for this class is required.
9141 DefinedAnything = true;
9142 MarkVirtualMembersReferenced(Loc, Class);
9143 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
9144 Consumer.HandleVTable(Class, VTablesUsed[Canonical]);
9146 // Optionally warn if we're emitting a weak vtable.
9147 if (Class->getLinkage() == ExternalLinkage &&
9148 Class->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
9149 if (!KeyFunction || (KeyFunction->hasBody() && KeyFunction->isInlined()))
9150 Diag(Class->getLocation(), diag::warn_weak_vtable) << Class;
9155 return DefinedAnything;
9158 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
9159 const CXXRecordDecl *RD) {
9160 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
9161 e = RD->method_end(); i != e; ++i) {
9162 CXXMethodDecl *MD = *i;
9164 // C++ [basic.def.odr]p2:
9165 // [...] A virtual member function is used if it is not pure. [...]
9166 if (MD->isVirtual() && !MD->isPure())
9167 MarkDeclarationReferenced(Loc, MD);
9170 // Only classes that have virtual bases need a VTT.
9171 if (RD->getNumVBases() == 0)
9174 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
9175 e = RD->bases_end(); i != e; ++i) {
9176 const CXXRecordDecl *Base =
9177 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
9178 if (Base->getNumVBases() == 0)
9180 MarkVirtualMembersReferenced(Loc, Base);
9184 /// SetIvarInitializers - This routine builds initialization ASTs for the
9185 /// Objective-C implementation whose ivars need be initialized.
9186 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
9187 if (!getLangOptions().CPlusPlus)
9189 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
9190 llvm::SmallVector<ObjCIvarDecl*, 8> ivars;
9191 CollectIvarsToConstructOrDestruct(OID, ivars);
9194 llvm::SmallVector<CXXCtorInitializer*, 32> AllToInit;
9195 for (unsigned i = 0; i < ivars.size(); i++) {
9196 FieldDecl *Field = ivars[i];
9197 if (Field->isInvalidDecl())
9200 CXXCtorInitializer *Member;
9201 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
9202 InitializationKind InitKind =
9203 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
9205 InitializationSequence InitSeq(*this, InitEntity, InitKind, 0, 0);
9206 ExprResult MemberInit =
9207 InitSeq.Perform(*this, InitEntity, InitKind, MultiExprArg());
9208 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
9209 // Note, MemberInit could actually come back empty if no initialization
9210 // is required (e.g., because it would call a trivial default constructor)
9211 if (!MemberInit.get() || MemberInit.isInvalid())
9215 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
9217 MemberInit.takeAs<Expr>(),
9219 AllToInit.push_back(Member);
9221 // Be sure that the destructor is accessible and is marked as referenced.
9222 if (const RecordType *RecordTy
9223 = Context.getBaseElementType(Field->getType())
9224 ->getAs<RecordType>()) {
9225 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
9226 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
9227 MarkDeclarationReferenced(Field->getLocation(), Destructor);
9228 CheckDestructorAccess(Field->getLocation(), Destructor,
9229 PDiag(diag::err_access_dtor_ivar)
9230 << Context.getBaseElementType(Field->getType()));
9234 ObjCImplementation->setIvarInitializers(Context,
9235 AllToInit.data(), AllToInit.size());
9240 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
9241 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
9242 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
9243 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
9245 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9247 if (Ctor->isInvalidDecl())
9250 const FunctionDecl *FNTarget = 0;
9251 CXXConstructorDecl *Target;
9253 // We ignore the result here since if we don't have a body, Target will be
9255 (void)Ctor->getTargetConstructor()->hasBody(FNTarget);
9257 = const_cast<CXXConstructorDecl*>(cast_or_null<CXXConstructorDecl>(FNTarget));
9259 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
9260 // Avoid dereferencing a null pointer here.
9261 *TCanonical = Target ? Target->getCanonicalDecl() : 0;
9263 if (!Current.insert(Canonical))
9266 // We know that beyond here, we aren't chaining into a cycle.
9267 if (!Target || !Target->isDelegatingConstructor() ||
9268 Target->isInvalidDecl() || Valid.count(TCanonical)) {
9269 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9272 // We've hit a cycle.
9273 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
9274 Current.count(TCanonical)) {
9275 // If we haven't diagnosed this cycle yet, do so now.
9276 if (!Invalid.count(TCanonical)) {
9277 S.Diag((*Ctor->init_begin())->getSourceLocation(),
9278 diag::warn_delegating_ctor_cycle)
9281 // Don't add a note for a function delegating directo to itself.
9282 if (TCanonical != Canonical)
9283 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
9285 CXXConstructorDecl *C = Target;
9286 while (C->getCanonicalDecl() != Canonical) {
9287 (void)C->getTargetConstructor()->hasBody(FNTarget);
9288 assert(FNTarget && "Ctor cycle through bodiless function");
9291 = const_cast<CXXConstructorDecl*>(cast<CXXConstructorDecl>(FNTarget));
9292 S.Diag(C->getLocation(), diag::note_which_delegates_to);
9296 for (CI = Current.begin(), CE = Current.end(); CI != CE; ++CI)
9297 Invalid.insert(*CI);
9300 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
9305 void Sema::CheckDelegatingCtorCycles() {
9306 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
9308 llvm::SmallSet<CXXConstructorDecl*, 4>::iterator CI = Current.begin(),
9311 for (llvm::SmallVector<CXXConstructorDecl*, 4>::iterator
9312 I = DelegatingCtorDecls.begin(),
9313 E = DelegatingCtorDecls.end();
9315 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
9318 for (CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
9319 (*CI)->setInvalidDecl();