[clang] [Clang][C++2d] Implement defaulted postfix increment and decrement operators (P3668R4) (PR #229560)
Corentin Jabot via cfe-commits
cfe-commits at lists.llvm.org
Thu Oct 29 03:23:06 PDT 2026
================
@@ -9481,6 +9507,552 @@ ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
return ExceptSpec;
}
+static Sema::ImplicitExceptionSpecification
+ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
+ FunctionDecl *FD,
+ DefaultedComparisonKind DCK) {
+ auto BuildBody = [&](SourceLocation BodyLoc) {
+ CXXRecordDecl *RD =
+ cast<CXXRecordDecl>(FD->getFriendObjectKind() == Decl::FOK_None
+ ? FD->getDeclContext()
+ : FD->getLexicalDeclContext());
+ return DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
+ };
+ return computeExceptionSpecFromSynthesizedBody(S, Loc, FD, BuildBody);
+}
+
+// C++2d [over.inc.default]: defaulted postfix increment and decrement operator
+// functions (P3668R4).
+
+namespace {
+/// Information about a defaulted postfix increment or decrement operator
+/// function, as determined by analyzeDefaultedPostfixOperator.
+struct DefaultedPostfixOperatorInfo {
+ /// Whether the function should be defined as deleted.
+ bool Deleted = false;
+ /// Whether every function invoked by the implicit definition is constexpr.
+ bool Constexpr = true;
+};
+} // namespace
+
+/// Get the type of the first parameter of a postfix increment or decrement
+/// operator function, where the implicit object parameter (if any) is
+/// considered to be the first parameter.
+static QualType getPostfixOperatorFirstParamType(const FunctionDecl *FD) {
+ if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
+ return MD->getFunctionObjectParameterReferenceType();
+ return FD->getParamDecl(0)->getType();
+}
+
+/// Determine whether the implicit definition of the defaulted postfix
+/// increment or decrement operator function \p FD can direct-initialize a
+/// variable of class type \p C from the lvalue \p Obj of type \p C, and then
+/// destroy it, using functions that are usable from the current context.
+///
+/// \p CheckConstexpr is called on each constructor the initialization invokes.
+/// If \p Diagnose is true, explain why the copy or destruction is not possible.
+static bool canCopyAndDestroyForDefaultedPostfixOperator(
+ Sema &S, FunctionDecl *FD, CXXRecordDecl *RD, QualType C, Expr *Obj,
+ bool Diagnose,
+ llvm::function_ref<void(const FunctionDecl *, unsigned)> CheckConstexpr) {
+ SourceLocation Loc = FD->getLocation();
+ auto InaccessibleDiag = [&](unsigned Step) {
+ return Diagnose
+ ? S.PDiag(diag::note_defaulted_postfix_operator_inaccessible)
+ << FD << Step
+ : S.PDiag();
+ };
+
+ InitializedEntity Entity = InitializedEntity::InitializeTemporary(C);
+ InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
+ InitializationSequence Seq(S, Entity, InitKind, Obj);
+ if (Seq.Failed()) {
+ // FIXME: This emits errors rather than notes explaining why the function
+ // is deleted.
+ if (Diagnose)
+ Seq.Diagnose(S, Entity, InitKind, Obj);
+ return false;
+ }
+ for (const InitializationSequence::Step &Step : Seq.steps()) {
+ if (Step.Kind != InitializationSequence::SK_ConstructorInitialization)
+ continue;
+ if (!S.isMemberAccessibleForDeletion(
+ RD, Step.Function.FoundDecl, C, Loc,
+ InaccessibleDiag(diag::DefaultedPostfixOperatorStep::Constructor)))
+ return false;
+ CheckConstexpr(Step.Function.Function,
+ diag::DefaultedPostfixOperatorStep::Constructor);
+ }
+
+ CXXDestructorDecl *Dtor = S.LookupDestructor(RD);
+ if (!Dtor)
+ return true;
+ if (Dtor->isDeleted()) {
+ if (Diagnose) {
+ S.Diag(Loc, diag::note_defaulted_function_calls_deleted)
+ << FD << diag::DefaultedPostfixOperatorStep::Destructor
+ << /*complete object*/ 0;
+ S.NoteDeletedFunction(Dtor);
+ }
+ return false;
+ }
+ return S.isMemberAccessibleForDeletion(
+ RD, DeclAccessPair::make(Dtor, Dtor->getAccess()), C, Loc,
+ InaccessibleDiag(diag::DefaultedPostfixOperatorStep::Destructor));
+}
+
+/// Determine whether a defaulted postfix increment or decrement operator
+/// function for type \p C should be defined as deleted, as specified in C++2d
+/// [over.inc.default]p2, and whether every function it would invoke is
+/// constexpr.
+///
+/// If \p Diagnose is true, explain why the function is defined as deleted or,
+/// if it is not, which of the functions it invokes are not constexpr.
+static DefaultedPostfixOperatorInfo
+analyzeDefaultedPostfixOperator(Sema &S, FunctionDecl *FD,
+ PostfixOperatorKind Kind, QualType C,
+ bool Diagnose) {
+ DefaultedPostfixOperatorInfo Info;
+ SourceLocation Loc = FD->getLocation();
+
+ // C++2d [over.inc.default]p1:
+ // Name lookups and access checks in the implicit definition of a defaulted
+ // postfix increment or decrement operator function are performed from a
+ // context equivalent to its function-body.
+ Sema::ContextRAII SavedContext(S, FD);
+
+ // Let c be an lvalue of type C. c stands for the first parameter (or the
+ // implicit object), which is always an lvalue when named in the function
+ // body, even if it is declared as an rvalue reference.
+ OpaqueValueExpr Obj(Loc, C, VK_LValue);
+ Expr *Args[] = {&Obj};
+
+ auto Deleted = [&] {
+ Info.Deleted = true;
+ return Info;
+ };
+ auto InaccessibleDiag = [&](unsigned Step) {
+ return Diagnose
+ ? S.PDiag(diag::note_defaulted_postfix_operator_inaccessible)
+ << FD << Step
+ : S.PDiag();
+ };
+ auto NoteCallsDeleted = [&](unsigned Step, FunctionDecl *Callee) {
+ if (!Diagnose)
+ return;
+ S.Diag(Loc, diag::note_defaulted_function_calls_deleted)
+ << FD << Step << /*complete object*/ 0;
+ if (Callee)
+ S.NoteDeletedFunction(Callee);
+ };
+ // The non-constexpr functions are only worth explaining if the function is
+ // not deleted, which isn't known until the end of the analysis.
+ SmallVector<std::pair<const FunctionDecl *, unsigned>, 2> NonConstexpr;
+ auto CheckConstexpr = [&](const FunctionDecl *Callee, unsigned Step) {
+ if (Callee->isConstexpr())
+ return;
+ Info.Constexpr = false;
+ NonConstexpr.push_back({Callee, Step});
+ };
+
+ // C++2d [over.inc.default]p2:
+ // A defaulted postfix increment or decrement operator function for a type
+ // C is defined as deleted if
+ // -- C is a class type for which overload resolution, as applied to
+ // direct-initialization of a variable of type C from an lvalue of
+ // type C, does not result in a usable candidate,
+ // -- C has a destructor that is deleted or inaccessible from the context
+ // of the function-body, or
+ CXXRecordDecl *RD = C->getAsCXXRecordDecl();
+ if (RD && !canCopyAndDestroyForDefaultedPostfixOperator(
+ S, FD, RD, C, &Obj, Diagnose, CheckConstexpr))
+ return Deleted();
+
+ // -- for an lvalue c of type C, overload resolution as applied to ++c for a
+ // postfix increment operator function or --c for a postfix decrement
+ // operator function does not result in a usable candidate.
+ bool IsIncrement = Kind == PostfixOperatorKind::Increment;
+ unsigned PrefixStep =
+ IsIncrement ? diag::DefaultedPostfixOperatorStep::PrefixIncrement
+ : diag::DefaultedPostfixOperatorStep::PrefixDecrement;
+ UnresolvedSet<16> Fns;
+ if (auto *DFI = FD->getDefaultedOrDeletedInfo())
+ Fns.assign(DFI->getUnqualifiedLookups().begin(),
+ DFI->getUnqualifiedLookups().end());
+ OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
+ S.LookupOverloadedUnaryOp(
+ CandidateSet, IsIncrement ? OO_PlusPlus : OO_MinusMinus, Fns, Args);
+
+ OverloadCandidateSet::iterator Best;
+ switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
+ case OR_Success:
+ if (FunctionDecl *Prefix = Best->Function) {
+ // Only a member of C can be inaccessible here; the non-member
+ // candidates were found by unqualified lookup and ADL.
+ if (RD && Best->FoundDecl.getDecl() &&
+ Best->FoundDecl.getDecl()->isCXXClassMember() &&
+ !S.isMemberAccessibleForDeletion(RD, Best->FoundDecl, C, Loc,
+ InaccessibleDiag(PrefixStep)))
+ return Deleted();
+ CheckConstexpr(Prefix, PrefixStep);
+ } else if (!Best->Conversions.empty() &&
+ Best->Conversions[0].isUserDefined()) {
+ // A built-in candidate, reached through a conversion function.
+ CheckConstexpr(Best->Conversions[0].UserDefined.ConversionFunction,
+ diag::DefaultedPostfixOperatorStep::ConversionFunction);
+ }
+ break;
+
+ case OR_Ambiguous:
+ if (Diagnose)
+ CandidateSet.NoteCandidates(
+ PartialDiagnosticAt(
+ Loc, S.PDiag(diag::note_defaulted_postfix_operator_ambiguous)
+ << FD << !IsIncrement << C),
+ S, OCD_AmbiguousCandidates, Args, IsIncrement ? "++" : "--", Loc);
+ return Deleted();
+
+ case OR_Deleted:
+ NoteCallsDeleted(PrefixStep, Best->Function);
+ return Deleted();
+
+ case OR_No_Viable_Function:
+ // Don't list the non-viable candidates: like for any other unary operator,
+ // the candidate notes can't sensibly describe an arity mismatch for a
+ // member postfix operator (whose object argument is not a parameter).
+ if (Diagnose)
+ S.Diag(Loc, diag::note_defaulted_postfix_operator_no_viable)
+ << FD << !IsIncrement << C;
+ return Deleted();
+ }
+
+ if (Diagnose)
+ for (auto [Callee, Step] : NonConstexpr)
+ S.Diag(Callee->getLocation(),
+ diag::note_defaulted_postfix_operator_not_constexpr_here)
+ << Step;
+ return Info;
+}
+
+bool Sema::CheckExplicitlyDefaultedPostfixOperator(Scope *S, FunctionDecl *FD,
+ PostfixOperatorKind Kind) {
+ assert(Kind != PostfixOperatorKind::None &&
+ "not a defaulted postfix operator");
+ bool IsIncrement = Kind == PostfixOperatorKind::Increment;
+
+ // Perform the unqualified lookup of the prefix operator that the implicit
+ // definition needs. C++2d [over.inc.default]p1:
+ // Name lookups and access checks in the implicit definition of a defaulted
+ // postfix increment or decrement operator function are performed from a
+ // context equivalent to its function-body.
+ // The lookup is performed from S, not from CurContext. S is either the body
+ // scope of an out-of-line definition, or the scope of the class in which the
+ // function is defaulted on its first declaration; for a lookup that ignores
+ // member functions, both are equivalent to the function-body.
+ if (S) {
+ assert((S->getEntity() == FD ||
+ S->getEntity() == FD->getLexicalDeclContext()) &&
+ "lookup scope is not equivalent to the function-body");
+ UnresolvedSet<16> Operators;
+ LookupOverloadedOperatorName(IsIncrement ? OO_PlusPlus : OO_MinusMinus, S,
+ Operators);
+ FD->setDefaultedOrDeletedInfo(
+ FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
+ Context, Operators.pairs(), CurFPFeatureOverrides()));
+ }
+
+ // C++2d [over.inc.default]p1:
+ // A defaulted postfix increment or decrement operator function for a type
+ // C shall be a non-template function that
+ // -- has a first parameter of type "reference to C" or a first parameter
+ // of type "reference to volatile C", where the implicit object
+ // parameter (if any) is considered to be the first parameter,
+ // -- is defined as defaulted in C or in a context where C is complete,
+ // and
+ // -- has a declared return type of C.
+ auto *MD = dyn_cast<CXXMethodDecl>(FD);
+ ParmVarDecl *FirstParam = FD->getParamDecl(0);
+ QualType FirstParamType = getPostfixOperatorFirstParamType(FD);
+ QualType ReturnType = FD->getDeclaredReturnType();
+
+ // If the first parameter type is dependent, or the function is in a dependent
+ // context, defer all checks until instantiation.
+ if (FirstParamType->isDependentType() || FD->isDependentContext())
+ return false;
+
+ // Check the type of the first parameter and determine the type C from it.
+ // For a member function, C is the enclosing class. For a non-member function,
+ // C is the class or enumeration type of its first parameter;
+ // CheckOverloadedOperatorDeclaration has already required it to have one.
+ QualType Referent = FirstParamType.getNonReferenceType();
+ QualType C = MD ? Context.getCanonicalTagType(MD->getParent())
+ : Referent.getUnqualifiedType();
+ assert((C->isRecordType() || C->isEnumeralType()) &&
+ "postfix operator for a non-class, non-enumeration type");
+
+ // The first parameter must be a reference to C, which may be
+ // volatile-qualified but not const-qualified.
+ if (!FirstParamType->isReferenceType() ||
+ !Context.hasSameUnqualifiedType(Referent, C) ||
+ Referent.isConstQualified()) {
+ if (MD && MD->isImplicitObjectMemberFunction()) {
+ // The implicit object parameter is always a reference to the enclosing
+ // class, so the only possible problem is a const qualifier.
+ Diag(MD->getLocation(), diag::err_defaulted_postfix_operator_const)
+ << (int)Kind;
+ } else {
+ Diag(FirstParam->getBeginLoc(),
+ diag::err_defaulted_postfix_operator_param)
+ << (int)Kind << !MD << FirstParamType
+ << Context.getLValueReferenceType(C) << FirstParam->getSourceRange();
+ }
+ return true;
+ }
+
+ // A deduced return type is never permitted. Allowing it would need P2952R2
+ // (auto& operator=(X&&) = default), which is not part of the standard.
+ if (ReturnType->getContainedDeducedType()) {
+ Diag(FD->getLocation(),
+ diag::err_defaulted_postfix_operator_deduced_return_type)
+ << (int)Kind << FD->getReturnTypeSourceRange();
+ return true;
+ }
+
+ // -- has a declared return type of C.
+ if (!Context.hasSameType(ReturnType, C)) {
+ Diag(FD->getLocation(), diag::err_defaulted_postfix_operator_return_type)
+ << (int)Kind << C << ReturnType << FD->getReturnTypeSourceRange();
+ return true;
+ }
+
+ // -- is defined as defaulted in C or in a context where C is complete
+ if (RequireCompleteType(FD->getLocation(), C,
+ diag::err_defaulted_postfix_operator_incomplete,
+ (int)Kind))
+ return true;
+
+ // Determine whether the function should be defined as deleted.
+ DefaultedPostfixOperatorInfo Info =
+ analyzeDefaultedPostfixOperator(*this, FD, Kind, C, /*Diagnose=*/false);
+
+ bool First = FD == FD->getFirstDecl();
+
+ if (!First) {
+ if (Info.Deleted) {
+ // C++11 [dcl.fct.def.default]p4:
+ // [For a] user-provided explicitly-defaulted function [...] if such a
+ // function is implicitly defined as deleted, the program is ill-formed.
+ //
+ // This is really just a consequence of the general rule that you can
+ // only delete a function on its first declaration.
+ Diag(FD->getLocation(),
+ diag::err_non_first_default_postfix_operator_deletes)
+ << (int)Kind;
+ analyzeDefaultedPostfixOperator(*this, FD, Kind, C, /*Diagnose=*/true);
+ return true;
+ }
+ if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
+ // C++2d [over.inc.default]p1:
+ // A definition of a postfix increment or decrement operator as
+ // defaulted that appears in a class shall be the first declaration of
+ // that function.
+ Diag(FD->getLocation(),
+ diag::err_non_first_default_postfix_operator_in_class)
+ << (int)Kind;
+ Diag(FD->getCanonicalDecl()->getLocation(),
+ diag::note_previous_declaration);
+ return true;
+ }
+ }
+
+ // If we want to delete the function, then do so; there's nothing else to
+ // check in that case.
+ if (Info.Deleted) {
+ SetDeclDeleted(FD, FD->getLocation());
+ if (!inTemplateInstantiation() && !FD->isImplicit()) {
+ Diag(FD->getLocation(), diag::warn_defaulted_postfix_operator_deleted)
+ << (int)Kind;
+ analyzeDefaultedPostfixOperator(*this, FD, Kind, C, /*Diagnose=*/true);
+ if (FD->getDefaultLoc().isValid())
+ Diag(FD->getDefaultLoc(), diag::note_replace_equals_default_to_delete)
+ << FixItHint::CreateReplacement(FD->getDefaultLoc(), "delete");
+ }
+ return false;
+ }
+
+ // C++2a [dcl.fct.def.default]p3 [P2002R0]:
+ // An explicitly-defaulted function that is not defined as deleted may be
+ // declared constexpr or consteval only if it is constexpr-compatible.
+ // By analogy with C++2a [class.compare.default]p3, we consider a defaulted
+ // postfix operator to be constexpr-compatible if its parameter and return
+ // types are literal types and no overload resolution performed when
+ // determining whether to delete it results in a non-constexpr function.
+ //
+ // C++23 [dcl.fct.def.default]p3 [P2448R2] removed this restriction: a
+ // defaulted function may always be declared constexpr.
+ if (FD->isConstexpr() && !getLangOpts().CPlusPlus23 &&
+ !FD->isTemplateInstantiation() &&
+ CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
+ CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
+ !Info.Constexpr) {
+ Diag(FD->getBeginLoc(),
+ diag::err_defaulted_postfix_operator_constexpr_mismatch)
+ << (int)Kind << FD->isConsteval();
+ analyzeDefaultedPostfixOperator(*this, FD, Kind, C, /*Diagnose=*/true);
+ return true;
+ }
+
+ if (First) {
+ // C++11 [dcl.fct.def.default]p5:
+ // A function explicitly defaulted on its first declaration is implicitly
+ // inline.
+ FD->setImplicitlyInline();
+
+ // C++2a [dcl.fct.def.default]p3 [P2002R0]:
+ // If a constexpr-compatible function is explicitly defaulted on its
+ // first declaration, it is implicitly considered to be constexpr.
+ // C++23 [dcl.fct.def.default]p3 [P2448R2]:
+ // A function explicitly defaulted on its first declaration is [...]
+ // implicitly constexpr if it is constexpr-suitable.
+ // A postfix operator function is always constexpr-suitable. The implicit
+ // definition declares a variable, so it can only be constexpr in C++14
+ // and later, and a virtual function can only be constexpr in C++20 and
+ // later.
+ if (!FD->isConstexpr() && getLangOpts().CPlusPlus14 &&
+ (getLangOpts().CPlusPlus20 || !MD || !MD->isVirtual()) &&
+ (getLangOpts().CPlusPlus23 ||
+ (Info.Constexpr &&
+ CheckConstexprReturnType(*this, FD, CheckConstexprKind::CheckValid) &&
+ CheckConstexprParameterTypes(*this, FD,
+ CheckConstexprKind::CheckValid))))
+ FD->setConstexprKind(ConstexprSpecKind::Constexpr);
+
+ // C++2d [except.spec]p10:
+ // The exception specification for [...] a postfix increment or decrement
+ // operator function without a noexcept-specifier that is defaulted on
+ // its first declaration is potentially-throwing if and only if any
+ // expression in the implicit definition is potentially-throwing.
+ if (FD->getExceptionSpecType() == EST_None) {
+ auto *FPT = FD->getType()->castAs<FunctionProtoType>();
+ FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
+ EPI.ExceptionSpec.Type = EST_Unevaluated;
+ EPI.ExceptionSpec.SourceDecl = FD;
+ FD->setType(Context.getFunctionType(FPT->getReturnType(),
+ FPT->getParamTypes(), EPI));
+ }
+ }
+
+ return false;
+}
+
+/// Build the body of a defaulted postfix increment or decrement operator
+/// function. C++2d [over.inc.default]p3:
+/// The implicit definition of a defaulted postfix increment or decrement
+/// operator function F that is not defined as deleted for a type C is
+/// equivalent to:
+/// C tmp(c);
+/// ++c; // or --c
+/// return tmp;
+/// where tmp is a variable defined for exposition only, and c is an lvalue
+/// that denotes *this if F is an implicit object member function, or the
+/// first parameter of F otherwise.
+static StmtResult buildDefaultedPostfixOperatorBody(Sema &S, FunctionDecl *FD,
+ PostfixOperatorKind Kind,
+ SourceLocation Loc) {
+ Sema::CompoundScopeRAII CompoundScope(S);
+
+ // Build an expression denoting 'c'.
+ auto BuildObject = [&]() -> ExprResult {
+ if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);
+ MD && MD->isImplicitObjectMemberFunction()) {
+ ExprResult This = S.ActOnCXXThis(Loc);
+ if (This.isInvalid())
+ return ExprError();
+ return S.CreateBuiltinUnaryOp(Loc, UO_Deref, This.get());
+ }
+ ParmVarDecl *Param = FD->getParamDecl(0);
+ return S.BuildDeclarationNameExpr(
+ CXXScopeSpec(), DeclarationNameInfo(Param->getDeclName(), Loc), Param);
+ };
+
+ // C tmp(c);
+ ExprResult Init = BuildObject();
+ if (Init.isInvalid())
+ return StmtError();
+ QualType C = FD->getReturnType();
+ IdentifierInfo *TmpName = &S.Context.Idents.get("__tmp");
+ VarDecl *Tmp =
+ VarDecl::Create(S.Context, S.CurContext, Loc, Loc, TmpName, C,
+ S.Context.getTrivialTypeSourceInfo(C, Loc), SC_None);
----------------
cor3ntin wrote:
we should not need to name `Tmp` at all
https://github.com/llvm/llvm-project/pull/229560
More information about the cfe-commits
mailing list