[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);
----------------
cor3ntin wrote:

Can you explain `IsIncrement ? "++" : "--"` ? I'm confused how that impact the diagnostics

https://github.com/llvm/llvm-project/pull/229560


More information about the cfe-commits mailing list