[clang] [Clang-Repl] Introduce Error Recovery for Clang-Repl (PR #247062)

Vassil Vassilev via cfe-commits cfe-commits at lists.llvm.org
Thu Dec 3 02:08:41 PST 2026


https://github.com/vgvassilev updated https://github.com/llvm/llvm-project/pull/247062

>From 5d5df24d134e6f9ff4214fe74ae7bd73a48b9372 Mon Sep 17 00:00:00 2001
From: SahilPatidar <patidarsahil2001 at gmail.com>
Date: Wed, 25 Nov 2026 11:29:40 +0530
Subject: [PATCH 1/5] [Clang-Repl] Introduce Error Recovery for Clang-Repl

---
 clang/lib/Interpreter/ErrorRecovery.cpp | 1467 +++++++++++++++++++++++
 clang/lib/Interpreter/ErrorRecovery.h   |  771 ++++++++++++
 2 files changed, 2238 insertions(+)
 create mode 100644 clang/lib/Interpreter/ErrorRecovery.cpp
 create mode 100644 clang/lib/Interpreter/ErrorRecovery.h

diff --git a/clang/lib/Interpreter/ErrorRecovery.cpp b/clang/lib/Interpreter/ErrorRecovery.cpp
new file mode 100644
index 00000000000000..cd90b8152c1b62
--- /dev/null
+++ b/clang/lib/Interpreter/ErrorRecovery.cpp
@@ -0,0 +1,1467 @@
+//===--------- ErrorRecovery.cpp - Declaration State Recovery -------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception.
+//
+//===----------------------------------------------------------------------===//
+//
+// This file implements declaration state recovery for failed
+// partial translation units (PTUs), restoring declaration state to
+// the state of the previous PTU.
+//
+//===----------------------------------------------------------------------===//
+
+#include "ErrorRecovery.h"
+
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclBase.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclContextInternals.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/DeclVisitor.h"
+#include "clang/AST/GlobalDecl.h"
+#include "clang/Sema/Sema.h"
+
+#define DEBUG_TYPE "clang-repl"
+
+namespace clang {
+
+/// -----------------------------------------------------------------------
+//////////////////////// PTUMutationActions::Helpers ///////////////////////
+/// -----------------------------------------------------------------------
+
+/// ASTDeclUnmerger handles two cases based on whether a declaration should be
+/// discarded or belongs to a previous PTU: it unlinks discarded declarations
+/// from the compiler's shared state, or restores their previous state using
+/// the MutationRecord information.
+class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
+private:
+  PTUID ID;
+  IncrementalStateTracker &Tracker;
+  PTUMutationActions &Actions;
+  Sema &SemaRef;
+  SemaCacheReverter &SemaCache;
+  CodeGenerator *CodeGen;
+  MutationRecord *Rec = nullptr;
+
+  llvm::SmallPtrSet<const Decl *, 16> RepairedChains;
+  // llvm::SmallPtrSet<const DeclContext *, 8> RepairedLexicalContexts;
+
+  bool isFromThisPTU(const void *Ptr) const {
+    return Tracker.isFromThisPTU(Ptr, ID);
+  }
+
+  bool isDiscarded(const void *Ptr) const {
+    return Tracker.isFromThisPTU(Ptr, ID);
+  }
+
+  bool hasRecord() const { return Rec != nullptr; }
+
+  MutationRecord &Record() { return *Rec; }
+
+  bool hasNoPreviousDecl(const Decl *D) {
+    return D->getPreviousDecl() == nullptr;
+  }
+
+  template <typename DeclT> DeclT *findSurvivor(DeclT *D) const {
+    for (Decl *It = D->getMostRecentDecl(); It; It = It->getPreviousDecl())
+      if (!isFromThisPTU(It))
+        return dyn_cast<DeclT>(It);
+    return nullptr;
+  }
+
+  template <typename DeclT>
+  void resetRedeclLink(Redeclarable<DeclT> *DBase, DeclT *Survivor) {
+    auto *Latest = static_cast<DeclT *>(DBase);
+
+    // Rebuild First -> ... -> Survivor -> ... -> Latest as
+    // First -> ... -> Survivor.
+    Latest->getFirstDecl()->RedeclLink.setLatest(Survivor);
+
+    // The chain is circular: a withdrawn declaration still linked into it can
+    // never walk back around to itself, so redecls() on one would not
+    // terminate. Give each withdrawn declaration a chain of its own.
+    for (DeclT *Dead = Latest; Dead != Survivor;) {
+      DeclT *Next = Dead->getPreviousDecl();
+      Dead->First = Dead;
+      Dead->RedeclLink =
+          Redeclarable<DeclT>::LatestDeclLink(Tracker.getASTContext());
+      Dead = Next;
+    }
+  }
+
+  template <typename DeclT> void unlinkRedeclChain(DeclT *D) {
+    if (hasNoPreviousDecl(D))
+      return;
+    if (!RepairedChains.insert(D->getCanonicalDecl()).second)
+      return;
+    DeclT *Latest = D->getMostRecentDecl();
+    if (DeclT *Survivor = findSurvivor(D))
+      resetRedeclLink(Latest, Survivor);
+  }
+
+  /// Remove D from its DeclContext lookup map and restore the previous
+  /// declaration if it was replaced.
+  void detachFromDCLookup(NamedDecl *ND) {
+    // Find any declaration from the previous PTU in the redecl chain that may
+    // have been replaced by this declaration.
+    NamedDecl *Survivor = findSurvivor(ND);
+    DeclarationName Name = ND->getDeclName();
+
+    DeclContext *DC = ND->getDeclContext();
+    do {
+      DeclContext *Primary = DC->getPrimaryContext();
+      if (StoredDeclsMap *Map = Primary->getLookupPtr()) {
+        auto Pos = Map->find(Name);
+        if (Pos != Map->end()) {
+          StoredDeclsList &List = Pos->second;
+          List.remove(ND);
+          if (Survivor) {
+            List.addOrReplaceDecl(Survivor);
+          }
+          if (List.isNull())
+            Map->erase(Pos);
+        }
+      }
+    } while ((DC->isTransparentContext() || DC->isInlineNamespace()) &&
+             (DC = DC->getParent()));
+  }
+
+  /// Remove entry from "C"'s lookup tables
+  void removeFromLookups(NamedDecl *D) {
+    if (D->getDeclName().isEmpty())
+      return;
+
+    if (D->getDeclName().isIdentifier() && D->getDeclName().getFETokenInfo() &&
+        !D->getLangOpts().ObjC && !D->getLangOpts().CPlusPlus)
+      SemaRef.IdResolver.RemoveDecl(D);
+
+    ExternCContextDecl *ECCD = Tracker.getASTContext().getExternCContextDecl();
+    if (StoredDeclsMap *Map = ECCD->getPrimaryContext()->getLookupPtr()) {
+      auto It = Map->find(D->getDeclName());
+      if (It != Map->end())
+        It->second.remove(D);
+    }
+  }
+
+  void detachDefData(CXXRecordDecl *RD) {
+    for (auto *I : RD->redecls())
+      cast<CXXRecordDecl>(I)->DefinitionData = nullptr;
+  }
+
+  void detachCommonBase(const RedeclarableTemplateDecl *RT) {
+    for (const auto *R : RT->redecls())
+      R->Common = nullptr;
+  }
+
+  void repairLexicalChain(DeclContext *DC) {
+    Decl *Prev = nullptr;
+    for (Decl *Cur = DC->FirstDecl; Cur; Cur = Cur->getNextDeclInContext()) {
+      if (isFromThisPTU(Cur)) {
+        if (Prev) {
+          DC->LastDecl = Prev;
+          Prev->NextInContextAndBits.setPointer(nullptr);
+        } else {
+          DC->FirstDecl = DC->LastDecl = nullptr; // nothing survives
+        }
+        return;
+      }
+      Prev = Cur;
+    }
+  }
+
+  void forgetMangledNames(std::initializer_list<GlobalDecl> GDs) {
+    if (!CodeGen)
+      return;
+    // TODO: Codegen mangle name cleanup need to handle.
+  }
+
+  void forgetMangledNames(NamedDecl *ND) {
+    forgetMangledNames({GlobalDecl(ND)});
+  }
+
+  void unlinkCommon(NamedDecl *ND) {
+    removeFromLookups(ND);
+
+    Decl *Canon = ND->getCanonicalDecl();
+    if (RepairedChains.count(Canon))
+      return;
+
+    detachFromDCLookup(ND);
+  }
+
+  void VisitDeclContext(DeclContext *DC) {
+    for (Decl *D : llvm::SmallVector<Decl *, 8>(DC->decls()))
+      Visit(D);
+    repairLexicalChain(DC);
+  }
+  
+
+  void revertDefinitionArrival(VarDecl *VD) {
+    VD->setInit(nullptr);
+    VD->setInvalidDecl(false);
+  }
+
+  void revertDefinitionArrival(FunctionDecl *FD) {
+    FD->setBody(nullptr);
+    // Reset the body state so a later PTU sees this as not instantiated.
+    FD->setWillHaveBody(false);
+
+    // The reverted body may have caused a substitution failure to mark
+    // the function invalid. Clear that state as well.
+    FD->setInvalidDecl(false);
+  }
+
+  void revertDefinitionArrival(EnumDecl *ED) {
+    // Undo EnumDecl::completeDefinition() writes. PromotionType and both
+    // bit-count fields are always overwritten during completion, so they can
+    // be reset unconditionally.
+    ED->setPromotionType(QualType());
+    // resetEnumBits(*ED);
+    // EnumDecl::setNumPositiveBits/setNumNegativeBits -- private.
+    // ED->setNumPositiveBits(0);
+    // ED->setNumNegativeBits(0);
+
+    // completeDefinition() only sets IntegerType for non-fixed enums. A fixed
+    // enum may already have an IntegerType from its forward declaration, which
+    // must be preserved.
+    if (!ED->isFixed())
+      ED->setIntegerType(QualType());
+    ED->setCompleteDefinition(false);
+    ED->setBeingDefined(false);
+  }
+  void revertDefinitionArrival(CXXRecordDecl *RD) {
+    // 1. DefinitionData pointer -- back to null.
+    RD->DefinitionData = nullptr;
+
+    // 2. DeclContext member list -- back to empty.
+    RD->FirstDecl = nullptr;
+    RD->LastDecl = nullptr;
+    DeclContext *Primary = RD->getPrimaryContext();
+    if (StoredDeclsMap *Map = Primary->getLookupPtr())
+      Map->clear();
+
+    // 3. TagDecl completion bits -- back to "never started". Flipped by
+    // startDefinition()/completeDefinition().
+    RD->setBeingDefined(false);
+    RD->setCompleteDefinition(false);
+  }
+
+public:
+  friend class PTUMutationActions;
+
+  ASTDeclUnmerger(PTUID ID, IncrementalStateTracker &Tracker,
+                  PTUMutationActions &Action, Sema &SemaRef,
+                  SemaCacheReverter &SemaCache, CodeGenerator *CodeGen)
+      : ID(ID), Tracker(Tracker), Actions(Action), SemaRef(SemaRef),
+        SemaCache(SemaCache), CodeGen(CodeGen) {}
+
+  static DefinitionDataFootprint
+  createDefinitionDataFootprint(const CXXRecordDecl &RD) {
+    DefinitionDataFootprint FP;
+    const auto &Live = RD.data();
+#define FIELD(Name, Width, Merge) FP.Name = Live.Name;
+#include "clang/AST/CXXRecordDeclDefinitionBits.def"
+    return FP;
+  }
+
+  static void restoreDefinitionDataFootprint(const DefinitionDataFootprint &FP,
+                                             CXXRecordDecl &RD) {
+    auto &Live = RD.data();
+#define FIELD(Name, Width, Merge) Live.Name = FP.Name;
+#include "clang/AST/CXXRecordDeclDefinitionBits.def"
+  }
+
+  // Generic across every other footprint type exclusing DefinitionDataFootprint
+  // -- SpecializationFootprint, VarSpecializationFootprint,
+  // FunctionSpecializationFootprint, MemberSpecializationFootprint.
+  template <typename FootprintT, typename OwnerT>
+  static FootprintT createFootprint(const OwnerT &Owner) {
+    FootprintT FP;
+    FP.update(Owner);
+    return FP;
+  }
+  template <typename FootprintT, typename OwnerT>
+  static void restoreFootprint(const FootprintT &FP, OwnerT &Owner) {
+    FP.restore(Owner);
+  }
+
+  void restoreDecl(Decl *D, MutationRecord &R) {
+    Rec = &R;
+    Visit(D);
+    Rec = nullptr;
+  }
+
+  void VisitDecl(Decl *D) {
+    if (!isDiscarded(D))
+      return;
+
+    if (auto *DC = dyn_cast<DeclContext>(D))
+      VisitDeclContext(DC);
+    if (auto *ND = dyn_cast<NamedDecl>(D)) {
+      unlinkCommon(ND);
+    }
+  }
+
+  void VisitTranslationUnitDecl(TranslationUnitDecl *D) { VisitDeclContext(D); }
+  void VisitNamespaceDecl(NamespaceDecl *D);
+  void VisitCXXRecordDecl(CXXRecordDecl *RD);
+  void VisitFunctionDecl(FunctionDecl *FD);
+  void VisitCXXConstructorDecl(CXXConstructorDecl *D);
+  void VisitCXXDestructorDecl(CXXDestructorDecl *D);
+  void VisitVarDecl(VarDecl *VD);
+  void VisitEnumDecl(EnumDecl *ED);
+  void VisitClassTemplateDecl(ClassTemplateDecl *CTD);
+  void VisitFunctionTemplateDecl(FunctionTemplateDecl *FTD);
+  void VisitVarTemplateDecl(VarTemplateDecl *VTD);
+  void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
+  void VisitTypedefNameDecl(TypedefNameDecl *D);
+  void VisitUsingShadowDecl(UsingShadowDecl *D);
+};
+
+static DeclShape classifyShape(const Decl *D) {
+  // Base shape -- most-derived first.
+  if (isa<RedeclarableTemplateDecl>(D))
+    return DeclShape::Template;
+  else if (isa<EnumDecl>(D))
+    return DeclShape::Enum;
+  else if (isa<FunctionDecl>(D))
+    return DeclShape::Function;
+  else if (isa<VarDecl>(D))
+    return DeclShape::Var;
+  else if (isa<CXXRecordDecl>(D))
+    return DeclShape::Class;
+  else if (isa<TypedefDecl, TypeAliasDecl>(D))
+    return DeclShape::Typedef;
+  else
+    return DeclShape::None;
+}
+
+/// This is called when a decl is created or seen for the first time. It also
+/// checks whether the decl is still in a mutation-sensitive state, meaning that
+/// a later PTU can modify it. Because of this, we need to track its state. This
+/// function provides a single place to decide whether a decl needs to be
+/// committed or not. It is called from commitDecl to determine whether a new
+/// decl needs to be tracked.
+///
+/// This requires DeclShape S and Decl to determine which mutation kinds
+/// apply to the shape and whether they need to be tracked.
+/// In the future, if a new mutation site is found for a shape, it should be
+/// added here along with the logic to determine whether the decl is still in an
+/// open, modifiable state.
+uint32_t PTUMutationActions::DeclNeedingTracking(DeclShape S, const Decl *D) {
+  switch (S) {
+  case DeclShape::Class: {
+    const auto *RD = cast<CXXRecordDecl>(D);
+    uint32_t Kinds = 0;
+    if (RD->hasDefinition() && RD == RD->getDefinition()) {
+      // Do we really need to create a DefData chain here? Usually, an implicit
+      // decl can be mutated later after the definition. If it is already wired
+      // correctly, there is nothing to mutate or track here.
+      //
+      // Save the current DefinitionData because it may change later.
+      if (RD->needsImplicitDefaultConstructor() ||
+          RD->needsImplicitCopyConstructor() ||
+          RD->needsImplicitCopyAssignment() ||
+          RD->needsImplicitMoveConstructor() ||
+          RD->needsImplicitMoveAssignment() || RD->needsImplicitDestructor())
+        Kinds |= uint32_t(MutationKind::DefinitionData);
+    }
+    if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
+      // If SpecializationKind == TSK_ExplicitSpecialization, there is less
+      // chance that the info will be modified later, so we are all set and
+      // don't need to track it.
+      // A specialization's Kind/point-of-instantiation is overwritten in place,
+      // with no separate record of the previous value. The footprint chain is
+      // the only place where the previous value is stored.
+      if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
+        Kinds |= uint32_t(MutationKind::SpecInfo);
+    } else if (const auto *MSI = RD->getMemberSpecializationInfo()) {
+      if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
+        Kinds |= uint32_t(MutationKind::MemberSpecInfo);
+    }
+    return Kinds;
+  }
+  case DeclShape::Function: {
+    const auto *FD = cast<FunctionDecl>(D);
+    uint32_t Kinds = 0;
+    if (FD->getTemplateSpecializationInfo() &&
+        FD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
+      Kinds |= uint32_t(MutationKind::SpecInfo);
+    if (const auto *MSI = FD->getMemberSpecializationInfo()) {
+      if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
+        Kinds |= uint32_t(MutationKind::MemberSpecInfo);
+    }
+    return Kinds;
+  }
+  case DeclShape::Var: {
+    const auto *VD = cast<VarDecl>(D);
+    uint32_t Kinds = 0;
+    if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
+      if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
+        Kinds |= uint32_t(MutationKind::SpecInfo);
+    } else if (const auto *MSI = VD->getMemberSpecializationInfo()) {
+      if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
+        Kinds |= uint32_t(MutationKind::MemberSpecInfo);
+    }
+    return Kinds;
+  }
+  case DeclShape::Enum: {
+    const auto *ED = cast<EnumDecl>(D);
+    uint32_t Kinds = 0;
+    if (const auto *MSI = ED->getMemberSpecializationInfo()) {
+      // Same terminal-state exclusion as the other MSI-backed cases above.
+      if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
+        Kinds |= uint32_t(MutationKind::MemberSpecInfo);
+    }
+    return Kinds;
+  }
+  case DeclShape::None:
+    return 0;
+  }
+  return 0;
+}
+
+template <typename T>
+static bool differsFromLast(IncrementalStateTracker &Tracker, const Decl *Owner,
+                            MutationKind K, const T &LiveValue) {
+  const auto *Last = Tracker.getFootprints().mostRecent<T>(Owner, K);
+  assert(Last && "baseline missing at verify time");
+  return !Last || *Last != LiveValue;
+}
+
+template <typename FootprintT, typename OwnerT>
+static FootprintT Footprint(const OwnerT &Owner) {
+  FootprintT FP;
+  FP.update(Owner);
+  return FP;
+}
+
+/// The single place to check whether a kind has actually changed.
+///
+/// This handles both listener-less kinds and listener-unconfirmed mutations
+/// (currently SpecInfo and MemberSpecInfo). Mutations can be detected by
+/// both SweepTracker and the listener re-check. SweepTracker tracks hidden
+/// and listener-unconfirmed mutations in case the listener misses them. If the
+/// listener catches a mutation, it is removed from SweepTracker; see
+/// PTUStateInfo::verifyMutations. both use this functionality to verify
+/// mutation kind.
+///
+/// This check uses the decl shape and mutation kind to determine whether the
+/// decl has changed from its previous state.
+///
+/// Similarly, if a new hidden or listener-unconfirmed mutation is introduced
+/// in DeclNeedingTracking, and we need to determine whether it changed the
+/// previous state, the corresponding logic should be added here too
+/// when the kind is categorized as a hidden mutation from the listener.
+uint32_t PTUMutationActions::confirmMutation(const Decl *D, DeclShape S,
+                                             uint32_t FlaggedKinds) {
+  uint32_t Verified = 0;
+  switch (S) {
+  case DeclShape::Class: {
+    const auto *RD = cast<CXXRecordDecl>(D);
+    if (FlaggedKinds & uint32_t(MutationKind::SpecInfo)) {
+      if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RD))
+        if (differsFromLast(Tracker, Spec, MutationKind::SpecInfo,
+                            Footprint<SpecializationFootprint>(*Spec)))
+          Verified |= uint32_t(MutationKind::SpecInfo);
+    } else if (FlaggedKinds & uint32_t(MutationKind::MemberSpecInfo)) {
+      if (differsFromLast(Tracker, RD, MutationKind::MemberSpecInfo,
+                          Footprint<MemberSpecializationFootprint>(*RD)))
+        Verified |= uint32_t(MutationKind::MemberSpecInfo);
+    }
+    break;
+  }
+  case DeclShape::Function: {
+    const auto *FD = cast<FunctionDecl>(D);
+    if (FlaggedKinds & uint32_t(MutationKind::SpecInfo)) {
+      if (differsFromLast(Tracker, FD, MutationKind::SpecInfo,
+                          Footprint<FunctionSpecializationFootprint>(*FD)))
+        Verified |= uint32_t(MutationKind::SpecInfo);
+    } else if (FlaggedKinds & uint32_t(MutationKind::MemberSpecInfo)) {
+      if (differsFromLast(Tracker, FD, MutationKind::MemberSpecInfo,
+                          Footprint<MemberSpecializationFootprint>(*FD)))
+        Verified |= uint32_t(MutationKind::MemberSpecInfo);
+    }
+    break;
+  }
+  case DeclShape::Var: {
+    const auto *VD = cast<VarDecl>(D);
+    if (FlaggedKinds & uint32_t(MutationKind::SpecInfo)) {
+      if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
+        if (differsFromLast(Tracker, Spec, MutationKind::SpecInfo,
+                            Footprint<VarSpecializationFootprint>(*Spec)))
+          Verified |= uint32_t(MutationKind::SpecInfo);
+    } else if (FlaggedKinds & uint32_t(MutationKind::MemberSpecInfo)) {
+      if (differsFromLast(Tracker, VD, MutationKind::MemberSpecInfo,
+                          Footprint<MemberSpecializationFootprint>(*VD)))
+        Verified |= uint32_t(MutationKind::MemberSpecInfo);
+    }
+    break;
+  }
+  case DeclShape::Enum: {
+    const auto *ED = cast<EnumDecl>(D);
+    if (FlaggedKinds & uint32_t(MutationKind::MemberSpecInfo)) {
+      if (differsFromLast(Tracker, ED, MutationKind::MemberSpecInfo,
+                          Footprint<MemberSpecializationFootprint>(*ED)))
+        Verified |= uint32_t(MutationKind::MemberSpecInfo);
+    }
+    break;
+  }
+  case DeclShape::None:
+    break;
+  }
+  return Verified;
+}
+
+/// A single function called during commit and restore (when the PTU is
+/// uncommitted).
+///
+/// This is where we check for any hidden mutations previously registered with
+/// SweepTracker. If a mutation is confirmed, we record it in the
+/// PTUStateInfo mutation set via OnConfirmed.
+template <typename OnConfirmedFn>
+void SweepTracker::sweep(PTUMutationActions &Act, OnConfirmedFn OnConfirmed) {
+  for (auto &Entry : Active) {
+    const Decl *D = Entry.getFirst();
+    uint32_t StillOpen = Entry.getSecond();
+    DeclShape S = classifyShape(D);
+    if (uint32_t Newly = Act.confirmMutation(D, S, StillOpen)) {
+      OnConfirmed(D, S, Newly);
+    }
+  }
+}
+
+/// These kinds have listeners, but listeners alone cannot reliably detect
+/// real changes. Compare the current value with the last known value, as we
+/// do for kinds without listeners.
+///
+/// These kinds are also checked by the sweep to catch changes that listeners
+/// miss or report incorrectly.
+///
+/// Currently, SpecInfo/MemberSpecInfo are tracked from the listener side.
+/// This applies when the listener reports that a mutation may have happened
+/// but it has not been confirmed yet.
+///
+/// Not all hidden mutations are tracked here; they are tracked in
+/// SweepTracker. This logic applies only to listener-unconfirmed mutations.
+static constexpr uint32_t KindsNeedingVerification =
+    uint32_t(MutationKind::SpecInfo) | uint32_t(MutationKind::MemberSpecInfo);
+
+/// Start tracking D for mutation kinds that need verification.
+/// Called when a new mutation is committed or an undone mutation is restored.
+/// we apply this for listener unconfirmed cases.
+void PTUMutationActions::trackForSweep(const Decl *D, uint32_t Kinds) {
+  if (uint32_t Flag = Kinds & KindsNeedingVerification)
+    HiddenMutationTracker.track(D, Flag);
+}
+
+/// Stop tracking Decl D when it no longer needs verification.
+/// Re-check DeclNeedingTracking to see if a later PTU can still update D.
+void PTUMutationActions::untrackIfClosed(const Decl *D, DeclShape S,
+                                         uint32_t Confirmed) {
+  uint32_t Flag = Confirmed & KindsNeedingVerification;
+  if (!Flag || !HiddenMutationTracker.isTrackedFor(D, Flag))
+    return;
+  uint32_t StillOpen = DeclNeedingTracking(S, D) & Flag;
+  uint32_t Closed = Flag & ~StillOpen;
+  if (Closed)
+    HiddenMutationTracker.untrack(D, Closed);
+}
+
+// Shared sweep-tracking logic(track/untrack) for
+// commitClass/commitFunction/commitVar/commitEnum.
+void PTUMutationActions::syncSweepTracking(const Decl *D, DeclShape S,
+                                           uint32_t Kinds, bool IsNew) {
+  if (IsNew)
+    trackForSweep(D, Kinds);
+  else
+    untrackIfClosed(D, S, Kinds);
+}
+
+/// Verify recorded mutations and remove any false mutation ones. If none of a
+/// decl’s mutation kinds are confirmed, remove the record entirely so
+/// restore() does not pop chain entries that were never written.
+void PTUStateInfo::verifyMutations(PTUMutationActions &Actions) {
+  Mutations.remove_if([&](auto &Entry) -> bool {
+    const Decl *D = Entry.first;
+    MutationRecord &Rec = Entry.second;
+    uint32_t Flagged = Rec.MutationFlags & KindsNeedingVerification;
+    if (!Flagged)
+      return false;
+    uint32_t Confirmed = Actions.confirmMutation(D, Rec.S, Flagged);
+    /// untrack kind from SweepTracker if confirmed.
+    Actions.untrackIfClosed(D, Rec.S, Confirmed);
+    Rec.MutationFlags = (Rec.MutationFlags & ~Flagged) | Confirmed;
+    return Rec.MutationFlags == 0;
+  });
+}
+
+static bool isReachableFromThisTU(const Decl *D,
+                                  const TranslationUnitDecl *ThisTU) {
+  const DeclContext *DC = D->getLexicalDeclContext();
+  for (; DC; DC = DC->getLexicalParent())
+    if (DC == ThisTU)
+      return DC->containsDecl(const_cast<Decl *>(D));
+  return false;
+}
+
+/// -----------------------------------------------------------------------
+//////////////////////// PTUMutationActions::commit ///////////////////////
+/// -----------------------------------------------------------------------
+
+/// These are the places where the incremental state of a declaration is
+/// registered based on its DeclShape.
+///
+/// For a declaration created in the current PTU, its state is committed
+/// to the tracker. For an existing declaration modified in the current
+/// PTU, its previous state is recorded so it can be restored on undo.
+///
+/// The idea is to keep state tracking limited to a small set of known
+/// mutation sites for each DeclShape, instead of tracking changes
+/// everywhere in Clang.
+///
+/// Currently, this covers Class, Function, Enum, Template, etc. Each
+/// DeclShape is associated with the mutation kinds that need to be tracked.
+///
+/// When adding a new mutation site, it should be handled according to
+/// the corresponding DeclShape and mutation kind.
+
+bool PTUMutationActions::shouldRecurseInto(const Decl *D) {
+  if (isa<NamespaceDecl>(D))
+    return true;
+  if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
+    return RD->isCompleteDefinition();
+  return false;
+}
+
+void PTUMutationActions::VisitDeclContext(const DeclContext *DC) {
+  for (const Decl *D : DC->decls()) {
+    if (shouldRecurseInto(D))
+      VisitDeclContext(cast<DeclContext>(D));
+    commitDecl(D, nullptr);
+  }
+}
+
+void PTUMutationActions::VisitCXXRecordDecl(const CXXRecordDecl *RD) {
+  MutationRecord &Rec = Record();
+
+  if (Rec.has(MutationKind::DefinitionInstantiate) ||
+      Rec.has(MutationKind::DefinitionData)) {
+    Tracker.commitFootprint(
+        RD, MutationKind::DefinitionData, CurrentID(),
+        ASTDeclUnmerger::createDefinitionDataFootprint(*RD));
+
+    if (Rec.has(MutationKind::DefinitionInstantiate)) {
+      if (RD->getMemberSpecializationInfo())
+        VisitDeclContext(cast<DeclContext>(RD));
+    }
+  }
+
+  if (Rec.has(MutationKind::SpecInfo)) {
+    const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RD);
+    if (Spec) {
+      Tracker.commitFootprint(
+          Spec, MutationKind::SpecInfo, CurrentID(),
+          ASTDeclUnmerger::createFootprint<SpecializationFootprint>(*Spec));
+      /// Member declarations are instantiated eagerly with the class
+      /// definition, egardless of TSK; only their definitions are deferred.
+      ///
+      /// Walk them here so each member’s MemberSpecializationInfo is tracked as
+      /// soon as it is created.
+      bool IsNew = Tracker.isFromCurrentPTU(Spec);
+      if (IsNew && Spec->getSpecializationKind() == TSK_ImplicitInstantiation)
+        VisitDeclContext(cast<DeclContext>(Spec));
+      // FIXME: Remove syncSweepTracking from all places
+      // (SpecInfo/MemberSpecInfo) once the missing notifier
+      // (ASTMutationListener) is added for (SpecInfo/MemberSpecInfo).
+      syncSweepTracking(Spec, DeclShape::Class,
+                        uint32_t(MutationKind::SpecInfo), IsNew);
+    }
+  }
+
+  if (Rec.has(MutationKind::MemberSpecInfo)) {
+    if (RD->getMemberSpecializationInfo()) {
+      Tracker.commitFootprint(
+          RD, MutationKind::MemberSpecInfo, CurrentID(),
+          ASTDeclUnmerger::createFootprint<MemberSpecializationFootprint>(*RD));
+      syncSweepTracking(RD, DeclShape::Class,
+                        uint32_t(MutationKind::MemberSpecInfo),
+                        Tracker.isFromCurrentPTU(RD));
+    }
+  }
+}
+
+void PTUMutationActions::VisitFunctionDecl(const FunctionDecl *FD) {
+  MutationRecord &Rec = Record();
+  if (Rec.has(MutationKind::SpecInfo)) {
+    assert(FD->getTemplateSpecializationKind() != TSK_Undeclared &&
+           "SpecInfoChanged on a function with no specialization info");
+    Tracker.commitFootprint(
+        FD, MutationKind::SpecInfo, CurrentID(),
+        ASTDeclUnmerger::createFootprint<FunctionSpecializationFootprint>(*FD));
+    syncSweepTracking(FD, DeclShape::Function, uint32_t(MutationKind::SpecInfo),
+                      Tracker.isFromCurrentPTU(FD));
+  }
+
+  if (Rec.has(MutationKind::MemberSpecInfo)) {
+    if (FD->getMemberSpecializationInfo()) {
+      Tracker.commitFootprint(
+          FD, MutationKind::MemberSpecInfo, CurrentID(),
+          ASTDeclUnmerger::createFootprint<MemberSpecializationFootprint>(*FD));
+      syncSweepTracking(FD, DeclShape::Function,
+                        uint32_t(MutationKind::MemberSpecInfo),
+                        Tracker.isFromCurrentPTU(FD));
+    }
+  }
+}
+
+void PTUMutationActions::VisitVarDecl(const VarDecl *VD) {
+  MutationRecord &Rec = Record();
+
+  if (Rec.has(MutationKind::SpecInfo)) {
+    const auto *Spec = cast<VarTemplateSpecializationDecl>(VD);
+    Tracker.commitFootprint(
+        Spec, MutationKind::SpecInfo, CurrentID(),
+        ASTDeclUnmerger::createFootprint<VarSpecializationFootprint>(*Spec));
+    syncSweepTracking(Spec, DeclShape::Var, uint32_t(MutationKind::SpecInfo),
+                      Tracker.isFromCurrentPTU(Spec));
+  }
+
+  if (Rec.has(MutationKind::MemberSpecInfo)) {
+    if (VD->getMemberSpecializationInfo()) {
+      Tracker.commitFootprint(
+          VD, MutationKind::MemberSpecInfo, CurrentID(),
+          ASTDeclUnmerger::createFootprint<MemberSpecializationFootprint>(*VD));
+      syncSweepTracking(VD, DeclShape::Var,
+                        uint32_t(MutationKind::MemberSpecInfo),
+                        Tracker.isFromCurrentPTU(VD));
+    }
+  }
+}
+
+void PTUMutationActions::VisitEnumDecl(const EnumDecl *ED) {
+  MutationRecord &Rec = Record();
+  if (Rec.has(MutationKind::MemberSpecInfo)) {
+    if (ED->getMemberSpecializationInfo()) {
+      Tracker.commitFootprint(
+          ED, MutationKind::MemberSpecInfo, CurrentID(),
+          ASTDeclUnmerger::createFootprint<MemberSpecializationFootprint>(*ED));
+      syncSweepTracking(ED, DeclShape::Enum,
+                        uint32_t(MutationKind::MemberSpecInfo),
+                        Tracker.isFromCurrentPTU(ED));
+    }
+  }
+}
+
+void PTUMutationActions::commitDecl(const Decl *D, MutationRecord *R) {
+  if (!D->isDefinedOutsideFunctionOrMethod())
+    return;
+
+  MutationRecord NewRec;
+  if (!R) {
+    DeclShape S = classifyShape(D);
+    if (S == DeclShape::None)
+      return;
+
+    // Handle cases where baseline info needs to be created, as well as cases
+    // where a declaration has already completed all required mutations. For
+    // example, member specs may already be fully populated, so we should avoid
+    // creating spec info blindly.
+    uint32_t Kinds = DeclNeedingTracking(S, D);
+    if (!Kinds)
+      return;
+
+    NewRec.add(Kinds);
+    R = &NewRec;
+  }
+
+  MutationRecord *OldRec = Rec;
+  Rec = R;
+  Visit(D);
+  Rec = OldRec;
+}
+
+void PTUMutationActions::commit(TranslationUnitDecl *ThisTU) {
+  PTUStateInfo &Cur = Tracker.current();
+  assert(!Cur.Commited && "Current PTUState is already commited");
+  Cur.ThisPTU = ThisTU;
+
+  LLVM_DEBUG({ llvm::dbgs() << "Commit ThisTU\n"; });
+
+  // 1. Verify any unconfirmed mutation (see : KindsNeedingVerification)
+  // reported by the listener, whether true or false.
+  Cur.verifyMutations(*this);
+  // 2. Catch any mutation-sensitive state of Decl from previous PTUs that
+  //    ASTMutationListener cannot catch if it was registered during a
+  //    previous PTU commit.
+  Tracker.getHiddenMutationTracker().sweep(
+      *this, [&](const Decl *D, DeclShape S, uint32_t K) {
+        Cur.noteMutated(D, S, K);
+      });
+
+  // 3. Update the tracking state of declarations from the previous PTU using
+  //    Cur.Mutations reported by ASTMutationListener and HiddenMutationTracker.
+  for (auto &[D, Rec] : Cur.Mutations)
+    commitDecl(D, &Rec);
+
+  // 4. Cur.ImplicitDecls: Declarations created by this PTU. Register them for
+  //    tracking if they have mutation-sensitive state that can be modified by
+  //    later PTUs.
+  //
+  // commitDecl: Decides what to do with declarations created by the current
+  // PTU, such as whether a declaration needs to be tracked or not.
+  for (const Decl *D : Cur.ImplicitDecls) {
+    if (isReachableFromThisTU(D, ThisTU))
+      continue;
+    if (shouldRecurseInto(D))
+      VisitDeclContext(cast<DeclContext>(D));
+    commitDecl(D, nullptr);
+  }
+
+  // Iterate over all declarations in this TU and register them whether they
+  // need explicit tracking.
+  VisitDeclContext(ThisTU);
+
+  Cur.Commited = true;
+}
+
+/// -----------------------------------------------------------------------
+//////////////////////// PTUMutationActions::restore //////////////////////
+/// -----------------------------------------------------------------------
+
+/// These are the places where we restore or undo/unlink the incremental state
+/// of a decl based on its DeclShape.
+///
+/// The same DeclShape -> mutation kind relationship used during commit is
+/// followed here. For declarations created in the current PTU, unlinks them
+/// from the compiler shared state. For existing declarations that were
+/// modified, restore brings them back to their previous state.
+///
+/// When adding a new mutation site that requires restoring or unlinking
+/// state, it should be handled according to the corresponding DeclShape
+/// and mutation kind.
+
+void ASTDeclUnmerger::VisitNamespaceDecl(NamespaceDecl *D) {
+  // we don't care about the decl which complete chain is part belong to
+  // current PTU.
+  if (!Tracker.isFromThisPTU(D->getCanonicalDecl(), ID))
+    VisitDeclContext(D);
+  unlinkCommon(D);
+  unlinkRedeclChain(D);
+}
+
+void ASTDeclUnmerger::VisitCXXRecordDecl(CXXRecordDecl *RD) {
+  if (isDiscarded(RD)) {
+    VisitDeclContext(RD);
+    unlinkCommon(RD);
+    if (CXXRecordDecl *Def = RD->getDefinition();
+        Def && RD->getPreviousDecl() && isFromThisPTU(Def))
+      detachDefData(Def);
+    unlinkRedeclChain<TagDecl>(RD);
+    return;
+  }
+
+  if (!hasRecord())
+    return;
+
+  // else perform restoration of decl state.
+  if (Record().has(MutationKind::DefinitionInstantiate) ||
+      Record().has(MutationKind::DefinitionData)) {
+    if (Record().has(MutationKind::DefinitionInstantiate)) {
+      revertDefinitionArrival(RD);
+    } else if (const auto *Restored =
+                   Tracker.getFootprints().mostRecent<DefinitionDataFootprint>(
+                       RD, MutationKind::DefinitionData)) {
+      restoreDefinitionDataFootprint(*Restored, *RD);
+    }
+  }
+
+  if (Record().has(MutationKind::SpecInfo)) {
+    // Only a specialization can carry this kind; a plain CXXRecordDecl
+    // reaching here means a note*() wrapper passed the wrong kind.
+    auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RD);
+    assert(Spec && "SpecializationAdded noted on a non-specialization");
+    if (const SpecializationFootprint *Restored =
+            Tracker.getFootprints().mostRecent<SpecializationFootprint>(
+                Spec, MutationKind::SpecInfo))
+      restoreFootprint<SpecializationFootprint>(*Restored, *Spec);
+    Actions.trackForSweep(Spec, uint32_t(MutationKind::SpecInfo));
+  }
+
+  if (Record().has(MutationKind::MemberSpecInfo)) {
+    // A nested member of a class template – its MSI kind or
+    // point-of-instantiation changed.
+    assert(RD->getMemberSpecializationInfo());
+    if (const MemberSpecializationFootprint *Restored =
+            Tracker.getFootprints().mostRecent<MemberSpecializationFootprint>(
+                RD, MutationKind::MemberSpecInfo))
+      restoreFootprint<MemberSpecializationFootprint>(*Restored, *RD);
+    Actions.trackForSweep(RD, uint32_t(MutationKind::MemberSpecInfo));
+  }
+}
+
+void ASTDeclUnmerger::VisitFunctionDecl(FunctionDecl *FD) {
+  // unlink Discarded decl.
+  if (isDiscarded(FD)) {
+    forgetMangledNames(FD);
+    unlinkCommon(FD);
+    unlinkRedeclChain(FD);
+    return;
+  }
+
+  if (!hasRecord())
+    return;
+
+  // Restore decl state.
+
+  if (Record().has(MutationKind::DefinitionInstantiate)) {
+    if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
+      forgetMangledNames({GlobalDecl(Ctor, Ctor_Complete),
+                          GlobalDecl(Ctor, Ctor_Base),
+                          GlobalDecl(Ctor, Ctor_Comdat)});
+    } else if (CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(FD)) {
+      forgetMangledNames(
+          {GlobalDecl(Dtor, Dtor_Deleting), GlobalDecl(Dtor, Dtor_Complete),
+           GlobalDecl(Dtor, Dtor_Base), GlobalDecl(Dtor, Dtor_Comdat)});
+    }
+    revertDefinitionArrival(FD);
+    if (auto *MD = dyn_cast<CXXMethodDecl>(FD); MD && MD->isVirtual())
+      SemaCache.restoreVTableUsed(MD->getParent());
+  }
+
+  if (Record().has(MutationKind::SpecInfo)) {
+    // A function template specialization is a plain FunctionDecl carrying
+    // FunctionTemplateSpecializationInfo.
+    assert(FD->getTemplateSpecializationKind() != TSK_Undeclared &&
+           "SpecInfoChanged on a function with no specialization info");
+    if (const auto *Restored =
+            Tracker.getFootprints().mostRecent<FunctionSpecializationFootprint>(
+                FD, MutationKind::SpecInfo))
+      restoreFootprint<FunctionSpecializationFootprint>(*Restored, *FD);
+    FD->setInstantiationIsPending(false);
+    Actions.trackForSweep(FD, uint32_t(MutationKind::SpecInfo));
+  }
+
+  if (Record().has(MutationKind::MemberSpecInfo)) {
+    assert(FD->getMemberSpecializationInfo());
+    if (const auto *Restored =
+            Tracker.getFootprints().mostRecent<MemberSpecializationFootprint>(
+                FD, MutationKind::MemberSpecInfo))
+      restoreFootprint<MemberSpecializationFootprint>(*Restored, *FD);
+    FD->setInstantiationIsPending(false);
+    Actions.trackForSweep(FD, uint32_t(MutationKind::MemberSpecInfo));
+  }
+}
+
+void ASTDeclUnmerger::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
+  // Unlinking discared Decl.
+  if (isDiscarded(D)) {
+    forgetMangledNames({GlobalDecl(D, Ctor_Complete), GlobalDecl(D, Ctor_Base),
+                        GlobalDecl(D, Ctor_Comdat)});
+    unlinkCommon(D);
+    unlinkRedeclChain<FunctionDecl>(D);
+    return;
+  }
+
+  // Restore decl.
+  if (hasRecord())
+    VisitFunctionDecl(D);
+}
+
+void ASTDeclUnmerger::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
+  // Unlinking discared Decl.
+  if (isDiscarded(D)) {
+    forgetMangledNames({GlobalDecl(D, Dtor_Deleting),
+                        GlobalDecl(D, Dtor_Complete), GlobalDecl(D, Dtor_Base),
+                        GlobalDecl(D, Dtor_Comdat)});
+    unlinkCommon(D);
+    unlinkRedeclChain<FunctionDecl>(D);
+    return;
+  }
+
+  // Restore decl.
+  if (hasRecord())
+    VisitFunctionDecl(D);
+}
+
+void ASTDeclUnmerger::VisitVarDecl(VarDecl *VD) {
+  // Unlinking discared Decl.
+  if (isDiscarded(VD)) {
+    if (!isa<ParmVarDecl>(VD) && !VD->getDeclContext()->isDependentContext())
+      forgetMangledNames(VD);
+    unlinkCommon(VD);
+    unlinkRedeclChain(VD);
+    return;
+  }
+
+  if (!hasRecord())
+    return;
+
+  // Restore decl.
+
+  if (Record().has(MutationKind::DefinitionInstantiate)) {
+    revertDefinitionArrival(VD);
+    forgetMangledNames(VD);
+  }
+
+  if (Record().has(MutationKind::SpecInfo)) {
+    auto *Spec = cast<VarTemplateSpecializationDecl>(VD);
+    if (const auto *Restored =
+            Tracker.getFootprints().mostRecent<VarSpecializationFootprint>(
+                Spec, MutationKind::SpecInfo))
+      restoreFootprint<VarSpecializationFootprint>(*Restored, *Spec);
+    Actions.trackForSweep(VD, uint32_t(MutationKind::SpecInfo));
+  }
+
+  if (Record().has(MutationKind::MemberSpecInfo)) {
+    assert(VD->getMemberSpecializationInfo());
+    if (const auto *Restored =
+            Tracker.getFootprints().mostRecent<MemberSpecializationFootprint>(
+                VD, MutationKind::MemberSpecInfo))
+      restoreFootprint<MemberSpecializationFootprint>(*Restored, *VD);
+    Actions.trackForSweep(VD, uint32_t(MutationKind::MemberSpecInfo));
+  }
+}
+
+void ASTDeclUnmerger::VisitEnumDecl(EnumDecl *ED) {
+  // Unlink Discarded Decl.
+  if (isDiscarded(ED)) {
+    VisitDeclContext(ED);
+    unlinkCommon(ED);
+    unlinkRedeclChain<TagDecl>(ED);
+    return;
+  }
+
+  if (!hasRecord())
+    return;
+
+  // Restore Decl state.
+  if (Record().has(MutationKind::TypeForDecl)) {
+    // for (const TagDecl *Redecl : ED->redecls()) {
+    //   const auto *Last = Tracker.getFootprints().mostRecent<const Type *>(
+    //       Redecl, MutationKind::TypeForDecl);
+    //   TODO: need to handle?
+    // }
+  }
+
+  if (Record().has(MutationKind::DefinitionInstantiate))
+    revertDefinitionArrival(ED);
+
+  if (Record().has(MutationKind::MemberSpecInfo)) {
+    assert(ED->getMemberSpecializationInfo());
+    if (const auto *Restored =
+            Tracker.getFootprints().mostRecent<MemberSpecializationFootprint>(
+                ED, MutationKind::MemberSpecInfo))
+      restoreFootprint<MemberSpecializationFootprint>(*Restored, *ED);
+
+    Actions.trackForSweep(ED, uint32_t(MutationKind::MemberSpecInfo));
+  }
+}
+
+void ASTDeclUnmerger::VisitClassTemplateDecl(ClassTemplateDecl *CT) {
+  // Unlinking discared Decl.
+  if (isDiscarded(CT)) {
+    unlinkCommon(CT);
+    bool HasSurvivorToReplace =
+        !hasNoPreviousDecl(CT) && !isFromThisPTU(CT->getCanonicalDecl());
+    if (HasSurvivorToReplace)
+      unlinkRedeclChain(cast<RedeclarableTemplateDecl>(CT));
+
+    NamedDecl *Templated = CT->getTemplatedDecl();
+    if (auto *RD = dyn_cast<CXXRecordDecl>(Templated)) {
+      if (CXXRecordDecl *Def = RD->getDefinition(); Def && isFromThisPTU(Def))
+        detachDefData(RD);
+      if (HasSurvivorToReplace)
+        unlinkRedeclChain<TagDecl>(RD);
+    }
+  }
+
+  if (!hasRecord())
+    return;
+
+  // Restore Decl.
+  if (Record().has(MutationKind::SpecializationAdded)) {
+    auto &Specs = CT->getSpecializations();
+    while (!Specs.empty()) {
+      auto It = Specs.end();
+      --It;
+      if (!Tracker.isFromThisPTU(&*It, ID))
+        break;
+      Specs.pop_back();
+    }
+  }
+}
+
+void ASTDeclUnmerger::VisitFunctionTemplateDecl(FunctionTemplateDecl *FTD) {
+  // Unlinking discared Decl.
+  if (isDiscarded(FTD)) {
+    unlinkCommon(FTD);
+    bool HasSurvivorToReplace =
+        !hasNoPreviousDecl(FTD) && !isFromThisPTU(FTD->getCanonicalDecl());
+    if (HasSurvivorToReplace)
+      unlinkRedeclChain(cast<RedeclarableTemplateDecl>(FTD));
+
+    if (HasSurvivorToReplace) {
+      if (auto *FD = dyn_cast<FunctionDecl>(FTD->getTemplatedDecl()))
+        unlinkRedeclChain(FD);
+    }
+  }
+
+  if (!hasRecord())
+    return;
+
+  // Restore Decl.
+  if (Record().has(MutationKind::SpecializationAdded)) {
+    auto &Specs = FTD->getSpecializations();
+    while (!Specs.empty()) {
+      auto It = Specs.end();
+      --It;
+      if (!Tracker.isFromThisPTU(It->getFunction(), ID))
+        break;
+      Specs.pop_back();
+    }
+  }
+}
+
+void ASTDeclUnmerger::VisitVarTemplateDecl(VarTemplateDecl *VTD) {
+  // Unlinking discared Decl.
+  if (isDiscarded(VTD)) {
+    unlinkCommon(VTD);
+    bool HasSurvivorToReplace =
+        !hasNoPreviousDecl(VTD) && !isFromThisPTU(VTD->getCanonicalDecl());
+    if (HasSurvivorToReplace)
+      unlinkRedeclChain(cast<RedeclarableTemplateDecl>(VTD));
+
+    NamedDecl *Templated = VTD->getTemplatedDecl();
+    if (HasSurvivorToReplace) {
+      if (auto *VD = dyn_cast<VarDecl>(Templated))
+        unlinkRedeclChain(VD);
+    }
+  }
+
+  if (!hasRecord())
+    return;
+
+  // Restore Decl.
+  if (Record().has(MutationKind::SpecializationAdded)) {
+    auto &Specs = VTD->getSpecializations();
+    while (!Specs.empty()) {
+      auto It = Specs.end();
+      --It;
+      if (!Tracker.isFromThisPTU(&*It, ID))
+        break;
+      Specs.pop_back();
+    }
+  }
+}
+
+void ASTDeclUnmerger::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
+  // Unlink Discarded Decl.
+  if (isDiscarded(D)) {
+    unlinkCommon(D);
+    unlinkRedeclChain(D);
+    return;
+  }
+}
+
+void ASTDeclUnmerger::VisitTypedefNameDecl(TypedefNameDecl *D) {
+  // Unlink Discarded Decl.
+  if (isDiscarded(D)) {
+    unlinkCommon(D);
+    unlinkRedeclChain(D);
+    return;
+  }
+}
+
+void ASTDeclUnmerger::VisitUsingShadowDecl(UsingShadowDecl *D) {
+  // Unlink Discarded Decl.
+  if (isDiscarded(D)) {
+    unlinkCommon(D);
+    unlinkRedeclChain(D);
+    return;
+  }
+}
+
+void SemaCacheReverter::restoreSpecialMemberCache(PTUID ID) {
+  PTUStateInfo &Cur = Tracker.current();
+  if (!Cur.HadImplicitCXXMember)
+    return;
+
+  llvm::SmallVector<Sema::SpecialMemberCacheKey, 8> ToRemove;
+  for (auto &Entry : SemaRef.SpecialMemberCache) {
+    CXXMethodDecl *MD = Entry.second.getMethod();
+    if (MD && (Tracker.isFromThisPTU(MD, ID) || Cur.ImplicitDecls.contains(MD)))
+      ToRemove.push_back(Entry.first);
+  }
+  for (const auto &Key : ToRemove)
+    SemaRef.SpecialMemberCache.erase(Key);
+}
+
+void SemaCacheReverter::restoreVTableUsed(CXXRecordDecl *RD) {
+  SemaRef.VTablesUsed.erase(RD->getCanonicalDecl());
+}
+
+void PTUMutationActions::restore(TranslationUnitDecl *ThisTU) {
+  PTUStateInfo &Cur = Tracker.current();
+  assert((!Cur.Commited || ThisTU == Cur.ThisPTU) &&
+         "MostRecentTU doesn't match the TU recorded at commit time");
+  PTUID ID = Cur.ID;
+
+  // 1. Check whether this PTU was committed. If the PTU failed, it was not
+  //    committed and therefore did not go through the commit policy or register
+  //    any declaration state, so there is nothing to undo from
+  //    IncrementalStateTracker.
+  //
+  //    If the PTU was successfully committed, the commit policy must have
+  //    registered the declaration state and updated the state of declarations
+  //    from the previous PTU in IncrementalStateTracker. First undo all state
+  //    recorded by IncrementalStateTracker, then perform the regular undo so
+  //    that mutated declarations are restored to the PTU(N-1) state rather
+  //    than the current PTU state.
+  if (Cur.Commited) {
+    // remove sweep-tracked decls owned by this PTU,
+    // which would otherwise become stale references with no cleanup path.
+    Tracker.getHiddenMutationTracker().untrackIf(
+        [&](const Decl *D) { return Tracker.isFromThisPTU(D, ID); });
+    Tracker.undoLastEntries();
+  } else {
+    // Same as the commit() step, but performed here because this PTU failed and
+    // was never committed. Since the commit step was never executed, we need to
+    // perform it here for an uncommitted PTU.
+    Cur.verifyMutations(*this);
+    Tracker.getHiddenMutationTracker().sweep(
+        *this, [&](const Decl *D, DeclShape S, uint32_t K) {
+          Cur.noteMutated(D, S, K);
+        });
+  }
+
+  ASTDeclUnmerger Umerger(ID, Tracker, *this, SemaRef, SemaCache, CodeGen);
+
+  // 2. Same as the commit() step, but in reverse: commit() updates the
+  //    IncrementalStateTracker with the mutated state of declarations from the
+  //    previous state. Here, we restore each mutated declaration using its most
+  //    recent state in IncrementalStateTracker (i.e., the PTU(N-1) state).
+  for (auto &[D, Rec] : Cur.Mutations)
+    Umerger.restoreDecl(const_cast<Decl *>(D), Rec);
+
+  // 3. Cur.ImplicitDecls: Declarations created by this PTU. Unlink them from
+  //    the compiler's shared state.
+  //
+  //    This is the counterpart to the commit, but
+  //    performs the opposite operation by unlinking the declarations.
+  //
+  // ASTDeclUnmerger: Determines how to undo declarations mutated or created by
+  // the current PTU, such as unlinking declarations from redeclaration chains
+  // and DeclContext lookup structures, or restoring declaration state (e.g.,
+  // CXXRecordDecl::DefinitionData).
+
+  for (const Decl *D : Cur.ImplicitDecls) {
+    if (isReachableFromThisTU(D, ThisTU))
+      continue;
+    Umerger.Visit(const_cast<Decl *>(D));
+  }
+
+  Umerger.Visit(ThisTU);
+
+  // SpecialMemberCache stores the CXXMethodDecl* from a previous
+  // LookupSpecialMember() call. If it was created by a PTU being rolled back,
+  // the cache entry is stale, so remove it here.
+  SemaCache.restoreSpecialMemberCache(ID);
+
+  // Must be last: Cur/ID/ThisTU refer to data owned by this PTU, and
+  // popCurrentPTU() destroys that entry. This runs for both committed and
+  // rolled-back PTUs to reclaim the PTUStack and checkpoint entry.
+  Tracker.popCurrentPTU();
+}
+
+/// -----------------------------------------------------------------------
+////////////////////////// MutationListener ///////////////////////////////
+/// -----------------------------------------------------------------------
+
+/// This is the place for listener-related functionality. When Clang notifies
+/// us about an AST mutation, we record it in PTUStateInfo.
+///
+/// We only capture mutations here. For example, if a decl from a previous PTU
+/// is mutated, we record its Decl -> DeclShape -> mutation kind relationship.
+/// We do not process the mutation here. Processing is deferred until commit
+/// if the PTU succeeds; if the PTU fails, the flow goes through restore
+/// instead.
+///
+/// We also track implicit decls. During commit, we walk the current PTU and
+/// can only commit decls that are visible from that TU. However, implicit decls
+/// can be created and added to another PTU, so we need to track them as well
+/// so they can be committed or unlinked during restore.
+///
+/// We do not cover every mutation case here yet. Any new case added should
+/// follow the same rule: if a mutation affects a decl from a previous PTU,
+/// record it in PTUStateInfo.
+///
+/// There are two separate restore paths:
+/// 1. Restoring a mutated decl to its previous state.
+/// 2. Unlinking a decl from shared state, such as redecl chains or DC lookup.
+///
+/// For example, see noteDefinitionInstantiated, where a decl is created by
+/// Clang and added to another PTU even though it is not marked as implicit.
+/// Such a decl needs to be tracked for unlinking rather than restoring its
+/// previous state.
+
+void PTUMutationRecorder::CompletedTagDefinition(const TagDecl *D) {
+  if (!D->isDefinedOutsideFunctionOrMethod())
+    return; // ordinary local class -- structurally unreachable by any other
+            // PTU
+
+  PTUStateInfo &Cur = Tracker.current();
+  if (Tracker.isFromThisPTU(D, Tracker.currentID())) {
+    if (D->isImplicit())
+      Cur.ImplicitDecls.insert(D);
+    return;
+  }
+
+  DeclShape S = classifyShape(D);
+  if (false)
+    Cur.noteMutated(D, S, MutationKind::DefinitionInstantiate);
+
+  /// Handle this for MemberSpec because the notifier does not guarantee whether
+  /// it fires before or after the mutation. We cannot reliably compare the
+  /// state here, so mutation detection is deferred to the verification layer.
+  if (S == DeclShape::Enum) {
+    if (const EnumDecl *ED = dyn_cast<EnumDecl>(D);
+        ED && ED->getMemberSpecializationInfo())
+      Cur.noteMutated(D, S, MutationKind::MemberSpecInfo);
+  } else if (S == DeclShape::Class) {
+    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D);
+        RD && RD->getMemberSpecializationInfo())
+      Cur.noteMutated(D, S, MutationKind::MemberSpecInfo);
+    if (isa<ClassTemplateSpecializationDecl>(D))
+      Cur.noteMutated(D, S, MutationKind::SpecInfo);
+  }
+}
+
+void PTUMutationRecorder::AddedVisibleDecl(const DeclContext *DC,
+                                           const Decl *D) {
+  PTUStateInfo &Cur = Tracker.current();
+  if (D->isImplicit())
+    Cur.ImplicitDecls.insert(D);
+
+  if (Tracker.isFromThisPTU(DC, Cur.ID) || Cur.TouchedDCs.contains(DC))
+    return;
+
+  Cur.TouchedDCs.insert(DC);
+}
+
+void PTUMutationRecorder::AddedCXXImplicitMember(const CXXRecordDecl *RD,
+                                                 const Decl *D) {
+  if (!RD->isDefinedOutsideFunctionOrMethod())
+    return; // ordinary local class -- structurally unreachable by any other
+            // PTU
+
+  PTUStateInfo &Cur = Tracker.current();
+
+  if (D->isImplicit())
+    Cur.ImplicitDecls.insert(D);
+
+  // cover only not from this ptu.
+  if (Tracker.isFromThisPTU(RD, Cur.ID))
+    return;
+
+  Cur.noteMutated(RD, DeclShape::Class, MutationKind::DefinitionData);
+}
+
+template <typename TemplateT, typename SpecT>
+void PTUMutationRecorder::noteTemplateDeclMutation(const TemplateT *TD,
+                                                   const SpecT *Spec,
+                                                   DeclShape S) {
+  PTUStateInfo &Cur = Tracker.current();
+  Cur.ImplicitDecls.insert(Spec);
+
+  if (Tracker.isFromThisPTU(TD, Cur.ID))
+    return;
+
+  Cur.noteMutated(TD, DeclShape::Template, MutationKind::SpecializationAdded);
+}
+
+void PTUMutationRecorder::AddedCXXTemplateSpecialization(
+    const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
+  noteTemplateDeclMutation(TD, D, DeclShape::Class);
+}
+
+void PTUMutationRecorder::AddedCXXTemplateSpecialization(
+    const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
+  noteTemplateDeclMutation(TD, D, DeclShape::Var);
+}
+
+void PTUMutationRecorder::AddedCXXTemplateSpecialization(
+    const FunctionTemplateDecl *TD, const FunctionDecl *D) {
+  noteTemplateDeclMutation(TD, D, DeclShape::Function);
+}
+
+void PTUMutationRecorder::noteDefinitionInstantiated(const Decl *D) {
+  PTUStateInfo &Cur = Tracker.current();
+  if (Tracker.isFromThisPTU(D, Cur.ID)) {
+    // Normally, walkDecls covers declarations created in this PTU.
+    // But an out-of-line static data member is a separate VarDecl whose
+    // lexical context is the class, so the namespace/TU walk won't find it.
+    // Process it like other implicit declarations instead.
+    const auto *VD = dyn_cast<VarDecl>(D);
+    if (VD && VD->getPreviousDecl() &&
+        !Tracker.isFromThisPTU(VD->getCanonicalDecl(), Cur.ID))
+      Cur.ImplicitDecls.insert(D);
+    return;
+  }
+
+  Cur.noteMutated(D, classifyShape(D), MutationKind::DefinitionInstantiate);
+}
+
+/// InstantiationRequested fires when Sema decides a template entity needs
+/// instantiating -- before the instantiation actually happens.
+void PTUMutationRecorder::InstantiationRequested(const ValueDecl *D) {
+  PTUStateInfo &Cur = Tracker.current();
+
+  if (Tracker.isFromThisPTU(D, Cur.ID)) {
+    // Created this PTU -- the creation path covers it, no mutation to note.
+    // But an implicitly-created decl may never be appended to any lexical
+    // chain, so walkTU would never see it. Record it here as the
+    // only path that will.
+    if (D->isImplicit())
+      Cur.ImplicitDecls.insert(D);
+    return;
+  }
+
+  DeclShape S;
+  MutationKind K = MutationKind::None;
+
+  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
+    S = DeclShape::Function;
+    if (FD->getMemberSpecializationInfo())
+      K = MutationKind::MemberSpecInfo;
+    else if (FD->getTemplateSpecializationKind() != TSK_Undeclared)
+      K = MutationKind::SpecInfo;
+    else
+      return; // neither -- nothing this notifier can be about
+  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
+    S = DeclShape::Var;
+    if (VD->getMemberSpecializationInfo())
+      K = MutationKind::MemberSpecInfo;
+    else if (isa<VarTemplateSpecializationDecl>(VD))
+      K = MutationKind::SpecInfo;
+    else
+      return;
+  } else {
+    return; // no other ValueDecl kind participates in instantiation
+  }
+
+  Cur.noteMutated(D, S, K);
+}
+
+// Remove all entries for each (Owner, Kind) key written by this PTU.
+void IncrementalStateTracker::undoLastEntries() {
+  PTUStateInfo &Cur = current();
+  PTUID ID = Cur.ID;
+
+  for (auto &[Owner, K] : Cur.TouchedFootprints)
+    Footprints.removeFrom(Owner, K, ID);
+}
+
+} // end namespace clang
\ No newline at end of file
diff --git a/clang/lib/Interpreter/ErrorRecovery.h b/clang/lib/Interpreter/ErrorRecovery.h
new file mode 100644
index 00000000000000..c596e765cc28d6
--- /dev/null
+++ b/clang/lib/Interpreter/ErrorRecovery.h
@@ -0,0 +1,771 @@
+//===--- ErrorRecovery.h - Errory Recovery Impl --------------*- C++
+//-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This header provides the main error-recovery component for supporting
+// error recovery in clang-repl.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_INTERPRETER_ERROR_RECOVERY_H
+#define LLVM_CLANG_INTERPRETER_ERROR_RECOVERY_H
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTMutationListener.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclBase.h"
+#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DeclTemplate.h"
+#include "clang/AST/DeclVisitor.h"
+#include "clang/CodeGen/ModuleBuilder.h"
+#include "llvm/ADT/BitVector.h"
+#include <variant>
+
+namespace clang {
+class ASTContext;
+class Sema;
+
+/// Index of a per PTU State.
+using PTUID = unsigned;
+
+/// A snapshot of the DefinitionData bits and bitfields that can change
+/// after a class gets a special implicit member added.
+struct DefinitionDataFootprint {
+#define FIELD(Name, Width, Merge) unsigned Name : Width;
+#include "clang/AST/CXXRecordDeclDefinitionBits.def"
+
+  bool operator==(const DefinitionDataFootprint &O) const {
+#define FIELD(Name, Width, Merge)                                              \
+  if (Name != O.Name)                                                          \
+    return false;
+#include "clang/AST/CXXRecordDeclDefinitionBits.def"
+    return true;
+  }
+  bool operator!=(const DefinitionDataFootprint &O) const {
+    return !(*this == O);
+  }
+
+  // void update(const CXXRecordDecl &Live) {
+  //   DeclStateReverter::createDefinitionDataFootprint(*this, Live);
+  // }
+
+  // void restore(CXXRecordDecl &Live) const {
+  //   DeclStateReverter::restoreDefinitionDataFootprint(*this, Live);
+  // }
+};
+
+// Stores the state of a class template specialization. Tracks its
+// specialization kind, point of instantiation, source location, and lexical
+// declaration context so the state can be compared and restored.
+struct SpecializationFootprint {
+  unsigned SpecializationKind : 3;
+  SourceLocation PointOfInstantiation;
+  SourceLocation Location;
+  const DeclContext *LexicalDC;
+
+  bool operator==(const SpecializationFootprint &O) const {
+    return SpecializationKind == O.SpecializationKind &&
+           PointOfInstantiation == O.PointOfInstantiation &&
+           Location == O.Location && LexicalDC == O.LexicalDC;
+  }
+  bool operator!=(const SpecializationFootprint &O) const {
+    return !(*this == O);
+  }
+
+  void update(const ClassTemplateSpecializationDecl &Live) {
+    SpecializationKind = Live.getSpecializationKind();
+    PointOfInstantiation = Live.getPointOfInstantiation();
+    Location = Live.getLocation();
+    LexicalDC = Live.getLexicalDeclContext();
+  }
+
+  void restore(ClassTemplateSpecializationDecl &Live) const {
+    Live.setSpecializationKind(
+        static_cast<TemplateSpecializationKind>(SpecializationKind));
+    Live.setPointOfInstantiation(PointOfInstantiation);
+    Live.setLocation(Location);
+    Live.setLexicalDeclContext(const_cast<DeclContext *>(LexicalDC));
+  }
+};
+
+// Stores the state of a variable template specialization. Tracks its
+// specialization kind and point of instantiation so the state can be
+// compared and restored.
+struct VarSpecializationFootprint {
+  unsigned SpecializationKind : 3;
+  SourceLocation PointOfInstantiation;
+
+  bool operator==(const VarSpecializationFootprint &O) const {
+    return SpecializationKind == O.SpecializationKind &&
+           PointOfInstantiation == O.PointOfInstantiation;
+  }
+  bool operator!=(const VarSpecializationFootprint &O) const {
+    return !(*this == O);
+  }
+
+  void update(const VarTemplateSpecializationDecl &Live) {
+    SpecializationKind = Live.getSpecializationKind();
+    PointOfInstantiation = Live.getPointOfInstantiation();
+  }
+
+  void restore(VarTemplateSpecializationDecl &Live) const {
+    Live.setSpecializationKind(
+        static_cast<TemplateSpecializationKind>(SpecializationKind));
+    Live.setPointOfInstantiation(PointOfInstantiation);
+  }
+};
+
+// Stores the state of a function template specialization. Tracks its
+// specialization kind, point of instantiation, source location, lexical
+// declaration context, and constexpr state so the state can be compared
+// and restored.
+struct FunctionSpecializationFootprint {
+  unsigned SpecializationKind : 3;
+  SourceLocation PointOfInstantiation;
+  SourceLocation Location;
+  const DeclContext *LexicalDC;
+  ConstexprSpecKind ConstexprKind;
+
+  bool operator==(const FunctionSpecializationFootprint &O) const {
+    return SpecializationKind == O.SpecializationKind &&
+           PointOfInstantiation == O.PointOfInstantiation &&
+           Location == O.Location && LexicalDC == O.LexicalDC &&
+           ConstexprKind == O.ConstexprKind;
+  }
+  bool operator!=(const FunctionSpecializationFootprint &O) const {
+    return !(*this == O);
+  }
+
+  void update(const FunctionDecl &Live) {
+    SpecializationKind = Live.getTemplateSpecializationKind();
+    PointOfInstantiation = Live.getPointOfInstantiation();
+    Location = Live.getLocation();
+    LexicalDC = Live.getLexicalDeclContext();
+    ConstexprKind = Live.getConstexprKind();
+  }
+
+  void restore(FunctionDecl &Live) const {
+    Live.setTemplateSpecializationKind(
+        static_cast<TemplateSpecializationKind>(SpecializationKind),
+        PointOfInstantiation);
+    Live.setLocation(Location);
+    Live.setLexicalDeclContext(const_cast<DeclContext *>(LexicalDC));
+    Live.setConstexprKind(ConstexprKind);
+  }
+};
+
+// Stores the state of an ordinary class member created from a class template
+// instantiation. Tracks its specialization kind and point of instantiation
+// so the state can be compared and restored.
+struct MemberSpecializationFootprint {
+  unsigned SpecializationKind : 3;
+  SourceLocation PointOfInstantiation;
+
+  bool operator==(const MemberSpecializationFootprint &O) const {
+    return SpecializationKind == O.SpecializationKind &&
+           PointOfInstantiation == O.PointOfInstantiation;
+  }
+  bool operator!=(const MemberSpecializationFootprint &O) const {
+    return !(*this == O);
+  }
+
+  template <typename OwnerT> void update(const OwnerT &Live) {
+    const MemberSpecializationInfo *MSI = Live.getMemberSpecializationInfo();
+    SpecializationKind = MSI->getTemplateSpecializationKind();
+    PointOfInstantiation = MSI->getPointOfInstantiation();
+  }
+
+  template <typename OwnerT> void restore(OwnerT &Live) const {
+    MemberSpecializationInfo *MSI = Live.getMemberSpecializationInfo();
+    MSI->setTemplateSpecializationKind(
+        static_cast<TemplateSpecializationKind>(SpecializationKind));
+    MSI->setPointOfInstantiation(PointOfInstantiation);
+  }
+};
+
+class PTUMutationActions;
+
+/// Maps addresses to the PTU that allocated them, by keeping the slab
+/// checkpoint taken before each PTU began.
+class PTUCheckpointLedger {
+  const ASTContext &Ctx;
+  llvm::SmallVector<llvm::SlabCheckPoint, 16> CheckpointBeforePTU;
+  llvm::BitVector Dead;
+
+  bool isAfter(const void *Ptr, PTUID ID) const {
+    return Ctx.getAllocator().isAfterCheckpoint(Ptr, CheckpointBeforePTU[ID]);
+  }
+
+public:
+  explicit PTUCheckpointLedger(const ASTContext &Ctx) : Ctx(Ctx) {}
+
+  /// Called once, right before parsing PTU \p ID begins.
+  void recordCheckpoint(PTUID ID, llvm::SlabCheckPoint CP) {
+    assert(ID == CheckpointBeforePTU.size() &&
+           "PTUs must be recorded in order");
+    CheckpointBeforePTU.push_back(CP);
+    Dead.push_back(false);
+  }
+
+  /// Was \p Ptr allocated during PTU \p ID or later?
+  bool isFromThisPTU(const void *Ptr, PTUID ID) const {
+    assert(ID < CheckpointBeforePTU.size());
+    assert(!Dead[ID] &&
+           "querying provenance against a PTU that no longer exists");
+    return isAfter(Ptr, ID);
+  }
+
+  /// The PTU that allocated \p Ptr, or nullopt if it predates the oldest
+  /// recorded checkpoint. The newest ID whose checkpoint \p Ptr is after.
+  std::optional<PTUID> attribute(const void *Ptr) const {
+    size_t Lo = 0, Hi = CheckpointBeforePTU.size();
+    std::optional<PTUID> Result;
+    while (Lo < Hi) {
+      size_t Mid = Lo + (Hi - Lo) / 2;
+      if (isAfter(Ptr, Mid)) {
+        Result = static_cast<PTUID>(Mid);
+        Lo = Mid + 1;
+      } else {
+        Hi = Mid;
+      }
+    }
+    assert((!Result || !Dead[*Result]) &&
+           "Ptr belongs to a PTU that was already rolled back");
+    return Result;
+  }
+
+  /// FIXME: Pop back CheckpointBeforePTU once memory restoration is supported.
+  /// For now, there is no memory restoration, so mark it dead.
+  void markDead(PTUID ID) {
+    assert(ID < Dead.size());
+    Dead[ID] = true;
+  }
+};
+
+struct MutationRecord {
+  enum class DeclShape : uint16_t {
+    None = 0,
+    // Base shapes -- what the decl fundamentally is. Exactly one is set.
+    Class = 1 << 0,    // CXXRecordDecl/TagDecl: DefinitionData, TypeForDecl
+    Function = 1 << 1, // FunctionDecl: exception spec, deduced return, body
+    Var = 1 << 2,      // VarDecl: cached constant-eval result
+    Enum = 1 << 3,     // EnumDecl: TypeForDecl
+    Template = 1 << 4, // RedeclarableTemplateDecl: spec list grows
+    Typedef = 1 << 5,  // TypedefDecl/TypeAliasDecl: TypeForDecl.
+  };
+
+  enum class MutationKind : uint32_t {
+    None = 0,
+    // ---- Common ----
+    DefinitionInstantiate = 1 << 0, // Class, Function, Var
+    SpecInfo = 1 << 1,              // Class, Function, Var  (Spec)
+    MemberSpecInfo = 1 << 2,        // Class, Function, Var, Enum (Member)
+    TypeForDecl = 1 << 3,           // Class, Enum
+
+    // ---- Shape-specific ----
+    DefinitionData = 1 << 8,       // Class only
+    ExceptionSpec = 1 << 9,        // Function only
+    DeducedReturnType = 1 << 10,   // Function only
+    EvaluatedValue = 1 << 11,      // Var only
+    SpecializationAdded = 1 << 12, // Template only
+
+    TemplateCommon = 1 << 4,   // Template CommonBase
+    CanonInjectedTST = 1 << 5, // Template CommonBase Type
+  };
+
+  DeclShape S = DeclShape::None;
+  uint32_t MutationFlags = 0; // what this decl can ever have
+
+  void add(MutationKind K) { MutationFlags |= uint32_t(K); }
+  void add(uint32_t K) { MutationFlags |= uint32_t(K); }
+  bool has(MutationKind K) const { return MutationFlags & uint32_t(K); }
+  void clear(MutationKind K) { MutationFlags &= ~uint32_t(K); }
+};
+
+using DeclShape = MutationRecord::DeclShape;
+using MutationKind = MutationRecord::MutationKind;
+
+using FootprintValue =
+    std::variant<DefinitionDataFootprint, SpecializationFootprint,
+                 VarSpecializationFootprint, FunctionSpecializationFootprint,
+                 MemberSpecializationFootprint, QualType, const Type *>;
+
+struct FootprintSnapshot {
+  PTUID ID;
+  FootprintValue Data;
+};
+
+class FootprintStore {
+  llvm::DenseMap<std::pair<const Decl *, MutationKind>,
+                 llvm::SmallVector<FootprintSnapshot, 2>>
+      Store;
+
+public:
+  // commit decl state owner+mutation_kind -> Footprint.
+  template <typename T>
+  void commit(const Decl *Owner, MutationKind K, PTUID ID, const T &Fresh) {
+    auto &History = Store[{Owner, K}];
+    if (!History.empty() && std::get<T>(History.back().Data) == Fresh)
+      return;
+    History.push_back(FootprintSnapshot{ID, FootprintValue(Fresh)});
+  }
+
+  // nullptr means either "no history at all" or "history exists but the
+  // most recent entry isn't a T".
+  template <typename T>
+  const T *mostRecent(const Decl *Owner, MutationKind K) const {
+    auto It = Store.find({Owner, K});
+    if (It == Store.end() || It->second.empty())
+      return nullptr;
+    return std::get_if<T>(&It->second.back().Data);
+  }
+
+  /// Remove all entries with IDs greater than or equal to \p ID for this
+  /// (Owner, K). If no entries remain, remove the key entirely.
+  void removeFrom(const Decl *Owner, MutationKind K, PTUID ID) {
+    auto It = Store.find({Owner, K});
+    if (It == Store.end())
+      return;
+    auto &History = It->second;
+    while (!History.empty() && History.back().ID >= ID)
+      History.pop_back();
+    if (History.empty())
+      Store.erase(It);
+  }
+};
+
+struct PTUStateInfo {
+  PTUID ID;
+  const TranslationUnitDecl *ThisPTU; // current info
+
+  llvm::MapVector<const Decl *, MutationRecord> Mutations;
+
+  llvm::SmallPtrSet<const Decl *, 4> ImplicitDecls;
+
+  /// Set exactly when AddedCXXImplicitMember fires this PTU.
+  bool HadImplicitCXXMember = false;
+
+  /// here touched info mean other this belongs to other PTUs;
+  llvm::SmallPtrSet<const DeclContext *, 8> TouchedDCs;
+
+  /// Every (Owner, Kind) key this PTU's own commit() wrote a FootprintStore
+  /// entry for.
+  llvm::SmallVector<std::pair<const Decl *, MutationKind>, 8> TouchedFootprints;
+
+  explicit PTUStateInfo(PTUID ID) : ID(ID) {}
+
+  template <typename KindT>
+  void noteMutated(const Decl *D, DeclShape S, KindT K) {
+    if (!D->isDefinedOutsideFunctionOrMethod())
+      return;
+    auto [It, Inserted] = Mutations.try_emplace(D);
+    if (Inserted) {
+      It->second.S = S;
+    }
+
+    assert(It->second.S == S && "same decl noted under two different shapes");
+
+    It->second.add(K);
+  }
+
+  void verifyMutations(PTUMutationActions &Actions);
+
+  // False until this PTU is actually committed.
+  // PTUMutationActions uses this to decide what "undo" should do:
+  // - If this PTU was never committed, nothing was added to the chain,
+  //   so we just restore the last PTU that was committed.
+  // - If this PTU was already committed (for example, by using %undo),
+  //   first remove the entries created by this PTU, then restore the
+  //   state from before this PTU was added.
+  bool Commited = false;
+};
+
+//===----------------------------------------------------------------------===//
+// SweepTracker -- Tracks declarations whose mutations cannot be reported
+// directly by an ASTMutationListener.
+//
+// Each Decl is tracked with the hidden mutation kinds that are still possible.
+// At commit time, sweep() checks the tracked kinds to find mutations made by
+// the current PTU. Once a mutation kind is confirmed or can no longer happen,
+// it is removed from tracking.
+//
+// During restore, a mutation kind can be tracked again so its mutation sites
+// can be restored when needed.
+//===----------------------------------------------------------------------===//
+class SweepTracker {
+  llvm::DenseMap<const Decl *, uint32_t> Active;
+
+public:
+  void track(const Decl *D, uint32_t HiddenBits) {
+    if (HiddenBits)
+      Active[D] |= HiddenBits;
+  }
+
+  bool isTrackedFor(const Decl *D, uint32_t Flag) const {
+    auto It = Active.find(D);
+    return It != Active.end() && (It->second & Flag);
+  }
+
+  void untrack(const Decl *D, uint32_t Flag) {
+    auto It = Active.find(D);
+    if (It == Active.end())
+      return;
+    It->second &= ~Flag;
+    if (!It->second)
+      Active.erase(It);
+  }
+
+  // removes every Active entry whose decl matches Predicate.
+  template <typename PredicateFn> void untrackIf(PredicateFn Predicate) {
+    llvm::SmallVector<const Decl *, 8> Stale;
+    for (auto &Entry : Active)
+      if (Predicate(Entry.getFirst()))
+        Stale.push_back(Entry.getFirst());
+    for (const Decl *D : Stale)
+      Active.erase(D);
+  }
+
+  // Call at commit/restore time. OnConfirmed is invoked as
+  // (const Decl *D, DeclShape S, uint32_t ConfirmedKinds) for every decl
+  // that had something newly confirmed this sweep.
+  template <typename OnConfirmedFn>
+  void sweep(PTUMutationActions &Act, OnConfirmedFn OnConfirmed);
+};
+
+// Overall flow:
+// - Track changes made by other PTUs so they can be applied to the relevant
+//   chains/mutations when those PTUs are committed.
+// - On rollback of a committed PTU, remove the entries created by that PTU
+//   and restore the state that existed before it.
+// - On rollback of a PTU that was never committed, restore the chain to its
+//   current mostRecent() state, since this PTU never added anything to it.
+// - For the current PTU, collect newly added declarations that are
+//   modifiable/visible to other PTUs. Local-only declarations are not exposed.
+//
+// In short, this keeps the shared declaration state in sync across PTUs.
+class IncrementalStateTracker {
+private:
+  ASTContext &Ctx;
+  PTUCheckpointLedger PTUSlabCheckpoints;
+  PTUID NextID = 0;
+
+  mutable std::vector<PTUStateInfo> PTUStack;
+
+  // One relation for every tracked footprint/value kind.
+  FootprintStore Footprints;
+
+  // Tracks hidden mutations for all supported Decl kinds in one shared tracker,
+  // so they can be restored correctly during rollback.
+  SweepTracker HiddenMutationTracker;
+
+  friend class PTUMutationActions;
+
+public:
+  IncrementalStateTracker(ASTContext &Ctx)
+      : Ctx(Ctx), PTUSlabCheckpoints(Ctx) {}
+
+  // Writes a new value to FootprintStore and records that this PTU touched
+  // (Owner, K), so undoLastEntries() knows what to remove if the PTU is rolled
+  // back without committing.
+  template <typename T>
+  void commitFootprint(const Decl *Owner, MutationKind K, PTUID ID,
+                       const T &Fresh) {
+    Footprints.commit(Owner, K, ID, Fresh);
+    current().TouchedFootprints.emplace_back(Owner, K);
+  }
+
+  FootprintStore &getFootprints() { return Footprints; }
+
+  PTUStateInfo &current() const {
+    assert(!PTUStack.empty() && "no PTU has been started");
+    return PTUStack.back();
+  }
+
+  PTUID currentID() const { return current().ID; }
+  bool hasOpenPTU() const { return !PTUStack.empty(); }
+
+  void beginPTU(llvm::SlabCheckPoint CP) {
+    PTUID ID = NextID++;
+    PTUSlabCheckpoints.recordCheckpoint(ID, CP);
+    PTUStack.emplace_back(ID);
+  }
+
+  bool isFromThisPTU(const void *Ptr, PTUID ID) const {
+    return PTUSlabCheckpoints.isFromThisPTU(Ptr, ID);
+  }
+  bool isFromCurrentPTU(const void *Ptr) const {
+    return isFromThisPTU(Ptr, currentID());
+  }
+
+  SweepTracker &getHiddenMutationTracker() { return HiddenMutationTracker; }
+  PTUCheckpointLedger &getPTUSlabCheckpoints() { return PTUSlabCheckpoints; }
+  ASTContext &getASTContext() const { return Ctx; }
+
+  void undoLastEntries();
+
+private:
+  void popCurrentPTU() {
+    PTUID ID = currentID();
+    PTUStack.pop_back();
+    PTUSlabCheckpoints.markDead(ID);
+  }
+};
+
+// Once place to revert Sema specific cache.
+class SemaCacheReverter {
+  Sema &SemaRef;
+  IncrementalStateTracker &Tracker;
+
+public:
+  explicit SemaCacheReverter(Sema &S, IncrementalStateTracker &Tracker)
+      : SemaRef(S), Tracker(Tracker) {}
+
+  // Sema::SpecialMemberCache stores the CXXMethodDecl* found by previous
+  // LookupSpecialMember() calls for each (RD, kind+qualifiers). Remove entries
+  // that refer to methods from the PTU being rolled back.
+  void restoreSpecialMemberCache(PTUID ID);
+
+  // Sema::VTablesUsed records, per class, whether its vtable has already
+  // been marked used.
+  void restoreVTableUsed(CXXRecordDecl *RD);
+};
+
+class PTUMutationActions : public ConstDeclVisitor<PTUMutationActions> {
+private:
+  IncrementalStateTracker &Tracker;
+  SweepTracker &HiddenMutationTracker;
+  Sema &SemaRef;
+  CodeGenerator *CodeGen = nullptr;
+  SemaCacheReverter SemaCache;
+
+  MutationRecord *Rec = nullptr;
+
+  PTUID CurrentID() const { return Tracker.currentID(); }
+  MutationRecord &Record() const {
+    assert(Rec && "Invalid MutationRecord");
+    return *Rec;
+  }
+
+public:
+  explicit PTUMutationActions(IncrementalStateTracker &Tracker, Sema &S,
+                              CodeGenerator *CodeGen = nullptr)
+      : Tracker(Tracker),
+        HiddenMutationTracker(Tracker.getHiddenMutationTracker()), SemaRef(S),
+        CodeGen(CodeGen), SemaCache(S, Tracker) {}
+
+  Sema &getSema() const { return SemaRef; }
+  CodeGenerator *getCodeGen() const { return CodeGen; }
+
+  template <typename DeclStatePolicyT>
+  void walkDecls(DeclContext *DC, DeclStatePolicyT &Policy);
+
+  uint32_t DeclNeedingTracking(DeclShape S, const Decl *D);
+
+  uint32_t confirmMutation(const Decl *D, DeclShape S, uint32_t FlaggedKinds);
+
+  void trackForSweep(const Decl *D, uint32_t Kinds);
+
+  void untrackIfClosed(const Decl *D, DeclShape S, uint32_t Confirmed);
+
+  void syncSweepTracking(const Decl *D, DeclShape S, uint32_t Kinds,
+                         bool IsNew);
+
+  bool shouldRecurseInto(const Decl *D);
+
+  void VisitDeclContext(const DeclContext *DC);
+  void VisitCXXRecordDecl(const CXXRecordDecl *RD);
+  void VisitFunctionDecl(const FunctionDecl *FD);
+  void VisitVarDecl(const VarDecl *VD);
+  void VisitEnumDecl(const EnumDecl *ED);
+  void VisitRedeclarableTemplateDecl(const RedeclarableTemplateDecl *RT);
+
+  void commitDecl(const Decl *D, MutationRecord *Rec);
+
+  // Actual commit action: updates IncrementalStateTracker tracking info for
+  // decls from the previous PTU after a successful PTU. And add tracking info
+  // for newly created Decls
+  //
+  void commit(TranslationUnitDecl *MostRecentTU);
+
+  // Restore action: restores decls from the previous PTU using
+  // IncrementalStateTracker tracking info and unlinks decls created by this
+  // PTU.
+  void restore(TranslationUnitDecl *MostRecentTU);
+};
+
+class PTUMutationRecorder : public ASTMutationListener {
+private:
+  IncrementalStateTracker &Tracker;
+
+  template <typename TemplateT, typename SpecT>
+  void noteTemplateDeclMutation(const TemplateT *TD, const SpecT *Spec,
+                                DeclShape S);
+
+  void noteExceptionSpecMutation(const FunctionDecl *FD,
+                                 MutationKind K = MutationKind::ExceptionSpec);
+
+  void noteDefinitionInstantiated(const Decl *D);
+
+public:
+  PTUMutationRecorder(IncrementalStateTracker &Tracker) : Tracker(Tracker) {}
+
+  /// A new TagDecl definition was completed.
+  void CompletedTagDefinition(const TagDecl *D) override;
+
+  /// A new declaration with name has been added to a DeclContext.
+  void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override;
+
+  /// An implicit member was added after the definition was completed.
+  void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override;
+
+  /// A template specialization (or partial one) was added to the
+  /// template declaration.
+  void AddedCXXTemplateSpecialization(
+      const ClassTemplateDecl *TD,
+      const ClassTemplateSpecializationDecl *D) override;
+
+  /// A template specialization (or partial one) was added to the
+  /// template declaration.
+  void AddedCXXTemplateSpecialization(
+      const VarTemplateDecl *TD,
+      const VarTemplateSpecializationDecl *D) override;
+
+  /// A template specialization (or partial one) was added to the
+  /// template declaration.
+  void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
+                                      const FunctionDecl *D) override;
+
+  /// A function's exception specification has been evaluated or
+  /// instantiated.
+  void ResolvedExceptionSpec(const FunctionDecl *FD) override {}
+
+  /// A function's return type has been deduced.
+  void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override {}
+
+  /// A virtual destructor's operator delete has been resolved.
+  void ResolvedOperatorDelete(const CXXDestructorDecl *DD,
+                              const FunctionDecl *Delete,
+                              Expr *ThisArg) override {}
+
+  /// A virtual destructor's operator global delete has been resolved.
+  void ResolvedOperatorGlobDelete(const CXXDestructorDecl *DD,
+                                  const FunctionDecl *GlobDelete) override {}
+
+  /// A virtual destructor's operator array delete has been resolved.
+  void ResolvedOperatorArrayDelete(const CXXDestructorDecl *DD,
+                                   const FunctionDecl *ArrayDelete) override {}
+
+  /// A virtual destructor's operator global array delete has been resolved.
+  void ResolvedOperatorGlobArrayDelete(
+      const CXXDestructorDecl *DD,
+      const FunctionDecl *GlobArrayDelete) override {}
+
+  /// An implicit member got a definition.
+  void CompletedImplicitDefinition(const FunctionDecl *D) override {
+    noteDefinitionInstantiated(D);
+  }
+
+  /// The instantiation of a templated function or variable was
+  /// requested. In particular, the point of instantiation and template
+  /// specialization kind of \p D may have changed.
+  void InstantiationRequested(const ValueDecl *D) override;
+
+  /// A templated variable's definition was implicitly instantiated.
+  void VariableDefinitionInstantiated(const VarDecl *D) override {
+    noteDefinitionInstantiated(D);
+  }
+
+  /// A function template's definition was instantiated.
+  void FunctionDefinitionInstantiated(const FunctionDecl *D) override {
+    noteDefinitionInstantiated(D);
+  }
+
+  /// A default argument was instantiated.
+  void DefaultArgumentInstantiated(const ParmVarDecl *D) override {}
+
+  /// A default member initializer was instantiated.
+  void DefaultMemberInitializerInstantiated(const FieldDecl *D) override {}
+
+  /// A new objc category class was added for an interface.
+  void AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
+                                    const ObjCInterfaceDecl *IFD) override {}
+
+  /// A declaration is marked used which was not previously marked used.
+  ///
+  /// \param D the declaration marked used
+  void DeclarationMarkedUsed(const Decl *D) override {}
+
+  /// A declaration is marked as OpenMP threadprivate which was not
+  /// previously marked as threadprivate.
+  ///
+  /// \param D the declaration marked OpenMP threadprivate.
+  void DeclarationMarkedOpenMPThreadPrivate(const Decl *D) override {}
+
+  /// A declaration is marked as OpenMP groupprivate which was not
+  /// previously marked as groupprivate.
+  ///
+  /// \param D the declaration marked OpenMP groupprivate.
+  void DeclarationMarkedOpenMPGroupPrivate(const Decl *D) override {}
+
+  /// A declaration is marked as OpenMP declaretarget which was not
+  /// previously marked as declaretarget.
+  ///
+  /// \param D the declaration marked OpenMP declaretarget.
+  /// \param Attr the added attribute.
+  void DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
+                                            const Attr *Attr) override {}
+
+  /// A declaration is marked as a variable with OpenMP allocator.
+  ///
+  /// \param D the declaration marked as a variable with OpenMP allocator.
+  void DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) override {}
+
+  /// A declaration is marked as an OpenMP indirect call target.
+  ///
+  /// \param D the declaration marked as an indirect call target.
+  void DeclarationMarkedOpenMPIndirectCall(const Decl *D) override {}
+
+  /// A definition has been made visible by being redefined locally.
+  ///
+  /// \param D The definition that was previously not visible.
+  /// \param M The containing module in which the definition was made visible,
+  ///        if any.
+  void RedefinedHiddenDefinition(const NamedDecl *D, Module *M) override {}
+
+  /// An attribute was added to a RecordDecl
+  ///
+  /// \param Attr The attribute that was added to the Record
+  ///
+  /// \param Record The RecordDecl that got a new attribute
+  void AddedAttributeToRecord(const Attr *Attr,
+                              const RecordDecl *Record) override {}
+
+  /// An mangling number was added to a Decl
+  ///
+  /// \param D The decl that got a mangling number
+  ///
+  /// \param Number The mangling number that was added to the Decl
+  void AddedManglingNumber(const Decl *D, unsigned Number) override {}
+
+  /// An static local number was added to a Decl
+  ///
+  /// \param D The decl that got a static local number
+  ///
+  /// \param Number The static local number that was added to the Decl
+  void AddedStaticLocalNumbers(const Decl *D, unsigned Number) override {}
+
+  /// An anonymous namespace was added the translation unit decl
+  ///
+  /// \param TU The translation unit decl that got a new anonymous namespace
+  ///
+  /// \param AnonNamespace The anonymous namespace that was added
+  void AddedAnonymousNamespace(const TranslationUnitDecl *TU,
+                               NamespaceDecl *AnonNamespace) override {}
+};
+} // end namespace clang
+#endif // LLVM_CLANG_INTERPRETER_ERROR_RECOVERY_H

>From ea3992eb318c2b9b1ab6f02abd9c14955d901d84 Mon Sep 17 00:00:00 2001
From: SahilPatidar <patidarsahil2001 at gmail.com>
Date: Sat, 28 Nov 2026 12:22:36 +0530
Subject: [PATCH 2/5] reducing scope

---
 clang/lib/Interpreter/ErrorRecovery.cpp | 572 +++++-------------------
 clang/lib/Interpreter/ErrorRecovery.h   |  60 +--
 2 files changed, 127 insertions(+), 505 deletions(-)

diff --git a/clang/lib/Interpreter/ErrorRecovery.cpp b/clang/lib/Interpreter/ErrorRecovery.cpp
index cd90b8152c1b62..5ae4ede3aac24e 100644
--- a/clang/lib/Interpreter/ErrorRecovery.cpp
+++ b/clang/lib/Interpreter/ErrorRecovery.cpp
@@ -46,7 +46,6 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
   MutationRecord *Rec = nullptr;
 
   llvm::SmallPtrSet<const Decl *, 16> RepairedChains;
-  // llvm::SmallPtrSet<const DeclContext *, 8> RepairedLexicalContexts;
 
   bool isFromThisPTU(const void *Ptr) const {
     return Tracker.isFromThisPTU(Ptr, ID);
@@ -150,11 +149,6 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
       cast<CXXRecordDecl>(I)->DefinitionData = nullptr;
   }
 
-  void detachCommonBase(const RedeclarableTemplateDecl *RT) {
-    for (const auto *R : RT->redecls())
-      R->Common = nullptr;
-  }
-
   void repairLexicalChain(DeclContext *DC) {
     Decl *Prev = nullptr;
     for (Decl *Cur = DC->FirstDecl; Cur; Cur = Cur->getNextDeclInContext()) {
@@ -171,16 +165,6 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
     }
   }
 
-  void forgetMangledNames(std::initializer_list<GlobalDecl> GDs) {
-    if (!CodeGen)
-      return;
-    // TODO: Codegen mangle name cleanup need to handle.
-  }
-
-  void forgetMangledNames(NamedDecl *ND) {
-    forgetMangledNames({GlobalDecl(ND)});
-  }
-
   void unlinkCommon(NamedDecl *ND) {
     removeFromLookups(ND);
 
@@ -191,61 +175,44 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
     detachFromDCLookup(ND);
   }
 
+  class ScopedMutationRecord {
+    MutationRecord *&Rec;
+    MutationRecord *OldRec;
+
+  public:
+    ScopedMutationRecord(MutationRecord *&Rec, MutationRecord *R)
+        : Rec(Rec), OldRec(Rec) {
+      Rec = R;
+    }
+
+    ~ScopedMutationRecord() { Rec = OldRec; }
+
+    ScopedMutationRecord(const ScopedMutationRecord &) = delete;
+    ScopedMutationRecord &operator=(const ScopedMutationRecord &) = delete;
+  };
+
   void VisitDeclContext(DeclContext *DC) {
+    ScopedMutationRecord Guard(Rec, nullptr);
     for (Decl *D : llvm::SmallVector<Decl *, 8>(DC->decls()))
       Visit(D);
     repairLexicalChain(DC);
   }
-  
 
-  void revertDefinitionArrival(VarDecl *VD) {
-    VD->setInit(nullptr);
-    VD->setInvalidDecl(false);
-  }
+  template <typename T>
+  void removeSpec(llvm::FoldingSetVector<T> &FSV,
+                  llvm::function_ref<bool(const void *)> ShouldStop) {
+    SmallVector<T *, 8> Remaining;
 
-  void revertDefinitionArrival(FunctionDecl *FD) {
-    FD->setBody(nullptr);
-    // Reset the body state so a later PTU sees this as not instantiated.
-    FD->setWillHaveBody(false);
+    for (T &Node : FSV) {
+      if (ShouldStop(&Node))
+        break;
+      Remaining.push_back(&Node);
+    }
 
-    // The reverted body may have caused a substitution failure to mark
-    // the function invalid. Clear that state as well.
-    FD->setInvalidDecl(false);
-  }
+    FSV.clear();
 
-  void revertDefinitionArrival(EnumDecl *ED) {
-    // Undo EnumDecl::completeDefinition() writes. PromotionType and both
-    // bit-count fields are always overwritten during completion, so they can
-    // be reset unconditionally.
-    ED->setPromotionType(QualType());
-    // resetEnumBits(*ED);
-    // EnumDecl::setNumPositiveBits/setNumNegativeBits -- private.
-    // ED->setNumPositiveBits(0);
-    // ED->setNumNegativeBits(0);
-
-    // completeDefinition() only sets IntegerType for non-fixed enums. A fixed
-    // enum may already have an IntegerType from its forward declaration, which
-    // must be preserved.
-    if (!ED->isFixed())
-      ED->setIntegerType(QualType());
-    ED->setCompleteDefinition(false);
-    ED->setBeingDefined(false);
-  }
-  void revertDefinitionArrival(CXXRecordDecl *RD) {
-    // 1. DefinitionData pointer -- back to null.
-    RD->DefinitionData = nullptr;
-
-    // 2. DeclContext member list -- back to empty.
-    RD->FirstDecl = nullptr;
-    RD->LastDecl = nullptr;
-    DeclContext *Primary = RD->getPrimaryContext();
-    if (StoredDeclsMap *Map = Primary->getLookupPtr())
-      Map->clear();
-
-    // 3. TagDecl completion bits -- back to "never started". Flipped by
-    // startDefinition()/completeDefinition().
-    RD->setBeingDefined(false);
-    RD->setCompleteDefinition(false);
+    for (T *Node : Remaining)
+      FSV.insert(Node);
   }
 
 public:
@@ -288,9 +255,8 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
   }
 
   void restoreDecl(Decl *D, MutationRecord &R) {
-    Rec = &R;
+    ScopedMutationRecord Guard(Rec, &R);
     Visit(D);
-    Rec = nullptr;
   }
 
   void VisitDecl(Decl *D) {
@@ -308,8 +274,8 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
   void VisitNamespaceDecl(NamespaceDecl *D);
   void VisitCXXRecordDecl(CXXRecordDecl *RD);
   void VisitFunctionDecl(FunctionDecl *FD);
-  void VisitCXXConstructorDecl(CXXConstructorDecl *D);
-  void VisitCXXDestructorDecl(CXXDestructorDecl *D);
+  // void VisitCXXConstructorDecl(CXXConstructorDecl *D);
+  // void VisitCXXDestructorDecl(CXXDestructorDecl *D);
   void VisitVarDecl(VarDecl *VD);
   void VisitEnumDecl(EnumDecl *ED);
   void VisitClassTemplateDecl(ClassTemplateDecl *CTD);
@@ -601,9 +567,18 @@ void PTUStateInfo::verifyMutations(PTUMutationActions &Actions) {
 static bool isReachableFromThisTU(const Decl *D,
                                   const TranslationUnitDecl *ThisTU) {
   const DeclContext *DC = D->getLexicalDeclContext();
-  for (; DC; DC = DC->getLexicalParent())
-    if (DC == ThisTU)
-      return DC->containsDecl(const_cast<Decl *>(D));
+
+  for (; DC; DC = DC->getLexicalParent()) {
+    if (DC->containsDecl(const_cast<Decl *>(D))) {
+      const DeclContext *Parent = DC;
+
+      while (Parent && !Parent->isTranslationUnit())
+        Parent = Parent->getLexicalParent();
+
+      return Parent == ThisTU;
+    }
+  }
+
   return false;
 }
 
@@ -645,114 +620,25 @@ void PTUMutationActions::VisitDeclContext(const DeclContext *DC) {
 }
 
 void PTUMutationActions::VisitCXXRecordDecl(const CXXRecordDecl *RD) {
-  MutationRecord &Rec = Record();
-
-  if (Rec.has(MutationKind::DefinitionInstantiate) ||
-      Rec.has(MutationKind::DefinitionData)) {
-    Tracker.commitFootprint(
-        RD, MutationKind::DefinitionData, CurrentID(),
-        ASTDeclUnmerger::createDefinitionDataFootprint(*RD));
-
-    if (Rec.has(MutationKind::DefinitionInstantiate)) {
-      if (RD->getMemberSpecializationInfo())
-        VisitDeclContext(cast<DeclContext>(RD));
-    }
-  }
-
-  if (Rec.has(MutationKind::SpecInfo)) {
-    const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RD);
-    if (Spec) {
-      Tracker.commitFootprint(
-          Spec, MutationKind::SpecInfo, CurrentID(),
-          ASTDeclUnmerger::createFootprint<SpecializationFootprint>(*Spec));
-      /// Member declarations are instantiated eagerly with the class
-      /// definition, egardless of TSK; only their definitions are deferred.
-      ///
-      /// Walk them here so each member’s MemberSpecializationInfo is tracked as
-      /// soon as it is created.
-      bool IsNew = Tracker.isFromCurrentPTU(Spec);
-      if (IsNew && Spec->getSpecializationKind() == TSK_ImplicitInstantiation)
-        VisitDeclContext(cast<DeclContext>(Spec));
-      // FIXME: Remove syncSweepTracking from all places
-      // (SpecInfo/MemberSpecInfo) once the missing notifier
-      // (ASTMutationListener) is added for (SpecInfo/MemberSpecInfo).
-      syncSweepTracking(Spec, DeclShape::Class,
-                        uint32_t(MutationKind::SpecInfo), IsNew);
-    }
-  }
-
-  if (Rec.has(MutationKind::MemberSpecInfo)) {
-    if (RD->getMemberSpecializationInfo()) {
-      Tracker.commitFootprint(
-          RD, MutationKind::MemberSpecInfo, CurrentID(),
-          ASTDeclUnmerger::createFootprint<MemberSpecializationFootprint>(*RD));
-      syncSweepTracking(RD, DeclShape::Class,
-                        uint32_t(MutationKind::MemberSpecInfo),
-                        Tracker.isFromCurrentPTU(RD));
-    }
-  }
+  // TODO
 }
 
 void PTUMutationActions::VisitFunctionDecl(const FunctionDecl *FD) {
-  MutationRecord &Rec = Record();
-  if (Rec.has(MutationKind::SpecInfo)) {
-    assert(FD->getTemplateSpecializationKind() != TSK_Undeclared &&
-           "SpecInfoChanged on a function with no specialization info");
-    Tracker.commitFootprint(
-        FD, MutationKind::SpecInfo, CurrentID(),
-        ASTDeclUnmerger::createFootprint<FunctionSpecializationFootprint>(*FD));
-    syncSweepTracking(FD, DeclShape::Function, uint32_t(MutationKind::SpecInfo),
-                      Tracker.isFromCurrentPTU(FD));
-  }
 
-  if (Rec.has(MutationKind::MemberSpecInfo)) {
-    if (FD->getMemberSpecializationInfo()) {
-      Tracker.commitFootprint(
-          FD, MutationKind::MemberSpecInfo, CurrentID(),
-          ASTDeclUnmerger::createFootprint<MemberSpecializationFootprint>(*FD));
-      syncSweepTracking(FD, DeclShape::Function,
-                        uint32_t(MutationKind::MemberSpecInfo),
-                        Tracker.isFromCurrentPTU(FD));
-    }
-  }
+  // TODO
 }
 
 void PTUMutationActions::VisitVarDecl(const VarDecl *VD) {
-  MutationRecord &Rec = Record();
-
-  if (Rec.has(MutationKind::SpecInfo)) {
-    const auto *Spec = cast<VarTemplateSpecializationDecl>(VD);
-    Tracker.commitFootprint(
-        Spec, MutationKind::SpecInfo, CurrentID(),
-        ASTDeclUnmerger::createFootprint<VarSpecializationFootprint>(*Spec));
-    syncSweepTracking(Spec, DeclShape::Var, uint32_t(MutationKind::SpecInfo),
-                      Tracker.isFromCurrentPTU(Spec));
-  }
-
-  if (Rec.has(MutationKind::MemberSpecInfo)) {
-    if (VD->getMemberSpecializationInfo()) {
-      Tracker.commitFootprint(
-          VD, MutationKind::MemberSpecInfo, CurrentID(),
-          ASTDeclUnmerger::createFootprint<MemberSpecializationFootprint>(*VD));
-      syncSweepTracking(VD, DeclShape::Var,
-                        uint32_t(MutationKind::MemberSpecInfo),
-                        Tracker.isFromCurrentPTU(VD));
-    }
-  }
+  // TODO
 }
 
 void PTUMutationActions::VisitEnumDecl(const EnumDecl *ED) {
-  MutationRecord &Rec = Record();
-  if (Rec.has(MutationKind::MemberSpecInfo)) {
-    if (ED->getMemberSpecializationInfo()) {
-      Tracker.commitFootprint(
-          ED, MutationKind::MemberSpecInfo, CurrentID(),
-          ASTDeclUnmerger::createFootprint<MemberSpecializationFootprint>(*ED));
-      syncSweepTracking(ED, DeclShape::Enum,
-                        uint32_t(MutationKind::MemberSpecInfo),
-                        Tracker.isFromCurrentPTU(ED));
-    }
-  }
+  // TODO
+}
+
+void PTUMutationActions::VisitRedeclarableTemplateDecl(
+    const RedeclarableTemplateDecl *RT) {
+  // TODO
 }
 
 void PTUMutationActions::commitDecl(const Decl *D, MutationRecord *R) {
@@ -806,19 +692,21 @@ void PTUMutationActions::commit(TranslationUnitDecl *ThisTU) {
   for (auto &[D, Rec] : Cur.Mutations)
     commitDecl(D, &Rec);
 
-  // 4. Cur.ImplicitDecls: Declarations created by this PTU. Register them for
+  // 4. Cur.ImplicitlyGeneratedDecls: Declarations created by this PTU. Register
+  // them for
   //    tracking if they have mutation-sensitive state that can be modified by
   //    later PTUs.
   //
   // commitDecl: Decides what to do with declarations created by the current
   // PTU, such as whether a declaration needs to be tracked or not.
-  for (const Decl *D : Cur.ImplicitDecls) {
-    if (isReachableFromThisTU(D, ThisTU))
-      continue;
-    if (shouldRecurseInto(D))
-      VisitDeclContext(cast<DeclContext>(D));
-    commitDecl(D, nullptr);
-  }
+  // FIXME: Uncomment once we handle restoration of Implicit Decl.
+  // for (const Decl *D : Cur.ImplicitlyGeneratedDecls) {
+  //   if (isReachableFromThisTU(D, ThisTU))
+  //     continue;
+  //   if (shouldRecurseInto(D))
+  //     VisitDeclContext(cast<DeclContext>(D));
+  //   commitDecl(D, nullptr);
+  // }
 
   // Iterate over all declarations in this TU and register them whether they
   // need explicit tracking.
@@ -854,8 +742,10 @@ void ASTDeclUnmerger::VisitNamespaceDecl(NamespaceDecl *D) {
 
 void ASTDeclUnmerger::VisitCXXRecordDecl(CXXRecordDecl *RD) {
   if (isDiscarded(RD)) {
-    VisitDeclContext(RD);
-    unlinkCommon(RD);
+    if (!RD->getDescribedClassTemplate()) {
+      VisitDeclContext(RD);
+      unlinkCommon(RD);
+    }
     if (CXXRecordDecl *Def = RD->getDefinition();
         Def && RD->getPreviousDecl() && isFromThisPTU(Def))
       detachDefData(Def);
@@ -867,45 +757,12 @@ void ASTDeclUnmerger::VisitCXXRecordDecl(CXXRecordDecl *RD) {
     return;
 
   // else perform restoration of decl state.
-  if (Record().has(MutationKind::DefinitionInstantiate) ||
-      Record().has(MutationKind::DefinitionData)) {
-    if (Record().has(MutationKind::DefinitionInstantiate)) {
-      revertDefinitionArrival(RD);
-    } else if (const auto *Restored =
-                   Tracker.getFootprints().mostRecent<DefinitionDataFootprint>(
-                       RD, MutationKind::DefinitionData)) {
-      restoreDefinitionDataFootprint(*Restored, *RD);
-    }
-  }
-
-  if (Record().has(MutationKind::SpecInfo)) {
-    // Only a specialization can carry this kind; a plain CXXRecordDecl
-    // reaching here means a note*() wrapper passed the wrong kind.
-    auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RD);
-    assert(Spec && "SpecializationAdded noted on a non-specialization");
-    if (const SpecializationFootprint *Restored =
-            Tracker.getFootprints().mostRecent<SpecializationFootprint>(
-                Spec, MutationKind::SpecInfo))
-      restoreFootprint<SpecializationFootprint>(*Restored, *Spec);
-    Actions.trackForSweep(Spec, uint32_t(MutationKind::SpecInfo));
-  }
-
-  if (Record().has(MutationKind::MemberSpecInfo)) {
-    // A nested member of a class template – its MSI kind or
-    // point-of-instantiation changed.
-    assert(RD->getMemberSpecializationInfo());
-    if (const MemberSpecializationFootprint *Restored =
-            Tracker.getFootprints().mostRecent<MemberSpecializationFootprint>(
-                RD, MutationKind::MemberSpecInfo))
-      restoreFootprint<MemberSpecializationFootprint>(*Restored, *RD);
-    Actions.trackForSweep(RD, uint32_t(MutationKind::MemberSpecInfo));
-  }
 }
 
 void ASTDeclUnmerger::VisitFunctionDecl(FunctionDecl *FD) {
   // unlink Discarded decl.
   if (isDiscarded(FD)) {
-    forgetMangledNames(FD);
+    // forgetMangledNames(FD);
     unlinkCommon(FD);
     unlinkRedeclChain(FD);
     return;
@@ -915,82 +772,13 @@ void ASTDeclUnmerger::VisitFunctionDecl(FunctionDecl *FD) {
     return;
 
   // Restore decl state.
-
-  if (Record().has(MutationKind::DefinitionInstantiate)) {
-    if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
-      forgetMangledNames({GlobalDecl(Ctor, Ctor_Complete),
-                          GlobalDecl(Ctor, Ctor_Base),
-                          GlobalDecl(Ctor, Ctor_Comdat)});
-    } else if (CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(FD)) {
-      forgetMangledNames(
-          {GlobalDecl(Dtor, Dtor_Deleting), GlobalDecl(Dtor, Dtor_Complete),
-           GlobalDecl(Dtor, Dtor_Base), GlobalDecl(Dtor, Dtor_Comdat)});
-    }
-    revertDefinitionArrival(FD);
-    if (auto *MD = dyn_cast<CXXMethodDecl>(FD); MD && MD->isVirtual())
-      SemaCache.restoreVTableUsed(MD->getParent());
-  }
-
-  if (Record().has(MutationKind::SpecInfo)) {
-    // A function template specialization is a plain FunctionDecl carrying
-    // FunctionTemplateSpecializationInfo.
-    assert(FD->getTemplateSpecializationKind() != TSK_Undeclared &&
-           "SpecInfoChanged on a function with no specialization info");
-    if (const auto *Restored =
-            Tracker.getFootprints().mostRecent<FunctionSpecializationFootprint>(
-                FD, MutationKind::SpecInfo))
-      restoreFootprint<FunctionSpecializationFootprint>(*Restored, *FD);
-    FD->setInstantiationIsPending(false);
-    Actions.trackForSweep(FD, uint32_t(MutationKind::SpecInfo));
-  }
-
-  if (Record().has(MutationKind::MemberSpecInfo)) {
-    assert(FD->getMemberSpecializationInfo());
-    if (const auto *Restored =
-            Tracker.getFootprints().mostRecent<MemberSpecializationFootprint>(
-                FD, MutationKind::MemberSpecInfo))
-      restoreFootprint<MemberSpecializationFootprint>(*Restored, *FD);
-    FD->setInstantiationIsPending(false);
-    Actions.trackForSweep(FD, uint32_t(MutationKind::MemberSpecInfo));
-  }
-}
-
-void ASTDeclUnmerger::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
-  // Unlinking discared Decl.
-  if (isDiscarded(D)) {
-    forgetMangledNames({GlobalDecl(D, Ctor_Complete), GlobalDecl(D, Ctor_Base),
-                        GlobalDecl(D, Ctor_Comdat)});
-    unlinkCommon(D);
-    unlinkRedeclChain<FunctionDecl>(D);
-    return;
-  }
-
-  // Restore decl.
-  if (hasRecord())
-    VisitFunctionDecl(D);
-}
-
-void ASTDeclUnmerger::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
-  // Unlinking discared Decl.
-  if (isDiscarded(D)) {
-    forgetMangledNames({GlobalDecl(D, Dtor_Deleting),
-                        GlobalDecl(D, Dtor_Complete), GlobalDecl(D, Dtor_Base),
-                        GlobalDecl(D, Dtor_Comdat)});
-    unlinkCommon(D);
-    unlinkRedeclChain<FunctionDecl>(D);
-    return;
-  }
-
-  // Restore decl.
-  if (hasRecord())
-    VisitFunctionDecl(D);
 }
 
 void ASTDeclUnmerger::VisitVarDecl(VarDecl *VD) {
   // Unlinking discared Decl.
   if (isDiscarded(VD)) {
-    if (!isa<ParmVarDecl>(VD) && !VD->getDeclContext()->isDependentContext())
-      forgetMangledNames(VD);
+    // if (!isa<ParmVarDecl>(VD) && !VD->getDeclContext()->isDependentContext())
+    //   forgetMangledNames(VD);
     unlinkCommon(VD);
     unlinkRedeclChain(VD);
     return;
@@ -999,30 +787,7 @@ void ASTDeclUnmerger::VisitVarDecl(VarDecl *VD) {
   if (!hasRecord())
     return;
 
-  // Restore decl.
-
-  if (Record().has(MutationKind::DefinitionInstantiate)) {
-    revertDefinitionArrival(VD);
-    forgetMangledNames(VD);
-  }
-
-  if (Record().has(MutationKind::SpecInfo)) {
-    auto *Spec = cast<VarTemplateSpecializationDecl>(VD);
-    if (const auto *Restored =
-            Tracker.getFootprints().mostRecent<VarSpecializationFootprint>(
-                Spec, MutationKind::SpecInfo))
-      restoreFootprint<VarSpecializationFootprint>(*Restored, *Spec);
-    Actions.trackForSweep(VD, uint32_t(MutationKind::SpecInfo));
-  }
-
-  if (Record().has(MutationKind::MemberSpecInfo)) {
-    assert(VD->getMemberSpecializationInfo());
-    if (const auto *Restored =
-            Tracker.getFootprints().mostRecent<MemberSpecializationFootprint>(
-                VD, MutationKind::MemberSpecInfo))
-      restoreFootprint<MemberSpecializationFootprint>(*Restored, *VD);
-    Actions.trackForSweep(VD, uint32_t(MutationKind::MemberSpecInfo));
-  }
+  // Restore decl state.
 }
 
 void ASTDeclUnmerger::VisitEnumDecl(EnumDecl *ED) {
@@ -1037,27 +802,7 @@ void ASTDeclUnmerger::VisitEnumDecl(EnumDecl *ED) {
   if (!hasRecord())
     return;
 
-  // Restore Decl state.
-  if (Record().has(MutationKind::TypeForDecl)) {
-    // for (const TagDecl *Redecl : ED->redecls()) {
-    //   const auto *Last = Tracker.getFootprints().mostRecent<const Type *>(
-    //       Redecl, MutationKind::TypeForDecl);
-    //   TODO: need to handle?
-    // }
-  }
-
-  if (Record().has(MutationKind::DefinitionInstantiate))
-    revertDefinitionArrival(ED);
-
-  if (Record().has(MutationKind::MemberSpecInfo)) {
-    assert(ED->getMemberSpecializationInfo());
-    if (const auto *Restored =
-            Tracker.getFootprints().mostRecent<MemberSpecializationFootprint>(
-                ED, MutationKind::MemberSpecInfo))
-      restoreFootprint<MemberSpecializationFootprint>(*Restored, *ED);
-
-    Actions.trackForSweep(ED, uint32_t(MutationKind::MemberSpecInfo));
-  }
+  // Restore decl state.
 }
 
 void ASTDeclUnmerger::VisitClassTemplateDecl(ClassTemplateDecl *CT) {
@@ -1084,13 +829,18 @@ void ASTDeclUnmerger::VisitClassTemplateDecl(ClassTemplateDecl *CT) {
   // Restore Decl.
   if (Record().has(MutationKind::SpecializationAdded)) {
     auto &Specs = CT->getSpecializations();
-    while (!Specs.empty()) {
-      auto It = Specs.end();
-      --It;
-      if (!Tracker.isFromThisPTU(&*It, ID))
-        break;
-      Specs.pop_back();
-    }
+    llvm::dbgs() << "Specs B ; " << Specs.size() << "\n";
+    removeSpec(Specs, [&](const void *Ptr) -> bool {
+      return Tracker.isFromThisPTU(Ptr, ID);
+    });
+    llvm::dbgs() << "Specs E ; " << Specs.size() << "\n";
+    // while (!Specs.empty()) {
+    //   auto It = Specs.end();
+    //   --It;
+    //   if (!Tracker.isFromThisPTU(&*It, ID))
+    //     break;
+    //   Specs.pop_back();
+    // }
   }
 }
 
@@ -1113,16 +863,6 @@ void ASTDeclUnmerger::VisitFunctionTemplateDecl(FunctionTemplateDecl *FTD) {
     return;
 
   // Restore Decl.
-  if (Record().has(MutationKind::SpecializationAdded)) {
-    auto &Specs = FTD->getSpecializations();
-    while (!Specs.empty()) {
-      auto It = Specs.end();
-      --It;
-      if (!Tracker.isFromThisPTU(It->getFunction(), ID))
-        break;
-      Specs.pop_back();
-    }
-  }
 }
 
 void ASTDeclUnmerger::VisitVarTemplateDecl(VarTemplateDecl *VTD) {
@@ -1145,16 +885,6 @@ void ASTDeclUnmerger::VisitVarTemplateDecl(VarTemplateDecl *VTD) {
     return;
 
   // Restore Decl.
-  if (Record().has(MutationKind::SpecializationAdded)) {
-    auto &Specs = VTD->getSpecializations();
-    while (!Specs.empty()) {
-      auto It = Specs.end();
-      --It;
-      if (!Tracker.isFromThisPTU(&*It, ID))
-        break;
-      Specs.pop_back();
-    }
-  }
 }
 
 void ASTDeclUnmerger::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
@@ -1164,6 +894,8 @@ void ASTDeclUnmerger::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
     unlinkRedeclChain(D);
     return;
   }
+
+  // Restore decl;
 }
 
 void ASTDeclUnmerger::VisitTypedefNameDecl(TypedefNameDecl *D) {
@@ -1173,6 +905,8 @@ void ASTDeclUnmerger::VisitTypedefNameDecl(TypedefNameDecl *D) {
     unlinkRedeclChain(D);
     return;
   }
+
+  // Restore decl;
 }
 
 void ASTDeclUnmerger::VisitUsingShadowDecl(UsingShadowDecl *D) {
@@ -1182,6 +916,8 @@ void ASTDeclUnmerger::VisitUsingShadowDecl(UsingShadowDecl *D) {
     unlinkRedeclChain(D);
     return;
   }
+
+  // Restore decl;
 }
 
 void SemaCacheReverter::restoreSpecialMemberCache(PTUID ID) {
@@ -1192,7 +928,8 @@ void SemaCacheReverter::restoreSpecialMemberCache(PTUID ID) {
   llvm::SmallVector<Sema::SpecialMemberCacheKey, 8> ToRemove;
   for (auto &Entry : SemaRef.SpecialMemberCache) {
     CXXMethodDecl *MD = Entry.second.getMethod();
-    if (MD && (Tracker.isFromThisPTU(MD, ID) || Cur.ImplicitDecls.contains(MD)))
+    if (MD && (Tracker.isFromThisPTU(MD, ID) ||
+               Cur.ImplicitlyGeneratedDecls.contains(MD)))
       ToRemove.push_back(Entry.first);
   }
   for (const auto &Key : ToRemove)
@@ -1246,7 +983,8 @@ void PTUMutationActions::restore(TranslationUnitDecl *ThisTU) {
   for (auto &[D, Rec] : Cur.Mutations)
     Umerger.restoreDecl(const_cast<Decl *>(D), Rec);
 
-  // 3. Cur.ImplicitDecls: Declarations created by this PTU. Unlink them from
+  // 3. Cur.ImplicitlyGeneratedDecls: Declarations created by this PTU. Unlink
+  // them from
   //    the compiler's shared state.
   //
   //    This is the counterpart to the commit, but
@@ -1257,18 +995,20 @@ void PTUMutationActions::restore(TranslationUnitDecl *ThisTU) {
   // and DeclContext lookup structures, or restoring declaration state (e.g.,
   // CXXRecordDecl::DefinitionData).
 
-  for (const Decl *D : Cur.ImplicitDecls) {
-    if (isReachableFromThisTU(D, ThisTU))
-      continue;
-    Umerger.Visit(const_cast<Decl *>(D));
-  }
+  // FIXME: Uncomment once we handle restoration of Implicit Decl.
+  //   for (const Decl *D : Cur.ImplicitlyGeneratedDecls) {
+  //     if (isReachableFromThisTU(D, ThisTU))
+  //       continue;
+  //     Umerger.Visit(const_cast<Decl *>(D));
+  //   }
 
   Umerger.Visit(ThisTU);
 
   // SpecialMemberCache stores the CXXMethodDecl* from a previous
   // LookupSpecialMember() call. If it was created by a PTU being rolled back,
   // the cache entry is stale, so remove it here.
-  SemaCache.restoreSpecialMemberCache(ID);
+  // FIXME: Uncomment once we handle restoration of CXXRecordDecl.
+  // SemaCache.restoreSpecialMemberCache(ID);
 
   // Must be last: Cur/ID/ThisTU refer to data owned by this PTU, and
   // popCurrentPTU() destroys that entry. This runs for both committed and
@@ -1308,73 +1048,24 @@ void PTUMutationActions::restore(TranslationUnitDecl *ThisTU) {
 /// previous state.
 
 void PTUMutationRecorder::CompletedTagDefinition(const TagDecl *D) {
-  if (!D->isDefinedOutsideFunctionOrMethod())
-    return; // ordinary local class -- structurally unreachable by any other
-            // PTU
-
-  PTUStateInfo &Cur = Tracker.current();
-  if (Tracker.isFromThisPTU(D, Tracker.currentID())) {
-    if (D->isImplicit())
-      Cur.ImplicitDecls.insert(D);
-    return;
-  }
-
-  DeclShape S = classifyShape(D);
-  if (false)
-    Cur.noteMutated(D, S, MutationKind::DefinitionInstantiate);
-
-  /// Handle this for MemberSpec because the notifier does not guarantee whether
-  /// it fires before or after the mutation. We cannot reliably compare the
-  /// state here, so mutation detection is deferred to the verification layer.
-  if (S == DeclShape::Enum) {
-    if (const EnumDecl *ED = dyn_cast<EnumDecl>(D);
-        ED && ED->getMemberSpecializationInfo())
-      Cur.noteMutated(D, S, MutationKind::MemberSpecInfo);
-  } else if (S == DeclShape::Class) {
-    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D);
-        RD && RD->getMemberSpecializationInfo())
-      Cur.noteMutated(D, S, MutationKind::MemberSpecInfo);
-    if (isa<ClassTemplateSpecializationDecl>(D))
-      Cur.noteMutated(D, S, MutationKind::SpecInfo);
-  }
+  // TODO;
 }
 
 void PTUMutationRecorder::AddedVisibleDecl(const DeclContext *DC,
                                            const Decl *D) {
-  PTUStateInfo &Cur = Tracker.current();
-  if (D->isImplicit())
-    Cur.ImplicitDecls.insert(D);
-
-  if (Tracker.isFromThisPTU(DC, Cur.ID) || Cur.TouchedDCs.contains(DC))
-    return;
-
-  Cur.TouchedDCs.insert(DC);
+  // TODO;
 }
 
 void PTUMutationRecorder::AddedCXXImplicitMember(const CXXRecordDecl *RD,
                                                  const Decl *D) {
-  if (!RD->isDefinedOutsideFunctionOrMethod())
-    return; // ordinary local class -- structurally unreachable by any other
-            // PTU
-
-  PTUStateInfo &Cur = Tracker.current();
-
-  if (D->isImplicit())
-    Cur.ImplicitDecls.insert(D);
-
-  // cover only not from this ptu.
-  if (Tracker.isFromThisPTU(RD, Cur.ID))
-    return;
-
-  Cur.noteMutated(RD, DeclShape::Class, MutationKind::DefinitionData);
+  // TODO;
 }
 
 template <typename TemplateT, typename SpecT>
 void PTUMutationRecorder::noteTemplateDeclMutation(const TemplateT *TD,
-                                                   const SpecT *Spec,
-                                                   DeclShape S) {
+                                                   const SpecT *Spec) {
   PTUStateInfo &Cur = Tracker.current();
-  Cur.ImplicitDecls.insert(Spec);
+  Cur.ImplicitlyGeneratedDecls.insert(Spec);
 
   if (Tracker.isFromThisPTU(TD, Cur.ID))
     return;
@@ -1384,17 +1075,17 @@ void PTUMutationRecorder::noteTemplateDeclMutation(const TemplateT *TD,
 
 void PTUMutationRecorder::AddedCXXTemplateSpecialization(
     const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
-  noteTemplateDeclMutation(TD, D, DeclShape::Class);
+  noteTemplateDeclMutation(TD, D);
 }
 
 void PTUMutationRecorder::AddedCXXTemplateSpecialization(
     const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
-  noteTemplateDeclMutation(TD, D, DeclShape::Var);
+  // TODO
 }
 
 void PTUMutationRecorder::AddedCXXTemplateSpecialization(
     const FunctionTemplateDecl *TD, const FunctionDecl *D) {
-  noteTemplateDeclMutation(TD, D, DeclShape::Function);
+  // TODO
 }
 
 void PTUMutationRecorder::noteDefinitionInstantiated(const Decl *D) {
@@ -1407,54 +1098,13 @@ void PTUMutationRecorder::noteDefinitionInstantiated(const Decl *D) {
     const auto *VD = dyn_cast<VarDecl>(D);
     if (VD && VD->getPreviousDecl() &&
         !Tracker.isFromThisPTU(VD->getCanonicalDecl(), Cur.ID))
-      Cur.ImplicitDecls.insert(D);
+      Cur.ImplicitlyGeneratedDecls.insert(D);
     return;
   }
 
   Cur.noteMutated(D, classifyShape(D), MutationKind::DefinitionInstantiate);
 }
 
-/// InstantiationRequested fires when Sema decides a template entity needs
-/// instantiating -- before the instantiation actually happens.
-void PTUMutationRecorder::InstantiationRequested(const ValueDecl *D) {
-  PTUStateInfo &Cur = Tracker.current();
-
-  if (Tracker.isFromThisPTU(D, Cur.ID)) {
-    // Created this PTU -- the creation path covers it, no mutation to note.
-    // But an implicitly-created decl may never be appended to any lexical
-    // chain, so walkTU would never see it. Record it here as the
-    // only path that will.
-    if (D->isImplicit())
-      Cur.ImplicitDecls.insert(D);
-    return;
-  }
-
-  DeclShape S;
-  MutationKind K = MutationKind::None;
-
-  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
-    S = DeclShape::Function;
-    if (FD->getMemberSpecializationInfo())
-      K = MutationKind::MemberSpecInfo;
-    else if (FD->getTemplateSpecializationKind() != TSK_Undeclared)
-      K = MutationKind::SpecInfo;
-    else
-      return; // neither -- nothing this notifier can be about
-  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
-    S = DeclShape::Var;
-    if (VD->getMemberSpecializationInfo())
-      K = MutationKind::MemberSpecInfo;
-    else if (isa<VarTemplateSpecializationDecl>(VD))
-      K = MutationKind::SpecInfo;
-    else
-      return;
-  } else {
-    return; // no other ValueDecl kind participates in instantiation
-  }
-
-  Cur.noteMutated(D, S, K);
-}
-
 // Remove all entries for each (Owner, Kind) key written by this PTU.
 void IncrementalStateTracker::undoLastEntries() {
   PTUStateInfo &Cur = current();
diff --git a/clang/lib/Interpreter/ErrorRecovery.h b/clang/lib/Interpreter/ErrorRecovery.h
index c596e765cc28d6..fc306ef58b0fe0 100644
--- a/clang/lib/Interpreter/ErrorRecovery.h
+++ b/clang/lib/Interpreter/ErrorRecovery.h
@@ -194,21 +194,18 @@ class PTUMutationActions;
 /// checkpoint taken before each PTU began.
 class PTUCheckpointLedger {
   const ASTContext &Ctx;
-  llvm::SmallVector<llvm::SlabCheckPoint, 16> CheckpointBeforePTU;
+  llvm::SmallVector<int64_t, 16> CheckpointBeforePTU;
   llvm::BitVector Dead;
 
-  bool isAfter(const void *Ptr, PTUID ID) const {
-    return Ctx.getAllocator().isAfterCheckpoint(Ptr, CheckpointBeforePTU[ID]);
-  }
-
 public:
   explicit PTUCheckpointLedger(const ASTContext &Ctx) : Ctx(Ctx) {}
 
   /// Called once, right before parsing PTU \p ID begins.
-  void recordCheckpoint(PTUID ID, llvm::SlabCheckPoint CP) {
+  void recordCheckpoint(PTUID ID) {
     assert(ID == CheckpointBeforePTU.size() &&
            "PTUs must be recorded in order");
-    CheckpointBeforePTU.push_back(CP);
+    CheckpointBeforePTU.push_back(Ctx.getAllocator().identifyKnownObject(
+        Ctx.getAllocator().Allocate(sizeof(int), alignof(int))));
     Dead.push_back(false);
   }
 
@@ -217,26 +214,8 @@ class PTUCheckpointLedger {
     assert(ID < CheckpointBeforePTU.size());
     assert(!Dead[ID] &&
            "querying provenance against a PTU that no longer exists");
-    return isAfter(Ptr, ID);
-  }
-
-  /// The PTU that allocated \p Ptr, or nullopt if it predates the oldest
-  /// recorded checkpoint. The newest ID whose checkpoint \p Ptr is after.
-  std::optional<PTUID> attribute(const void *Ptr) const {
-    size_t Lo = 0, Hi = CheckpointBeforePTU.size();
-    std::optional<PTUID> Result;
-    while (Lo < Hi) {
-      size_t Mid = Lo + (Hi - Lo) / 2;
-      if (isAfter(Ptr, Mid)) {
-        Result = static_cast<PTUID>(Mid);
-        Lo = Mid + 1;
-      } else {
-        Hi = Mid;
-      }
-    }
-    assert((!Result || !Dead[*Result]) &&
-           "Ptr belongs to a PTU that was already rolled back");
-    return Result;
+    return Ctx.getAllocator().identifyKnownObject(Ptr) >=
+           CheckpointBeforePTU[ID];
   }
 
   /// FIXME: Pop back CheckpointBeforePTU once memory restoration is supported.
@@ -345,7 +324,7 @@ struct PTUStateInfo {
 
   llvm::MapVector<const Decl *, MutationRecord> Mutations;
 
-  llvm::SmallPtrSet<const Decl *, 4> ImplicitDecls;
+  llvm::SmallPtrSet<const Decl *, 4> ImplicitlyGeneratedDecls;
 
   /// Set exactly when AddedCXXImplicitMember fires this PTU.
   bool HadImplicitCXXMember = false;
@@ -489,9 +468,9 @@ class IncrementalStateTracker {
   PTUID currentID() const { return current().ID; }
   bool hasOpenPTU() const { return !PTUStack.empty(); }
 
-  void beginPTU(llvm::SlabCheckPoint CP) {
+  void beginPTU() {
     PTUID ID = NextID++;
-    PTUSlabCheckpoints.recordCheckpoint(ID, CP);
+    PTUSlabCheckpoints.recordCheckpoint(ID);
     PTUStack.emplace_back(ID);
   }
 
@@ -516,7 +495,7 @@ class IncrementalStateTracker {
   }
 };
 
-// Once place to revert Sema specific cache.
+// // Once place to revert Sema specific cache.
 class SemaCacheReverter {
   Sema &SemaRef;
   IncrementalStateTracker &Tracker;
@@ -603,11 +582,7 @@ class PTUMutationRecorder : public ASTMutationListener {
   IncrementalStateTracker &Tracker;
 
   template <typename TemplateT, typename SpecT>
-  void noteTemplateDeclMutation(const TemplateT *TD, const SpecT *Spec,
-                                DeclShape S);
-
-  void noteExceptionSpecMutation(const FunctionDecl *FD,
-                                 MutationKind K = MutationKind::ExceptionSpec);
+  void noteTemplateDeclMutation(const TemplateT *TD, const SpecT *Spec);
 
   void noteDefinitionInstantiated(const Decl *D);
 
@@ -645,7 +620,8 @@ class PTUMutationRecorder : public ASTMutationListener {
   void ResolvedExceptionSpec(const FunctionDecl *FD) override {}
 
   /// A function's return type has been deduced.
-  void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override {}
+  void DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) override {
+  }
 
   /// A virtual destructor's operator delete has been resolved.
   void ResolvedOperatorDelete(const CXXDestructorDecl *DD,
@@ -667,7 +643,7 @@ class PTUMutationRecorder : public ASTMutationListener {
 
   /// An implicit member got a definition.
   void CompletedImplicitDefinition(const FunctionDecl *D) override {
-    noteDefinitionInstantiated(D);
+    // noteDefinitionInstantiated(D);
   }
 
   /// The instantiation of a templated function or variable was
@@ -676,14 +652,10 @@ class PTUMutationRecorder : public ASTMutationListener {
   void InstantiationRequested(const ValueDecl *D) override;
 
   /// A templated variable's definition was implicitly instantiated.
-  void VariableDefinitionInstantiated(const VarDecl *D) override {
-    noteDefinitionInstantiated(D);
-  }
+  void VariableDefinitionInstantiated(const VarDecl *D) override {}
 
   /// A function template's definition was instantiated.
-  void FunctionDefinitionInstantiated(const FunctionDecl *D) override {
-    noteDefinitionInstantiated(D);
-  }
+  void FunctionDefinitionInstantiated(const FunctionDecl *D) override {}
 
   /// A default argument was instantiated.
   void DefaultArgumentInstantiated(const ParmVarDecl *D) override {}

>From 5e158161d56f66f0041bd1a73fe42f4e32e1a438 Mon Sep 17 00:00:00 2001
From: SahilPatidar <patidarsahil2001 at gmail.com>
Date: Mon, 30 Nov 2026 09:43:27 +0530
Subject: [PATCH 3/5] Refactor the code

---
 clang/include/clang/AST/DeclBase.h          |   3 +
 clang/include/clang/AST/DeclTemplate.h      |   1 +
 clang/lib/Interpreter/CMakeLists.txt        |   1 +
 clang/lib/Interpreter/ErrorRecovery.cpp     | 105 +++----
 clang/lib/Interpreter/ErrorRecovery.h       |  25 +-
 clang/lib/Interpreter/IncrementalAction.cpp |   4 +
 clang/lib/Interpreter/IncrementalAction.h   |   1 +
 clang/lib/Interpreter/IncrementalParser.cpp | 310 ++++++++++----------
 clang/lib/Interpreter/IncrementalParser.h   |   8 +
 9 files changed, 227 insertions(+), 231 deletions(-)

diff --git a/clang/include/clang/AST/DeclBase.h b/clang/include/clang/AST/DeclBase.h
index 73bfe0a03bbe64..a91c46931c2dc3 100644
--- a/clang/include/clang/AST/DeclBase.h
+++ b/clang/include/clang/AST/DeclBase.h
@@ -257,6 +257,7 @@ class alignas(8) Decl {
   llvm::PointerIntPair<Decl *, 3, ModuleOwnershipKind> NextInContextAndBits;
 
 private:
+  friend class ASTDeclUnmerger;
   friend class DeclContext;
 
   struct MultipleDC {
@@ -1467,6 +1468,8 @@ enum class LinkageSpecLanguageIDs;
 class DeclContext {
   /// For makeDeclVisibleInContextImpl
   friend class ASTDeclReader;
+  /// For Clang-Repl's error-recovery
+  friend class ASTDeclUnmerger;
   /// For checking the new bits in the Serialization part.
   friend class ASTDeclWriter;
   /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
diff --git a/clang/include/clang/AST/DeclTemplate.h b/clang/include/clang/AST/DeclTemplate.h
index aae6afe164c086..5c1a6a1df5ac34 100644
--- a/clang/include/clang/AST/DeclTemplate.h
+++ b/clang/include/clang/AST/DeclTemplate.h
@@ -2324,6 +2324,7 @@ class ClassTemplateDecl : public RedeclarableTemplateDecl {
 public:
 
   friend class ASTDeclReader;
+  friend class ASTDeclUnmerger;
   friend class ASTDeclWriter;
   friend class TemplateDeclInstantiator;
 
diff --git a/clang/lib/Interpreter/CMakeLists.txt b/clang/lib/Interpreter/CMakeLists.txt
index 5e2937a2e7dcb9..a28c9d80796d49 100644
--- a/clang/lib/Interpreter/CMakeLists.txt
+++ b/clang/lib/Interpreter/CMakeLists.txt
@@ -31,6 +31,7 @@ endif()
 add_clang_library(clangInterpreter
   DeviceOffload.cpp
   CodeCompletion.cpp
+  ErrorRecovery.cpp
   IncrementalAction.cpp
   IncrementalExecutorBuilder.cpp
   IncrementalParser.cpp
diff --git a/clang/lib/Interpreter/ErrorRecovery.cpp b/clang/lib/Interpreter/ErrorRecovery.cpp
index 5ae4ede3aac24e..2c4cb351a4b3e4 100644
--- a/clang/lib/Interpreter/ErrorRecovery.cpp
+++ b/clang/lib/Interpreter/ErrorRecovery.cpp
@@ -39,10 +39,9 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
 private:
   PTUID ID;
   IncrementalStateTracker &Tracker;
-  PTUMutationActions &Actions;
+  [[maybe_unused]] PTUMutationActions &Actions;
   Sema &SemaRef;
-  SemaCacheReverter &SemaCache;
-  CodeGenerator *CodeGen;
+  [[maybe_unused]] SemaCacheReverter &SemaCache;
   MutationRecord *Rec = nullptr;
 
   llvm::SmallPtrSet<const Decl *, 16> RepairedChains;
@@ -220,9 +219,9 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
 
   ASTDeclUnmerger(PTUID ID, IncrementalStateTracker &Tracker,
                   PTUMutationActions &Action, Sema &SemaRef,
-                  SemaCacheReverter &SemaCache, CodeGenerator *CodeGen)
+                  SemaCacheReverter &SemaCache)
       : ID(ID), Tracker(Tracker), Actions(Action), SemaRef(SemaRef),
-        SemaCache(SemaCache), CodeGen(CodeGen) {}
+        SemaCache(SemaCache) {}
 
   static DefinitionDataFootprint
   createDefinitionDataFootprint(const CXXRecordDecl &RD) {
@@ -254,7 +253,7 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
     FP.restore(Owner);
   }
 
-  void restoreDecl(Decl *D, MutationRecord &R) {
+  void RestoreDecl(Decl *D, MutationRecord &R) {
     ScopedMutationRecord Guard(Rec, &R);
     Visit(D);
   }
@@ -308,7 +307,7 @@ static DeclShape classifyShape(const Decl *D) {
 /// checks whether the decl is still in a mutation-sensitive state, meaning that
 /// a later PTU can modify it. Because of this, we need to track its state. This
 /// function provides a single place to decide whether a decl needs to be
-/// committed or not. It is called from commitDecl to determine whether a new
+/// committed or not. It is called from CommitDecl to determine whether a new
 /// decl needs to be tracked.
 ///
 /// This requires DeclShape S and Decl to determine which mutation kinds
@@ -383,6 +382,8 @@ uint32_t PTUMutationActions::DeclNeedingTracking(DeclShape S, const Decl *D) {
     }
     return Kinds;
   }
+  case DeclShape::Template:
+  case DeclShape::Typedef:
   case DeclShape::None:
     return 0;
   }
@@ -475,6 +476,8 @@ uint32_t PTUMutationActions::confirmMutation(const Decl *D, DeclShape S,
     }
     break;
   }
+  case DeclShape::Template:
+  case DeclShape::Typedef:
   case DeclShape::None:
     break;
   }
@@ -564,23 +567,24 @@ void PTUStateInfo::verifyMutations(PTUMutationActions &Actions) {
   });
 }
 
-static bool isReachableFromThisTU(const Decl *D,
-                                  const TranslationUnitDecl *ThisTU) {
-  const DeclContext *DC = D->getLexicalDeclContext();
+// FIXME: Uncomment once we handle restoration of Implicit Decl.
+// static bool isReachableFromThisTU(const Decl *D,
+//                                   const TranslationUnitDecl *ThisTU) {
+//   const DeclContext *DC = D->getLexicalDeclContext();
 
-  for (; DC; DC = DC->getLexicalParent()) {
-    if (DC->containsDecl(const_cast<Decl *>(D))) {
-      const DeclContext *Parent = DC;
+//   for (; DC; DC = DC->getLexicalParent()) {
+//     if (DC->containsDecl(const_cast<Decl *>(D))) {
+//       const DeclContext *Parent = DC;
 
-      while (Parent && !Parent->isTranslationUnit())
-        Parent = Parent->getLexicalParent();
+//       while (Parent && !Parent->isTranslationUnit())
+//         Parent = Parent->getLexicalParent();
 
-      return Parent == ThisTU;
-    }
-  }
+//       return Parent == ThisTU;
+//     }
+//   }
 
-  return false;
-}
+//   return false;
+// }
 
 /// -----------------------------------------------------------------------
 //////////////////////// PTUMutationActions::commit ///////////////////////
@@ -615,7 +619,7 @@ void PTUMutationActions::VisitDeclContext(const DeclContext *DC) {
   for (const Decl *D : DC->decls()) {
     if (shouldRecurseInto(D))
       VisitDeclContext(cast<DeclContext>(D));
-    commitDecl(D, nullptr);
+    CommitDecl(D, nullptr);
   }
 }
 
@@ -641,7 +645,7 @@ void PTUMutationActions::VisitRedeclarableTemplateDecl(
   // TODO
 }
 
-void PTUMutationActions::commitDecl(const Decl *D, MutationRecord *R) {
+void PTUMutationActions::CommitDecl(const Decl *D, MutationRecord *R) {
   if (!D->isDefinedOutsideFunctionOrMethod())
     return;
 
@@ -669,7 +673,7 @@ void PTUMutationActions::commitDecl(const Decl *D, MutationRecord *R) {
   Rec = OldRec;
 }
 
-void PTUMutationActions::commit(TranslationUnitDecl *ThisTU) {
+void PTUMutationActions::CommitPTU(TranslationUnitDecl *ThisTU) {
   PTUStateInfo &Cur = Tracker.current();
   assert(!Cur.Commited && "Current PTUState is already commited");
   Cur.ThisPTU = ThisTU;
@@ -690,14 +694,14 @@ void PTUMutationActions::commit(TranslationUnitDecl *ThisTU) {
   // 3. Update the tracking state of declarations from the previous PTU using
   //    Cur.Mutations reported by ASTMutationListener and HiddenMutationTracker.
   for (auto &[D, Rec] : Cur.Mutations)
-    commitDecl(D, &Rec);
+    CommitDecl(D, &Rec);
 
   // 4. Cur.ImplicitlyGeneratedDecls: Declarations created by this PTU. Register
   // them for
   //    tracking if they have mutation-sensitive state that can be modified by
   //    later PTUs.
   //
-  // commitDecl: Decides what to do with declarations created by the current
+  // CommitDecl: Decides what to do with declarations created by the current
   // PTU, such as whether a declaration needs to be tracked or not.
   // FIXME: Uncomment once we handle restoration of Implicit Decl.
   // for (const Decl *D : Cur.ImplicitlyGeneratedDecls) {
@@ -705,7 +709,7 @@ void PTUMutationActions::commit(TranslationUnitDecl *ThisTU) {
   //     continue;
   //   if (shouldRecurseInto(D))
   //     VisitDeclContext(cast<DeclContext>(D));
-  //   commitDecl(D, nullptr);
+  //   CommitDecl(D, nullptr);
   // }
 
   // Iterate over all declarations in this TU and register them whether they
@@ -829,18 +833,9 @@ void ASTDeclUnmerger::VisitClassTemplateDecl(ClassTemplateDecl *CT) {
   // Restore Decl.
   if (Record().has(MutationKind::SpecializationAdded)) {
     auto &Specs = CT->getSpecializations();
-    llvm::dbgs() << "Specs B ; " << Specs.size() << "\n";
     removeSpec(Specs, [&](const void *Ptr) -> bool {
       return Tracker.isFromThisPTU(Ptr, ID);
     });
-    llvm::dbgs() << "Specs E ; " << Specs.size() << "\n";
-    // while (!Specs.empty()) {
-    //   auto It = Specs.end();
-    //   --It;
-    //   if (!Tracker.isFromThisPTU(&*It, ID))
-    //     break;
-    //   Specs.pop_back();
-    // }
   }
 }
 
@@ -940,7 +935,7 @@ void SemaCacheReverter::restoreVTableUsed(CXXRecordDecl *RD) {
   SemaRef.VTablesUsed.erase(RD->getCanonicalDecl());
 }
 
-void PTUMutationActions::restore(TranslationUnitDecl *ThisTU) {
+void PTUMutationActions::RestorePTU(TranslationUnitDecl *ThisTU) {
   PTUStateInfo &Cur = Tracker.current();
   assert((!Cur.Commited || ThisTU == Cur.ThisPTU) &&
          "MostRecentTU doesn't match the TU recorded at commit time");
@@ -964,9 +959,9 @@ void PTUMutationActions::restore(TranslationUnitDecl *ThisTU) {
         [&](const Decl *D) { return Tracker.isFromThisPTU(D, ID); });
     Tracker.undoLastEntries();
   } else {
-    // Same as the commit() step, but performed here because this PTU failed and
-    // was never committed. Since the commit step was never executed, we need to
-    // perform it here for an uncommitted PTU.
+    // Same as the CommitPTU() step, but performed here because this PTU failed
+    // and was never committed. Since the commit step was never executed, we
+    // need to perform it here for an uncommitted PTU.
     Cur.verifyMutations(*this);
     Tracker.getHiddenMutationTracker().sweep(
         *this, [&](const Decl *D, DeclShape S, uint32_t K) {
@@ -974,14 +969,14 @@ void PTUMutationActions::restore(TranslationUnitDecl *ThisTU) {
         });
   }
 
-  ASTDeclUnmerger Umerger(ID, Tracker, *this, SemaRef, SemaCache, CodeGen);
+  ASTDeclUnmerger Umerger(ID, Tracker, *this, SemaRef, SemaCache);
 
-  // 2. Same as the commit() step, but in reverse: commit() updates the
+  // 2. Same as the CommitPTU() step, but opposite of: CommitPTU() updates the
   //    IncrementalStateTracker with the mutated state of declarations from the
   //    previous state. Here, we restore each mutated declaration using its most
   //    recent state in IncrementalStateTracker (i.e., the PTU(N-1) state).
   for (auto &[D, Rec] : Cur.Mutations)
-    Umerger.restoreDecl(const_cast<Decl *>(D), Rec);
+    Umerger.RestoreDecl(const_cast<Decl *>(D), Rec);
 
   // 3. Cur.ImplicitlyGeneratedDecls: Declarations created by this PTU. Unlink
   // them from
@@ -1047,20 +1042,6 @@ void PTUMutationActions::restore(TranslationUnitDecl *ThisTU) {
 /// Such a decl needs to be tracked for unlinking rather than restoring its
 /// previous state.
 
-void PTUMutationRecorder::CompletedTagDefinition(const TagDecl *D) {
-  // TODO;
-}
-
-void PTUMutationRecorder::AddedVisibleDecl(const DeclContext *DC,
-                                           const Decl *D) {
-  // TODO;
-}
-
-void PTUMutationRecorder::AddedCXXImplicitMember(const CXXRecordDecl *RD,
-                                                 const Decl *D) {
-  // TODO;
-}
-
 template <typename TemplateT, typename SpecT>
 void PTUMutationRecorder::noteTemplateDeclMutation(const TemplateT *TD,
                                                    const SpecT *Spec) {
@@ -1078,20 +1059,10 @@ void PTUMutationRecorder::AddedCXXTemplateSpecialization(
   noteTemplateDeclMutation(TD, D);
 }
 
-void PTUMutationRecorder::AddedCXXTemplateSpecialization(
-    const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
-  // TODO
-}
-
-void PTUMutationRecorder::AddedCXXTemplateSpecialization(
-    const FunctionTemplateDecl *TD, const FunctionDecl *D) {
-  // TODO
-}
-
 void PTUMutationRecorder::noteDefinitionInstantiated(const Decl *D) {
   PTUStateInfo &Cur = Tracker.current();
   if (Tracker.isFromThisPTU(D, Cur.ID)) {
-    // Normally, walkDecls covers declarations created in this PTU.
+    // Normally, VisitDecls covers declarations created in this PTU.
     // But an out-of-line static data member is a separate VarDecl whose
     // lexical context is the class, so the namespace/TU walk won't find it.
     // Process it like other implicit declarations instead.
diff --git a/clang/lib/Interpreter/ErrorRecovery.h b/clang/lib/Interpreter/ErrorRecovery.h
index fc306ef58b0fe0..8a036941bbfaee 100644
--- a/clang/lib/Interpreter/ErrorRecovery.h
+++ b/clang/lib/Interpreter/ErrorRecovery.h
@@ -329,9 +329,6 @@ struct PTUStateInfo {
   /// Set exactly when AddedCXXImplicitMember fires this PTU.
   bool HadImplicitCXXMember = false;
 
-  /// here touched info mean other this belongs to other PTUs;
-  llvm::SmallPtrSet<const DeclContext *, 8> TouchedDCs;
-
   /// Every (Owner, Kind) key this PTU's own commit() wrote a FootprintStore
   /// entry for.
   llvm::SmallVector<std::pair<const Decl *, MutationKind>, 8> TouchedFootprints;
@@ -540,9 +537,6 @@ class PTUMutationActions : public ConstDeclVisitor<PTUMutationActions> {
   Sema &getSema() const { return SemaRef; }
   CodeGenerator *getCodeGen() const { return CodeGen; }
 
-  template <typename DeclStatePolicyT>
-  void walkDecls(DeclContext *DC, DeclStatePolicyT &Policy);
-
   uint32_t DeclNeedingTracking(DeclShape S, const Decl *D);
 
   uint32_t confirmMutation(const Decl *D, DeclShape S, uint32_t FlaggedKinds);
@@ -563,18 +557,18 @@ class PTUMutationActions : public ConstDeclVisitor<PTUMutationActions> {
   void VisitEnumDecl(const EnumDecl *ED);
   void VisitRedeclarableTemplateDecl(const RedeclarableTemplateDecl *RT);
 
-  void commitDecl(const Decl *D, MutationRecord *Rec);
+  void CommitDecl(const Decl *D, MutationRecord *Rec);
 
   // Actual commit action: updates IncrementalStateTracker tracking info for
   // decls from the previous PTU after a successful PTU. And add tracking info
   // for newly created Decls
   //
-  void commit(TranslationUnitDecl *MostRecentTU);
+  void CommitPTU(TranslationUnitDecl *MostRecentTU);
 
   // Restore action: restores decls from the previous PTU using
   // IncrementalStateTracker tracking info and unlinks decls created by this
   // PTU.
-  void restore(TranslationUnitDecl *MostRecentTU);
+  void RestorePTU(TranslationUnitDecl *MostRecentTU);
 };
 
 class PTUMutationRecorder : public ASTMutationListener {
@@ -590,13 +584,14 @@ class PTUMutationRecorder : public ASTMutationListener {
   PTUMutationRecorder(IncrementalStateTracker &Tracker) : Tracker(Tracker) {}
 
   /// A new TagDecl definition was completed.
-  void CompletedTagDefinition(const TagDecl *D) override;
+  void CompletedTagDefinition(const TagDecl *D) override {}
 
   /// A new declaration with name has been added to a DeclContext.
-  void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override;
+  void AddedVisibleDecl(const DeclContext *DC, const Decl *D) override {}
 
   /// An implicit member was added after the definition was completed.
-  void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override;
+  void AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) override {
+  }
 
   /// A template specialization (or partial one) was added to the
   /// template declaration.
@@ -608,12 +603,12 @@ class PTUMutationRecorder : public ASTMutationListener {
   /// template declaration.
   void AddedCXXTemplateSpecialization(
       const VarTemplateDecl *TD,
-      const VarTemplateSpecializationDecl *D) override;
+      const VarTemplateSpecializationDecl *D) override {}
 
   /// A template specialization (or partial one) was added to the
   /// template declaration.
   void AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
-                                      const FunctionDecl *D) override;
+                                      const FunctionDecl *D) override {}
 
   /// A function's exception specification has been evaluated or
   /// instantiated.
@@ -649,7 +644,7 @@ class PTUMutationRecorder : public ASTMutationListener {
   /// The instantiation of a templated function or variable was
   /// requested. In particular, the point of instantiation and template
   /// specialization kind of \p D may have changed.
-  void InstantiationRequested(const ValueDecl *D) override;
+  void InstantiationRequested(const ValueDecl *D) override {}
 
   /// A templated variable's definition was implicitly instantiated.
   void VariableDefinitionInstantiated(const VarDecl *D) override {}
diff --git a/clang/lib/Interpreter/IncrementalAction.cpp b/clang/lib/Interpreter/IncrementalAction.cpp
index 2c1ad404a3e7d7..67a653b2c93912 100644
--- a/clang/lib/Interpreter/IncrementalAction.cpp
+++ b/clang/lib/Interpreter/IncrementalAction.cpp
@@ -157,4 +157,8 @@ bool InProcessPrintingASTConsumer::HandleTopLevelDecl(DeclGroupRef DGR) {
   return MultiplexConsumer::HandleTopLevelDecl(DGR);
 }
 
+ASTMutationListener *InProcessPrintingASTConsumer::GetASTMutationListener() {
+  return Interp.getCompilerInstance()->getASTContext().getASTMutationListener();
+}
+
 } // namespace clang
diff --git a/clang/lib/Interpreter/IncrementalAction.h b/clang/lib/Interpreter/IncrementalAction.h
index 2893ff7b5baa6d..9ce7b91bb3357c 100644
--- a/clang/lib/Interpreter/IncrementalAction.h
+++ b/clang/lib/Interpreter/IncrementalAction.h
@@ -84,6 +84,7 @@ class InProcessPrintingASTConsumer final : public MultiplexConsumer {
   InProcessPrintingASTConsumer(std::unique_ptr<ASTConsumer> C, Interpreter &I);
 
   bool HandleTopLevelDecl(DeclGroupRef DGR) override;
+  ASTMutationListener *GetASTMutationListener() override;
 };
 
 } // end namespace clang
diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp
index dfcafc7d7dce5d..d8f76fd08763a7 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -10,6 +10,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "ErrorRecovery.h"
 #include "IncrementalParser.h"
 #include "IncrementalAction.h"
 
@@ -41,6 +42,13 @@ IncrementalParser::IncrementalParser(CompilerInstance &Instance,
                                      std::list<PartialTranslationUnit> &PTUs)
     : S(Instance.getSema()), Act(Act), PTUs(PTUs) {
   llvm::ErrorAsOutParameter EAO(&Err);
+
+  Tracker = std::make_unique<IncrementalStateTracker>(S.getASTContext());
+  MutationActions = std::make_unique<PTUMutationActions>(
+      *Tracker, S, Act->getCodeGen());
+  MutationRecorder = std::make_unique<PTUMutationRecorder>(*Tracker);
+  S.getASTContext().setASTMutationListener(MutationRecorder.get());
+
   Consumer = &S.getASTConsumer();
   P.reset(new Parser(S.getPreprocessor(), S, /*SkipBodies=*/false));
 
@@ -112,6 +120,7 @@ IncrementalParser::ParseOrWrapTopLevelDecl() {
 
 llvm::Expected<TranslationUnitDecl *>
 IncrementalParser::Parse(llvm::StringRef input) {
+  Tracker->beginPTU();
   Preprocessor &PP = S.getPreprocessor();
   assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode!?");
 
@@ -196,156 +205,157 @@ void IncrementalParser::withdrawMostRecentTU(
 
 /// Removes decls introduced in the discarding PTU and restores the
 /// redeclaration chain to previous state.
-class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
-  Sema &S;
-  TranslationUnitDecl *DiscardedTU;
-
-  /// The newest declaration of whatever D redeclares that still lives outside
-  /// the DiscardedTU, or null if DiscardedTU introduced the name.
-  NamedDecl *findSurvivor(NamedDecl *D) const {
-    for (Decl *Prev = D->getPreviousDecl(); Prev;
-         Prev = Prev->getPreviousDecl())
-      if (Prev->getTranslationUnitDecl() != DiscardedTU)
-        return dyn_cast<NamedDecl>(Prev);
-    return nullptr;
-  }
-
-  template <typename DeclT>
-  void unlinkRedeclChain(ASTContext &C, Redeclarable<DeclT> *DBase,
-                         NamedDecl *PrevND) {
-    auto *Latest = static_cast<DeclT *>(DBase);
-    auto *Survivor = cast<DeclT>(PrevND);
-
-    // Rebuild First -> ... -> Survivor -> ... -> Latest as
-    // First -> ... -> Survivor.
-    Latest->getFirstDecl()->RedeclLink.setLatest(Survivor);
-
-    // The chain is circular: a withdrawn declaration still linked into it can
-    // never walk back around to itself, so redecls() on one would not
-    // terminate. Give each withdrawn declaration a chain of its own.
-    for (DeclT *Dead = Latest; Dead != Survivor;) {
-      DeclT *Next = Dead->getPreviousDecl();
-      Dead->First = Dead;
-      Dead->RedeclLink = Redeclarable<DeclT>::LatestDeclLink(C);
-      Dead = Next;
-    }
-  }
-
-  /// Remove entry from "C"'s lookup tables
-  void removeFromLookups(NamedDecl *D) {
-    if (D->getDeclName().isEmpty())
-      return;
-
-    if (D->getDeclName().isIdentifier() && D->getDeclName().getFETokenInfo() &&
-        !D->getLangOpts().ObjC && !D->getLangOpts().CPlusPlus)
-      S.IdResolver.RemoveDecl(D);
-
-    ExternCContextDecl *ECCD = S.getASTContext().getExternCContextDecl();
-    if (StoredDeclsMap *Map = ECCD->getPrimaryContext()->getLookupPtr()) {
-      auto It = Map->find(D->getDeclName());
-      if (It != Map->end())
-        It->second.remove(D);
-    }
-  }
-
-  /// Remove Decls defined in this DC from the lookup table
-  /// and restore the redeclaration chain to previous state
-  void VisitDeclContext(DeclContext *DC) {
-    llvm::SmallVector<Decl *, 8> Members(DC->decls());
-    for (Decl *M : Members) {
-      Visit(M); // restore redecls and lookup
-      // VisitNamedDecl() removes the named decls.
-      if (!isa<NamedDecl>(M))
-        DC->removeDecl(M);
-    }
-  }
-
-public:
-  ASTDeclUnmerger(Sema &S, TranslationUnitDecl *DiscardedTU)
-      : S(S), DiscardedTU(DiscardedTU) {}
-
-  void VisitDecl(Decl *D) {
-    if (auto *DC = dyn_cast<DeclContext>(D))
-      VisitDeclContext(DC);
-  }
-
-  /// Remove ND from its context and the lookup tables, and make the
-  /// declaration it redeclares visible again. Called by VisitRedeclarable()
-  /// before it restores the redeclaration chain, which hides that declaration.
-  void VisitNamedDecl(NamedDecl *ND) {
-    // The templated decl of a template is not a member of its context: the
-    // template is.
-    DeclContext *DC = ND->getLexicalDeclContext();
-    if (!DC->containsDecl(ND))
-      return;
-    NamedDecl *Prev = findSurvivor(ND);
-    DC->removeDecl(ND);
-    removeFromLookups(ND);
-    // Like removeDecl(), use the semantic context: the out-of-line definition
-    // of a member is in DC, but it was removed from the lookup table of its
-    // class or namespace.
-    if (Prev)
-      Prev->getDeclContext()->makeDeclVisibleInContext(Prev);
-  }
-
-  /// Remove D like VisitNamedDecl() and restore its redeclaration chain to the
-  /// previous state. Returns the surviving previous declaration, if any.
-  /// DeclVisitor doesn't dispatch to it: Redeclarable is not a Decl class.
-  template <typename DeclT>
-  NamedDecl *VisitRedeclarable(Redeclarable<DeclT> *DBase) {
-    auto *D = static_cast<DeclT *>(DBase);
-    VisitNamedDecl(D);
-    NamedDecl *Prev = findSurvivor(D);
-    if (Prev)
-      unlinkRedeclChain(S.getASTContext(), DBase, Prev);
-    return Prev;
-  }
-
-  void VisitFunctionDecl(FunctionDecl *D) { VisitRedeclarable(D); }
-  void VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { VisitRedeclarable(D); }
-  void VisitTypedefNameDecl(TypedefNameDecl *D) { VisitRedeclarable(D); }
-  void VisitUsingShadowDecl(UsingShadowDecl *D) { VisitRedeclarable(D); }
-  void VisitVarDecl(VarDecl *D) { VisitRedeclarable(D); }
-
-  void VisitTagDecl(TagDecl *D) {
-    // Some members of a definition are visible outside of it: the enumerators
-    // of an unscoped enumeration, and in C the tags and enumerators declared
-    // in a structure or union.
-    if (D->isThisDeclarationADefinition())
-      VisitDeclContext(D);
-
-    NamedDecl *Prev = VisitRedeclarable(D);
-
-    // A class definition is kept in DefinitionData outside the
-    // redeclaration chain
-    auto *RD = dyn_cast_if_present<CXXRecordDecl>(Prev);
-    if (!RD)
-      return;
-    if (CXXRecordDecl *Def = RD->getDefinition();
-        Def && Def->getTranslationUnitDecl() == DiscardedTU)
-      for (auto *R : RD->redecls())
-        cast<CXXRecordDecl>(R)->DefinitionData = nullptr;
-  }
-
-  void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
-    VisitRedeclarable(D);
-    Visit(D->getTemplatedDecl());
-  }
-
-  void VisitNamespaceDecl(NamespaceDecl *D) {
-    // Handle cases of nested redeclarations like:
-    // PTU1: namespace outer { namespace ns { class Foo; } }
-    // PTU2: namespace outer { namespace ns { class Foo { ... }; error; } }
-    // Foo's redeclaration needs to be restored
-    VisitDeclContext(D);
-    VisitRedeclarable(D);
-  }
-
-  void VisitTranslationUnitDecl(TranslationUnitDecl *D) { VisitDeclContext(D); }
-};
+// class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
+//   Sema &S;
+//   TranslationUnitDecl *DiscardedTU;
+
+//   /// The newest declaration of whatever D redeclares that still lives outside
+//   /// the DiscardedTU, or null if DiscardedTU introduced the name.
+//   NamedDecl *findSurvivor(NamedDecl *D) const {
+//     for (Decl *Prev = D->getPreviousDecl(); Prev;
+//          Prev = Prev->getPreviousDecl())
+//       if (Prev->getTranslationUnitDecl() != DiscardedTU)
+//         return dyn_cast<NamedDecl>(Prev);
+//     return nullptr;
+//   }
+
+//   template <typename DeclT>
+//   void unlinkRedeclChain(ASTContext &C, Redeclarable<DeclT> *DBase,
+//                          NamedDecl *PrevND) {
+//     auto *Latest = static_cast<DeclT *>(DBase);
+//     auto *Survivor = cast<DeclT>(PrevND);
+
+//     // Rebuild First -> ... -> Survivor -> ... -> Latest as
+//     // First -> ... -> Survivor.
+//     Latest->getFirstDecl()->RedeclLink.setLatest(Survivor);
+
+//     // The chain is circular: a withdrawn declaration still linked into it can
+//     // never walk back around to itself, so redecls() on one would not
+//     // terminate. Give each withdrawn declaration a chain of its own.
+//     for (DeclT *Dead = Latest; Dead != Survivor;) {
+//       DeclT *Next = Dead->getPreviousDecl();
+//       Dead->First = Dead;
+//       Dead->RedeclLink = Redeclarable<DeclT>::LatestDeclLink(C);
+//       Dead = Next;
+//     }
+//   }
+
+//   /// Remove entry from "C"'s lookup tables
+//   void removeFromLookups(NamedDecl *D) {
+//     if (D->getDeclName().isEmpty())
+//       return;
+
+//     if (D->getDeclName().isIdentifier() && D->getDeclName().getFETokenInfo() &&
+//         !D->getLangOpts().ObjC && !D->getLangOpts().CPlusPlus)
+//       S.IdResolver.RemoveDecl(D);
+
+//     ExternCContextDecl *ECCD = S.getASTContext().getExternCContextDecl();
+//     if (StoredDeclsMap *Map = ECCD->getPrimaryContext()->getLookupPtr()) {
+//       auto It = Map->find(D->getDeclName());
+//       if (It != Map->end())
+//         It->second.remove(D);
+//     }
+//   }
+
+//   /// Remove Decls defined in this DC from the lookup table
+//   /// and restore the redeclaration chain to previous state
+//   void VisitDeclContext(DeclContext *DC) {
+//     llvm::SmallVector<Decl *, 8> Members(DC->decls());
+//     for (Decl *M : Members) {
+//       Visit(M); // restore redecls and lookup
+//       // VisitNamedDecl() removes the named decls.
+//       if (!isa<NamedDecl>(M))
+//         DC->removeDecl(M);
+//     }
+//   }
+
+// public:
+//   ASTDeclUnmerger(Sema &S, TranslationUnitDecl *DiscardedTU)
+//       : S(S), DiscardedTU(DiscardedTU) {}
+
+//   void VisitDecl(Decl *D) {
+//     if (auto *DC = dyn_cast<DeclContext>(D))
+//       VisitDeclContext(DC);
+//   }
+
+//   /// Remove ND from its context and the lookup tables, and make the
+//   /// declaration it redeclares visible again. Called by VisitRedeclarable()
+//   /// before it restores the redeclaration chain, which hides that declaration.
+//   void VisitNamedDecl(NamedDecl *ND) {
+//     // The templated decl of a template is not a member of its context: the
+//     // template is.
+//     DeclContext *DC = ND->getLexicalDeclContext();
+//     if (!DC->containsDecl(ND))
+//       return;
+//     NamedDecl *Prev = findSurvivor(ND);
+//     DC->removeDecl(ND);
+//     removeFromLookups(ND);
+//     // Like removeDecl(), use the semantic context: the out-of-line definition
+//     // of a member is in DC, but it was removed from the lookup table of its
+//     // class or namespace.
+//     if (Prev)
+//       Prev->getDeclContext()->makeDeclVisibleInContext(Prev);
+//   }
+
+//   /// Remove D like VisitNamedDecl() and restore its redeclaration chain to the
+//   /// previous state. Returns the surviving previous declaration, if any.
+//   /// DeclVisitor doesn't dispatch to it: Redeclarable is not a Decl class.
+//   template <typename DeclT>
+//   NamedDecl *VisitRedeclarable(Redeclarable<DeclT> *DBase) {
+//     auto *D = static_cast<DeclT *>(DBase);
+//     VisitNamedDecl(D);
+//     NamedDecl *Prev = findSurvivor(D);
+//     if (Prev)
+//       unlinkRedeclChain(S.getASTContext(), DBase, Prev);
+//     return Prev;
+//   }
+
+//   void VisitFunctionDecl(FunctionDecl *D) { VisitRedeclarable(D); }
+//   void VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { VisitRedeclarable(D); }
+//   void VisitTypedefNameDecl(TypedefNameDecl *D) { VisitRedeclarable(D); }
+//   void VisitUsingShadowDecl(UsingShadowDecl *D) { VisitRedeclarable(D); }
+//   void VisitVarDecl(VarDecl *D) { VisitRedeclarable(D); }
+
+//   void VisitTagDecl(TagDecl *D) {
+//     // Some members of a definition are visible outside of it: the enumerators
+//     // of an unscoped enumeration, and in C the tags and enumerators declared
+//     // in a structure or union.
+//     if (D->isThisDeclarationADefinition())
+//       VisitDeclContext(D);
+
+//     NamedDecl *Prev = VisitRedeclarable(D);
+
+//     // A class definition is kept in DefinitionData outside the
+//     // redeclaration chain
+//     auto *RD = dyn_cast_if_present<CXXRecordDecl>(Prev);
+//     if (!RD)
+//       return;
+//     if (CXXRecordDecl *Def = RD->getDefinition();
+//         Def && Def->getTranslationUnitDecl() == DiscardedTU)
+//       for (auto *R : RD->redecls())
+//         cast<CXXRecordDecl>(R)->DefinitionData = nullptr;
+//   }
+
+//   void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
+//     VisitRedeclarable(D);
+//     Visit(D->getTemplatedDecl());
+//   }
+
+//   void VisitNamespaceDecl(NamespaceDecl *D) {
+//     // Handle cases of nested redeclarations like:
+//     // PTU1: namespace outer { namespace ns { class Foo; } }
+//     // PTU2: namespace outer { namespace ns { class Foo { ... }; error; } }
+//     // Foo's redeclaration needs to be restored
+//     VisitDeclContext(D);
+//     VisitRedeclarable(D);
+//   }
+
+//   void VisitTranslationUnitDecl(TranslationUnitDecl *D) { VisitDeclContext(D); }
+// };
 
 void IncrementalParser::CleanUpPTU(TranslationUnitDecl *MostRecentTU) {
-  ASTDeclUnmerger(S, MostRecentTU).Visit(MostRecentTU);
+  // ASTDeclUnmerger(S, MostRecentTU).Visit(MostRecentTU);
+  MutationActions->RestorePTU(MostRecentTU);
 
   // Lookup alone is not enough: the redeclaration chain still reaches these.
   withdrawMostRecentTU(MostRecentTU);
@@ -358,8 +368,10 @@ IncrementalParser::RegisterPTU(TranslationUnitDecl *TU,
   PartialTranslationUnit &LastPTU = PTUs.back();
   LastPTU.TUPart = TU;
 
-  if (!M)
+  if (!M) {
+    MutationActions->CommitPTU(TU);
     M = Act->GenModule();
+  }
 
   assert((!Act->getCodeGen() || M) && "Must have a llvm::Module at this point");
 
diff --git a/clang/lib/Interpreter/IncrementalParser.h b/clang/lib/Interpreter/IncrementalParser.h
index b626cebaafcd70..79decf7d86fcf8 100644
--- a/clang/lib/Interpreter/IncrementalParser.h
+++ b/clang/lib/Interpreter/IncrementalParser.h
@@ -27,7 +27,11 @@ class Parser;
 class Sema;
 class TranslationUnitDecl;
 class IncrementalAction;
+class IncrementalStateTracker;
 struct PartialTranslationUnit;
+class PTUMutationActions;
+class PTUMutationRecorder;
+
 
 /// Provides support for incremental compilation. Keeps track of the state
 /// changes between the subsequent incremental input.
@@ -51,6 +55,10 @@ class IncrementalParser {
 
   std::list<PartialTranslationUnit> &PTUs;
 
+  std::unique_ptr<IncrementalStateTracker> Tracker;
+  std::unique_ptr<PTUMutationActions> MutationActions;
+  std::unique_ptr<PTUMutationRecorder> MutationRecorder;
+
 public:
   IncrementalParser(CompilerInstance &Instance, IncrementalAction *Act,
                     llvm::Error &Err, std::list<PartialTranslationUnit> &PTUs);

>From 13d304a80e8c8b77b604060866ef06615565cb5b Mon Sep 17 00:00:00 2001
From: SahilPatidar <patidarsahil2001 at gmail.com>
Date: Tue, 1 Dec 2026 09:34:43 +0530
Subject: [PATCH 4/5] Add tests

---
 clang/lib/Interpreter/IncrementalParser.cpp   |  4 +--
 clang/lib/Interpreter/IncrementalParser.h     |  1 -
 .../error-recovery-template-spec.cpp          | 27 +++++++++++++++++++
 clang/test/Interpreter/inline-namespace.cpp   | 18 +++++++++++++
 4 files changed, 47 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Interpreter/error-recovery-template-spec.cpp
 create mode 100644 clang/test/Interpreter/inline-namespace.cpp

diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp
index d8f76fd08763a7..2822ae24fd3d6b 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -44,8 +44,8 @@ IncrementalParser::IncrementalParser(CompilerInstance &Instance,
   llvm::ErrorAsOutParameter EAO(&Err);
 
   Tracker = std::make_unique<IncrementalStateTracker>(S.getASTContext());
-  MutationActions = std::make_unique<PTUMutationActions>(
-      *Tracker, S, Act->getCodeGen());
+  MutationActions =
+      std::make_unique<PTUMutationActions>(*Tracker, S, Act->getCodeGen());
   MutationRecorder = std::make_unique<PTUMutationRecorder>(*Tracker);
   S.getASTContext().setASTMutationListener(MutationRecorder.get());
 
diff --git a/clang/lib/Interpreter/IncrementalParser.h b/clang/lib/Interpreter/IncrementalParser.h
index 79decf7d86fcf8..48f53492e6fec0 100644
--- a/clang/lib/Interpreter/IncrementalParser.h
+++ b/clang/lib/Interpreter/IncrementalParser.h
@@ -32,7 +32,6 @@ struct PartialTranslationUnit;
 class PTUMutationActions;
 class PTUMutationRecorder;
 
-
 /// Provides support for incremental compilation. Keeps track of the state
 /// changes between the subsequent incremental input.
 ///
diff --git a/clang/test/Interpreter/error-recovery-template-spec.cpp b/clang/test/Interpreter/error-recovery-template-spec.cpp
new file mode 100644
index 00000000000000..000154cefdf5bf
--- /dev/null
+++ b/clang/test/Interpreter/error-recovery-template-spec.cpp
@@ -0,0 +1,27 @@
+// REQUIRES: host-supports-jit
+// RUN: cat %s | clang-repl | FileCheck %s
+//
+// Test rollback of SpecializationAdded.
+//
+// After each rollback, add a specialization to verify that
+// the previous specialization was properly removed.
+
+extern "C" int printf(const char *, ...);
+
+// SpecializationAdded: rollback using %undo.
+template<typename T> struct TplTagA { static const char* name() { return "generic1"; } };
+auto ta1 = printf("taA=%s\n", TplTagA<int>::name());
+%undo
+template<> struct TplTagA<int> { static const char* name() { return "a-v1"; } };
+auto ta2 = printf("taB=%s\n", TplTagA<int>::name());
+
+// SpecializationAdded: automatic rollback after a Sema error.
+auto ta3 = printf("taC=%s\n", TplTagA<double>::name()) + does_not_exist_ta1;
+template<> struct TplTagA<double> { static const char* name() { return "a-v2d"; } };
+auto ta4 = printf("taD=%s\n", TplTagA<double>::name());
+
+// CHECK: taA=generic1
+// CHECK: taB=a-v1
+// CHECK: taD=a-v2d
+
+%quit
diff --git a/clang/test/Interpreter/inline-namespace.cpp b/clang/test/Interpreter/inline-namespace.cpp
new file mode 100644
index 00000000000000..e498a7e22b62c3
--- /dev/null
+++ b/clang/test/Interpreter/inline-namespace.cpp
@@ -0,0 +1,18 @@
+// REQUIRES: host-supports-jit
+// RUN: cat %s | clang-repl | FileCheck %s
+//
+// Namespace PTU rollback tests.
+
+extern "C" int printf(const char *, ...);
+
+namespace InlineOuter { inline namespace v1 { int inline_val = 9; } }
+auto rns6 = printf("inline_val=%d qualified=%d\n", InlineOuter::inline_val, InlineOuter::v1::inline_val);
+// CHECK: inline_val=9 qualified=9
+
+namespace InlineOuter { inline namespace v1 { int inline_val2 = 20; struct InlineWidget { int x; }; } } InlineOuter::InlineWidget bad_widget; bad_widget.y = 1;
+namespace InlineOuter { inline namespace v1 { int inline_val2 = 30; struct InlineWidget { int x; }; } }
+InlineOuter::InlineWidget good_widget; good_widget.x = 42;
+auto rns8 = printf("inline_val2=%d good_widget_x=%d\n", InlineOuter::inline_val2, good_widget.x);
+// CHECK: inline_val2=30 good_widget_x=42
+
+%quit
\ No newline at end of file

>From 13659f4b276e8babddd63d95d38554887d3b1d72 Mon Sep 17 00:00:00 2001
From: SahilPatidar <patidarsahil2001 at gmail.com>
Date: Tue, 1 Dec 2026 14:27:48 +0530
Subject: [PATCH 5/5] Remove commented-out code

---
 clang/lib/Interpreter/ErrorRecovery.cpp     | 325 ++++++++------------
 clang/lib/Interpreter/ErrorRecovery.h       |  18 +-
 clang/lib/Interpreter/IncrementalParser.cpp | 158 +---------
 3 files changed, 134 insertions(+), 367 deletions(-)

diff --git a/clang/lib/Interpreter/ErrorRecovery.cpp b/clang/lib/Interpreter/ErrorRecovery.cpp
index 2c4cb351a4b3e4..0150c64c6d2fd1 100644
--- a/clang/lib/Interpreter/ErrorRecovery.cpp
+++ b/clang/lib/Interpreter/ErrorRecovery.cpp
@@ -44,8 +44,6 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
   [[maybe_unused]] SemaCacheReverter &SemaCache;
   MutationRecord *Rec = nullptr;
 
-  llvm::SmallPtrSet<const Decl *, 16> RepairedChains;
-
   bool isFromThisPTU(const void *Ptr) const {
     return Tracker.isFromThisPTU(Ptr, ID);
   }
@@ -90,10 +88,6 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
   }
 
   template <typename DeclT> void unlinkRedeclChain(DeclT *D) {
-    if (hasNoPreviousDecl(D))
-      return;
-    if (!RepairedChains.insert(D->getCanonicalDecl()).second)
-      return;
     DeclT *Latest = D->getMostRecentDecl();
     if (DeclT *Survivor = findSurvivor(D))
       resetRedeclLink(Latest, Survivor);
@@ -101,9 +95,12 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
 
   /// Remove D from its DeclContext lookup map and restore the previous
   /// declaration if it was replaced.
-  void detachFromDCLookup(NamedDecl *ND) {
+  void removeFromDCLookup(NamedDecl *ND) {
     // Find any declaration from the previous PTU in the redecl chain that may
     // have been replaced by this declaration.
+    if (!ND->getDeclName())
+      return;
+
     NamedDecl *Survivor = findSurvivor(ND);
     DeclarationName Name = ND->getDeclName();
 
@@ -115,6 +112,7 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
         if (Pos != Map->end()) {
           StoredDeclsList &List = Pos->second;
           List.remove(ND);
+
           if (Survivor) {
             List.addOrReplaceDecl(Survivor);
           }
@@ -164,16 +162,6 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
     }
   }
 
-  void unlinkCommon(NamedDecl *ND) {
-    removeFromLookups(ND);
-
-    Decl *Canon = ND->getCanonicalDecl();
-    if (RepairedChains.count(Canon))
-      return;
-
-    detachFromDCLookup(ND);
-  }
-
   class ScopedMutationRecord {
     MutationRecord *&Rec;
     MutationRecord *OldRec;
@@ -240,7 +228,7 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
   }
 
   // Generic across every other footprint type exclusing DefinitionDataFootprint
-  // -- SpecializationFootprint, VarSpecializationFootprint,
+  // -- ClassSpecializationFootprint, VarSpecializationFootprint,
   // FunctionSpecializationFootprint, MemberSpecializationFootprint.
   template <typename FootprintT, typename OwnerT>
   static FootprintT createFootprint(const OwnerT &Owner) {
@@ -264,17 +252,37 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
 
     if (auto *DC = dyn_cast<DeclContext>(D))
       VisitDeclContext(DC);
-    if (auto *ND = dyn_cast<NamedDecl>(D)) {
-      unlinkCommon(ND);
-    }
   }
 
-  void VisitTranslationUnitDecl(TranslationUnitDecl *D) { VisitDeclContext(D); }
+  /// Remove ND from its context and the lookup tables, and make the
+  /// declaration it redeclares visible again. Called by VisitRedeclarable()
+  /// before it restores the redeclaration chain, which hides that declaration.
+  void VisitNamedDecl(NamedDecl *ND) {
+    if (!isDiscarded(ND))
+      return;
+    // The templated decl of a template is not a member of its context: the
+    // template is.
+    DeclContext *DC = ND->getLexicalDeclContext();
+    if (!DC->containsDecl(ND))
+      return;
+    removeFromDCLookup(ND);
+    removeFromLookups(ND);
+  }
+
+  /// Remove D like VisitNamedDecl() and restore its redeclaration chain to the
+  /// previous state.
+  template <typename DeclT> void VisitRedeclarable(Redeclarable<DeclT> *DBase) {
+    auto *D = static_cast<DeclT *>(DBase);
+    VisitNamedDecl(D);
+    if (hasNoPreviousDecl(D) || isFromThisPTU(D->getCanonicalDecl()))
+      return;
+    unlinkRedeclChain(D);
+  }
+
   void VisitNamespaceDecl(NamespaceDecl *D);
+  void VisitTagDecl(TagDecl *TD);
   void VisitCXXRecordDecl(CXXRecordDecl *RD);
   void VisitFunctionDecl(FunctionDecl *FD);
-  // void VisitCXXConstructorDecl(CXXConstructorDecl *D);
-  // void VisitCXXDestructorDecl(CXXDestructorDecl *D);
   void VisitVarDecl(VarDecl *VD);
   void VisitEnumDecl(EnumDecl *ED);
   void VisitClassTemplateDecl(ClassTemplateDecl *CTD);
@@ -283,6 +291,7 @@ class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
   void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
   void VisitTypedefNameDecl(TypedefNameDecl *D);
   void VisitUsingShadowDecl(UsingShadowDecl *D);
+  void VisitTranslationUnitDecl(TranslationUnitDecl *D) { VisitDeclContext(D); }
 };
 
 static DeclShape classifyShape(const Decl *D) {
@@ -310,16 +319,17 @@ static DeclShape classifyShape(const Decl *D) {
 /// committed or not. It is called from CommitDecl to determine whether a new
 /// decl needs to be tracked.
 ///
-/// This requires DeclShape S and Decl to determine which mutation kinds
-/// apply to the shape and whether they need to be tracked.
-/// In the future, if a new mutation site is found for a shape, it should be
-/// added here along with the logic to determine whether the decl is still in an
-/// open, modifiable state.
+/// This requires Decl to determine which mutation kinds apply to the shape and
+/// whether they need to be tracked. In the future, if a new mutation site is
+/// found for a shape, it should be added here along with the logic to determine
+/// whether the decl is still in an open, modifiable state.
 uint32_t PTUMutationActions::DeclNeedingTracking(DeclShape S, const Decl *D) {
+  // TODO: Add logic to determine which mutation kinds require explicit
+  // tracking, similar to how MutationKind::DefinitionData is handled.
+  uint32_t Kinds = 0;
   switch (S) {
   case DeclShape::Class: {
     const auto *RD = cast<CXXRecordDecl>(D);
-    uint32_t Kinds = 0;
     if (RD->hasDefinition() && RD == RD->getDefinition()) {
       // Do we really need to create a DefData chain here? Usually, an implicit
       // decl can be mutated later after the definition. If it is already wired
@@ -333,61 +343,27 @@ uint32_t PTUMutationActions::DeclNeedingTracking(DeclShape S, const Decl *D) {
           RD->needsImplicitMoveAssignment() || RD->needsImplicitDestructor())
         Kinds |= uint32_t(MutationKind::DefinitionData);
     }
-    if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
-      // If SpecializationKind == TSK_ExplicitSpecialization, there is less
-      // chance that the info will be modified later, so we are all set and
-      // don't need to track it.
-      // A specialization's Kind/point-of-instantiation is overwritten in place,
-      // with no separate record of the previous value. The footprint chain is
-      // the only place where the previous value is stored.
-      if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
-        Kinds |= uint32_t(MutationKind::SpecInfo);
-    } else if (const auto *MSI = RD->getMemberSpecializationInfo()) {
-      if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
-        Kinds |= uint32_t(MutationKind::MemberSpecInfo);
-    }
-    return Kinds;
-  }
-  case DeclShape::Function: {
-    const auto *FD = cast<FunctionDecl>(D);
-    uint32_t Kinds = 0;
-    if (FD->getTemplateSpecializationInfo() &&
-        FD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
-      Kinds |= uint32_t(MutationKind::SpecInfo);
-    if (const auto *MSI = FD->getMemberSpecializationInfo()) {
-      if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
-        Kinds |= uint32_t(MutationKind::MemberSpecInfo);
-    }
-    return Kinds;
-  }
-  case DeclShape::Var: {
-    const auto *VD = cast<VarDecl>(D);
-    uint32_t Kinds = 0;
-    if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
-      if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
-        Kinds |= uint32_t(MutationKind::SpecInfo);
-    } else if (const auto *MSI = VD->getMemberSpecializationInfo()) {
-      if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
-        Kinds |= uint32_t(MutationKind::MemberSpecInfo);
-    }
-    return Kinds;
-  }
-  case DeclShape::Enum: {
-    const auto *ED = cast<EnumDecl>(D);
-    uint32_t Kinds = 0;
-    if (const auto *MSI = ED->getMemberSpecializationInfo()) {
-      // Same terminal-state exclusion as the other MSI-backed cases above.
-      if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
-        Kinds |= uint32_t(MutationKind::MemberSpecInfo);
-    }
-    return Kinds;
+    Kinds |= uint32_t(MutationKind::SpecInfo) |
+             uint32_t(MutationKind::MemberSpecInfo);
+    break;
   }
+  case DeclShape::Function:
+    Kinds |= uint32_t(MutationKind::SpecInfo) |
+             uint32_t(MutationKind::MemberSpecInfo);
+    break;
+  case DeclShape::Var:
+    Kinds |= uint32_t(MutationKind::SpecInfo) |
+             uint32_t(MutationKind::MemberSpecInfo);
+    break;
+  case DeclShape::Enum:
+    Kinds |= uint32_t(MutationKind::MemberSpecInfo);
+    break;
   case DeclShape::Template:
   case DeclShape::Typedef:
   case DeclShape::None:
-    return 0;
+    break;
   }
-  return 0;
+  return Kinds;
 }
 
 template <typename T>
@@ -431,7 +407,7 @@ uint32_t PTUMutationActions::confirmMutation(const Decl *D, DeclShape S,
     if (FlaggedKinds & uint32_t(MutationKind::SpecInfo)) {
       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(RD))
         if (differsFromLast(Tracker, Spec, MutationKind::SpecInfo,
-                            Footprint<SpecializationFootprint>(*Spec)))
+                            Footprint<ClassSpecializationFootprint>(*Spec)))
           Verified |= uint32_t(MutationKind::SpecInfo);
     } else if (FlaggedKinds & uint32_t(MutationKind::MemberSpecInfo)) {
       if (differsFromLast(Tracker, RD, MutationKind::MemberSpecInfo,
@@ -567,45 +543,44 @@ void PTUStateInfo::verifyMutations(PTUMutationActions &Actions) {
   });
 }
 
-// FIXME: Uncomment once we handle restoration of Implicit Decl.
-// static bool isReachableFromThisTU(const Decl *D,
-//                                   const TranslationUnitDecl *ThisTU) {
-//   const DeclContext *DC = D->getLexicalDeclContext();
+static bool isReachableFromThisTU(const Decl *D,
+                                  const TranslationUnitDecl *ThisTU) {
+  const DeclContext *DC = D->getLexicalDeclContext();
 
-//   for (; DC; DC = DC->getLexicalParent()) {
-//     if (DC->containsDecl(const_cast<Decl *>(D))) {
-//       const DeclContext *Parent = DC;
+  for (; DC; DC = DC->getLexicalParent()) {
+    if (DC->containsDecl(const_cast<Decl *>(D))) {
+      const DeclContext *Parent = DC;
 
-//       while (Parent && !Parent->isTranslationUnit())
-//         Parent = Parent->getLexicalParent();
+      while (Parent && !Parent->isTranslationUnit())
+        Parent = Parent->getLexicalParent();
 
-//       return Parent == ThisTU;
-//     }
-//   }
+      return Parent == ThisTU;
+    }
+  }
 
-//   return false;
-// }
+  return false;
+}
 
 /// -----------------------------------------------------------------------
 //////////////////////// PTUMutationActions::commit ///////////////////////
 /// -----------------------------------------------------------------------
 
 /// These are the places where the incremental state of a declaration is
-/// registered based on its DeclShape.
+/// registered based on its DeclKind.
 ///
 /// For a declaration created in the current PTU, its state is committed
 /// to the tracker. For an existing declaration modified in the current
 /// PTU, its previous state is recorded so it can be restored on undo.
 ///
 /// The idea is to keep state tracking limited to a small set of known
-/// mutation sites for each DeclShape, instead of tracking changes
+/// mutation sites for each DeclKind, instead of tracking changes
 /// everywhere in Clang.
 ///
 /// Currently, this covers Class, Function, Enum, Template, etc. Each
-/// DeclShape is associated with the mutation kinds that need to be tracked.
+/// DeclKind is associated with the mutation kinds that need to be tracked.
 ///
 /// When adding a new mutation site, it should be handled according to
-/// the corresponding DeclShape and mutation kind.
+/// the corresponding DeclKind and mutation kind.
 
 bool PTUMutationActions::shouldRecurseInto(const Decl *D) {
   if (isa<NamespaceDecl>(D))
@@ -623,28 +598,6 @@ void PTUMutationActions::VisitDeclContext(const DeclContext *DC) {
   }
 }
 
-void PTUMutationActions::VisitCXXRecordDecl(const CXXRecordDecl *RD) {
-  // TODO
-}
-
-void PTUMutationActions::VisitFunctionDecl(const FunctionDecl *FD) {
-
-  // TODO
-}
-
-void PTUMutationActions::VisitVarDecl(const VarDecl *VD) {
-  // TODO
-}
-
-void PTUMutationActions::VisitEnumDecl(const EnumDecl *ED) {
-  // TODO
-}
-
-void PTUMutationActions::VisitRedeclarableTemplateDecl(
-    const RedeclarableTemplateDecl *RT) {
-  // TODO
-}
-
 void PTUMutationActions::CommitDecl(const Decl *D, MutationRecord *R) {
   if (!D->isDefinedOutsideFunctionOrMethod())
     return;
@@ -703,14 +656,13 @@ void PTUMutationActions::CommitPTU(TranslationUnitDecl *ThisTU) {
   //
   // CommitDecl: Decides what to do with declarations created by the current
   // PTU, such as whether a declaration needs to be tracked or not.
-  // FIXME: Uncomment once we handle restoration of Implicit Decl.
-  // for (const Decl *D : Cur.ImplicitlyGeneratedDecls) {
-  //   if (isReachableFromThisTU(D, ThisTU))
-  //     continue;
-  //   if (shouldRecurseInto(D))
-  //     VisitDeclContext(cast<DeclContext>(D));
-  //   CommitDecl(D, nullptr);
-  // }
+  for (const Decl *D : Cur.ImplicitlyGeneratedDecls) {
+    if (isReachableFromThisTU(D, ThisTU))
+      continue;
+    if (shouldRecurseInto(D))
+      VisitDeclContext(cast<DeclContext>(D));
+    CommitDecl(D, nullptr);
+  }
 
   // Iterate over all declarations in this TU and register them whether they
   // need explicit tracking.
@@ -738,22 +690,33 @@ void PTUMutationActions::CommitPTU(TranslationUnitDecl *ThisTU) {
 void ASTDeclUnmerger::VisitNamespaceDecl(NamespaceDecl *D) {
   // we don't care about the decl which complete chain is part belong to
   // current PTU.
-  if (!Tracker.isFromThisPTU(D->getCanonicalDecl(), ID))
+  if (!Tracker.isFromThisPTU(D->getCanonicalDecl(), ID) ||
+      D->isInlineNamespace())
     VisitDeclContext(D);
-  unlinkCommon(D);
-  unlinkRedeclChain(D);
+  VisitRedeclarable(D);
+}
+
+void ASTDeclUnmerger::VisitTagDecl(TagDecl *D) {
+  // Some members of a definition are visible outside of it: the enumerators
+  // of an unscoped enumeration, and in C the tags and enumerators declared
+  // in a structure or union.
+  if (D->isThisDeclarationADefinition())
+    VisitDeclContext(D);
+
+  VisitRedeclarable(D);
 }
 
 void ASTDeclUnmerger::VisitCXXRecordDecl(CXXRecordDecl *RD) {
   if (isDiscarded(RD)) {
-    if (!RD->getDescribedClassTemplate()) {
-      VisitDeclContext(RD);
-      unlinkCommon(RD);
-    }
-    if (CXXRecordDecl *Def = RD->getDefinition();
-        Def && RD->getPreviousDecl() && isFromThisPTU(Def))
-      detachDefData(Def);
-    unlinkRedeclChain<TagDecl>(RD);
+    CXXRecordDecl *Def = RD->getDefinition();
+    CXXRecordDecl *Canon = RD->getCanonicalDecl();
+    bool DetachDefData = (Def && isFromThisPTU(Def) && !isFromThisPTU(Canon));
+    if (RD->getDescribedClassTemplate())
+      unlinkRedeclChain<TagDecl>(RD);
+    else
+      VisitTagDecl(RD);
+    if (DetachDefData)
+      detachDefData(Canon);
     return;
   }
 
@@ -766,9 +729,7 @@ void ASTDeclUnmerger::VisitCXXRecordDecl(CXXRecordDecl *RD) {
 void ASTDeclUnmerger::VisitFunctionDecl(FunctionDecl *FD) {
   // unlink Discarded decl.
   if (isDiscarded(FD)) {
-    // forgetMangledNames(FD);
-    unlinkCommon(FD);
-    unlinkRedeclChain(FD);
+    VisitRedeclarable(FD);
     return;
   }
 
@@ -781,10 +742,7 @@ void ASTDeclUnmerger::VisitFunctionDecl(FunctionDecl *FD) {
 void ASTDeclUnmerger::VisitVarDecl(VarDecl *VD) {
   // Unlinking discared Decl.
   if (isDiscarded(VD)) {
-    // if (!isa<ParmVarDecl>(VD) && !VD->getDeclContext()->isDependentContext())
-    //   forgetMangledNames(VD);
-    unlinkCommon(VD);
-    unlinkRedeclChain(VD);
+    VisitRedeclarable(VD);
     return;
   }
 
@@ -797,9 +755,7 @@ void ASTDeclUnmerger::VisitVarDecl(VarDecl *VD) {
 void ASTDeclUnmerger::VisitEnumDecl(EnumDecl *ED) {
   // Unlink Discarded Decl.
   if (isDiscarded(ED)) {
-    VisitDeclContext(ED);
-    unlinkCommon(ED);
-    unlinkRedeclChain<TagDecl>(ED);
+    VisitTagDecl(ED);
     return;
   }
 
@@ -812,19 +768,13 @@ void ASTDeclUnmerger::VisitEnumDecl(EnumDecl *ED) {
 void ASTDeclUnmerger::VisitClassTemplateDecl(ClassTemplateDecl *CT) {
   // Unlinking discared Decl.
   if (isDiscarded(CT)) {
-    unlinkCommon(CT);
-    bool HasSurvivorToReplace =
-        !hasNoPreviousDecl(CT) && !isFromThisPTU(CT->getCanonicalDecl());
-    if (HasSurvivorToReplace)
-      unlinkRedeclChain(cast<RedeclarableTemplateDecl>(CT));
-
     NamedDecl *Templated = CT->getTemplatedDecl();
     if (auto *RD = dyn_cast<CXXRecordDecl>(Templated)) {
       if (CXXRecordDecl *Def = RD->getDefinition(); Def && isFromThisPTU(Def))
         detachDefData(RD);
-      if (HasSurvivorToReplace)
-        unlinkRedeclChain<TagDecl>(RD);
+      VisitRedeclarable<TagDecl>(RD);
     }
+    VisitRedeclarable<RedeclarableTemplateDecl>(CT);
   }
 
   if (!hasRecord())
@@ -842,16 +792,11 @@ void ASTDeclUnmerger::VisitClassTemplateDecl(ClassTemplateDecl *CT) {
 void ASTDeclUnmerger::VisitFunctionTemplateDecl(FunctionTemplateDecl *FTD) {
   // Unlinking discared Decl.
   if (isDiscarded(FTD)) {
-    unlinkCommon(FTD);
-    bool HasSurvivorToReplace =
-        !hasNoPreviousDecl(FTD) && !isFromThisPTU(FTD->getCanonicalDecl());
-    if (HasSurvivorToReplace)
-      unlinkRedeclChain(cast<RedeclarableTemplateDecl>(FTD));
-
-    if (HasSurvivorToReplace) {
+    if (!isFromThisPTU(FTD->getCanonicalDecl())) {
       if (auto *FD = dyn_cast<FunctionDecl>(FTD->getTemplatedDecl()))
         unlinkRedeclChain(FD);
     }
+    VisitRedeclarable<RedeclarableTemplateDecl>(FTD);
   }
 
   if (!hasRecord())
@@ -863,17 +808,11 @@ void ASTDeclUnmerger::VisitFunctionTemplateDecl(FunctionTemplateDecl *FTD) {
 void ASTDeclUnmerger::VisitVarTemplateDecl(VarTemplateDecl *VTD) {
   // Unlinking discared Decl.
   if (isDiscarded(VTD)) {
-    unlinkCommon(VTD);
-    bool HasSurvivorToReplace =
-        !hasNoPreviousDecl(VTD) && !isFromThisPTU(VTD->getCanonicalDecl());
-    if (HasSurvivorToReplace)
-      unlinkRedeclChain(cast<RedeclarableTemplateDecl>(VTD));
-
-    NamedDecl *Templated = VTD->getTemplatedDecl();
-    if (HasSurvivorToReplace) {
-      if (auto *VD = dyn_cast<VarDecl>(Templated))
+    if (!isFromThisPTU(VTD->getCanonicalDecl())) {
+      if (auto *VD = dyn_cast<VarDecl>(VTD->getTemplatedDecl()))
         unlinkRedeclChain(VD);
     }
+    VisitRedeclarable<RedeclarableTemplateDecl>(VTD);
   }
 
   if (!hasRecord())
@@ -883,36 +822,24 @@ void ASTDeclUnmerger::VisitVarTemplateDecl(VarTemplateDecl *VTD) {
 }
 
 void ASTDeclUnmerger::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
-  // Unlink Discarded Decl.
-  if (isDiscarded(D)) {
-    unlinkCommon(D);
-    unlinkRedeclChain(D);
+  if (!isDiscarded(D))
     return;
-  }
 
-  // Restore decl;
+  VisitRedeclarable(D);
 }
 
 void ASTDeclUnmerger::VisitTypedefNameDecl(TypedefNameDecl *D) {
-  // Unlink Discarded Decl.
-  if (isDiscarded(D)) {
-    unlinkCommon(D);
-    unlinkRedeclChain(D);
+  if (!isDiscarded(D))
     return;
-  }
 
-  // Restore decl;
+  VisitRedeclarable(D);
 }
 
 void ASTDeclUnmerger::VisitUsingShadowDecl(UsingShadowDecl *D) {
-  // Unlink Discarded Decl.
-  if (isDiscarded(D)) {
-    unlinkCommon(D);
-    unlinkRedeclChain(D);
+  if (!isDiscarded(D))
     return;
-  }
 
-  // Restore decl;
+  VisitRedeclarable(D);
 }
 
 void SemaCacheReverter::restoreSpecialMemberCache(PTUID ID) {
@@ -989,13 +916,11 @@ void PTUMutationActions::RestorePTU(TranslationUnitDecl *ThisTU) {
   // the current PTU, such as unlinking declarations from redeclaration chains
   // and DeclContext lookup structures, or restoring declaration state (e.g.,
   // CXXRecordDecl::DefinitionData).
-
-  // FIXME: Uncomment once we handle restoration of Implicit Decl.
-  //   for (const Decl *D : Cur.ImplicitlyGeneratedDecls) {
-  //     if (isReachableFromThisTU(D, ThisTU))
-  //       continue;
-  //     Umerger.Visit(const_cast<Decl *>(D));
-  //   }
+  for (const Decl *D : Cur.ImplicitlyGeneratedDecls) {
+    if (isReachableFromThisTU(D, ThisTU))
+      continue;
+    Umerger.Visit(const_cast<Decl *>(D));
+  }
 
   Umerger.Visit(ThisTU);
 
@@ -1046,8 +971,6 @@ template <typename TemplateT, typename SpecT>
 void PTUMutationRecorder::noteTemplateDeclMutation(const TemplateT *TD,
                                                    const SpecT *Spec) {
   PTUStateInfo &Cur = Tracker.current();
-  Cur.ImplicitlyGeneratedDecls.insert(Spec);
-
   if (Tracker.isFromThisPTU(TD, Cur.ID))
     return;
 
diff --git a/clang/lib/Interpreter/ErrorRecovery.h b/clang/lib/Interpreter/ErrorRecovery.h
index 8a036941bbfaee..8699e30a57d248 100644
--- a/clang/lib/Interpreter/ErrorRecovery.h
+++ b/clang/lib/Interpreter/ErrorRecovery.h
@@ -62,18 +62,18 @@ struct DefinitionDataFootprint {
 // Stores the state of a class template specialization. Tracks its
 // specialization kind, point of instantiation, source location, and lexical
 // declaration context so the state can be compared and restored.
-struct SpecializationFootprint {
+struct ClassSpecializationFootprint {
   unsigned SpecializationKind : 3;
   SourceLocation PointOfInstantiation;
   SourceLocation Location;
   const DeclContext *LexicalDC;
 
-  bool operator==(const SpecializationFootprint &O) const {
+  bool operator==(const ClassSpecializationFootprint &O) const {
     return SpecializationKind == O.SpecializationKind &&
            PointOfInstantiation == O.PointOfInstantiation &&
            Location == O.Location && LexicalDC == O.LexicalDC;
   }
-  bool operator!=(const SpecializationFootprint &O) const {
+  bool operator!=(const ClassSpecializationFootprint &O) const {
     return !(*this == O);
   }
 
@@ -270,7 +270,7 @@ using DeclShape = MutationRecord::DeclShape;
 using MutationKind = MutationRecord::MutationKind;
 
 using FootprintValue =
-    std::variant<DefinitionDataFootprint, SpecializationFootprint,
+    std::variant<DefinitionDataFootprint, ClassSpecializationFootprint,
                  VarSpecializationFootprint, FunctionSpecializationFootprint,
                  MemberSpecializationFootprint, QualType, const Type *>;
 
@@ -551,11 +551,11 @@ class PTUMutationActions : public ConstDeclVisitor<PTUMutationActions> {
   bool shouldRecurseInto(const Decl *D);
 
   void VisitDeclContext(const DeclContext *DC);
-  void VisitCXXRecordDecl(const CXXRecordDecl *RD);
-  void VisitFunctionDecl(const FunctionDecl *FD);
-  void VisitVarDecl(const VarDecl *VD);
-  void VisitEnumDecl(const EnumDecl *ED);
-  void VisitRedeclarableTemplateDecl(const RedeclarableTemplateDecl *RT);
+  void VisitCXXRecordDecl(const CXXRecordDecl *RD) {}
+  void VisitFunctionDecl(const FunctionDecl *FD) {}
+  void VisitVarDecl(const VarDecl *VD) {}
+  void VisitEnumDecl(const EnumDecl *ED) {}
+  void VisitRedeclarableTemplateDecl(const RedeclarableTemplateDecl *RT) {}
 
   void CommitDecl(const Decl *D, MutationRecord *Rec);
 
diff --git a/clang/lib/Interpreter/IncrementalParser.cpp b/clang/lib/Interpreter/IncrementalParser.cpp
index 2822ae24fd3d6b..f5e9873925a8a2 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -10,16 +10,11 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "ErrorRecovery.h"
 #include "IncrementalParser.h"
+#include "ErrorRecovery.h"
 #include "IncrementalAction.h"
 
 #include "clang/AST/ASTContext.h"
-#include "clang/AST/Decl.h"
-#include "clang/AST/DeclCXX.h"
-#include "clang/AST/DeclContextInternals.h"
-#include "clang/AST/DeclTemplate.h"
-#include "clang/AST/DeclVisitor.h"
 #include "clang/Frontend/CompilerInstance.h"
 #include "clang/Interpreter/PartialTranslationUnit.h"
 #include "clang/Parse/Parser.h"
@@ -203,158 +198,7 @@ void IncrementalParser::withdrawMostRecentTU(
   C.TUDecl = Prev;
 }
 
-/// Removes decls introduced in the discarding PTU and restores the
-/// redeclaration chain to previous state.
-// class ASTDeclUnmerger : public DeclVisitor<ASTDeclUnmerger> {
-//   Sema &S;
-//   TranslationUnitDecl *DiscardedTU;
-
-//   /// The newest declaration of whatever D redeclares that still lives outside
-//   /// the DiscardedTU, or null if DiscardedTU introduced the name.
-//   NamedDecl *findSurvivor(NamedDecl *D) const {
-//     for (Decl *Prev = D->getPreviousDecl(); Prev;
-//          Prev = Prev->getPreviousDecl())
-//       if (Prev->getTranslationUnitDecl() != DiscardedTU)
-//         return dyn_cast<NamedDecl>(Prev);
-//     return nullptr;
-//   }
-
-//   template <typename DeclT>
-//   void unlinkRedeclChain(ASTContext &C, Redeclarable<DeclT> *DBase,
-//                          NamedDecl *PrevND) {
-//     auto *Latest = static_cast<DeclT *>(DBase);
-//     auto *Survivor = cast<DeclT>(PrevND);
-
-//     // Rebuild First -> ... -> Survivor -> ... -> Latest as
-//     // First -> ... -> Survivor.
-//     Latest->getFirstDecl()->RedeclLink.setLatest(Survivor);
-
-//     // The chain is circular: a withdrawn declaration still linked into it can
-//     // never walk back around to itself, so redecls() on one would not
-//     // terminate. Give each withdrawn declaration a chain of its own.
-//     for (DeclT *Dead = Latest; Dead != Survivor;) {
-//       DeclT *Next = Dead->getPreviousDecl();
-//       Dead->First = Dead;
-//       Dead->RedeclLink = Redeclarable<DeclT>::LatestDeclLink(C);
-//       Dead = Next;
-//     }
-//   }
-
-//   /// Remove entry from "C"'s lookup tables
-//   void removeFromLookups(NamedDecl *D) {
-//     if (D->getDeclName().isEmpty())
-//       return;
-
-//     if (D->getDeclName().isIdentifier() && D->getDeclName().getFETokenInfo() &&
-//         !D->getLangOpts().ObjC && !D->getLangOpts().CPlusPlus)
-//       S.IdResolver.RemoveDecl(D);
-
-//     ExternCContextDecl *ECCD = S.getASTContext().getExternCContextDecl();
-//     if (StoredDeclsMap *Map = ECCD->getPrimaryContext()->getLookupPtr()) {
-//       auto It = Map->find(D->getDeclName());
-//       if (It != Map->end())
-//         It->second.remove(D);
-//     }
-//   }
-
-//   /// Remove Decls defined in this DC from the lookup table
-//   /// and restore the redeclaration chain to previous state
-//   void VisitDeclContext(DeclContext *DC) {
-//     llvm::SmallVector<Decl *, 8> Members(DC->decls());
-//     for (Decl *M : Members) {
-//       Visit(M); // restore redecls and lookup
-//       // VisitNamedDecl() removes the named decls.
-//       if (!isa<NamedDecl>(M))
-//         DC->removeDecl(M);
-//     }
-//   }
-
-// public:
-//   ASTDeclUnmerger(Sema &S, TranslationUnitDecl *DiscardedTU)
-//       : S(S), DiscardedTU(DiscardedTU) {}
-
-//   void VisitDecl(Decl *D) {
-//     if (auto *DC = dyn_cast<DeclContext>(D))
-//       VisitDeclContext(DC);
-//   }
-
-//   /// Remove ND from its context and the lookup tables, and make the
-//   /// declaration it redeclares visible again. Called by VisitRedeclarable()
-//   /// before it restores the redeclaration chain, which hides that declaration.
-//   void VisitNamedDecl(NamedDecl *ND) {
-//     // The templated decl of a template is not a member of its context: the
-//     // template is.
-//     DeclContext *DC = ND->getLexicalDeclContext();
-//     if (!DC->containsDecl(ND))
-//       return;
-//     NamedDecl *Prev = findSurvivor(ND);
-//     DC->removeDecl(ND);
-//     removeFromLookups(ND);
-//     // Like removeDecl(), use the semantic context: the out-of-line definition
-//     // of a member is in DC, but it was removed from the lookup table of its
-//     // class or namespace.
-//     if (Prev)
-//       Prev->getDeclContext()->makeDeclVisibleInContext(Prev);
-//   }
-
-//   /// Remove D like VisitNamedDecl() and restore its redeclaration chain to the
-//   /// previous state. Returns the surviving previous declaration, if any.
-//   /// DeclVisitor doesn't dispatch to it: Redeclarable is not a Decl class.
-//   template <typename DeclT>
-//   NamedDecl *VisitRedeclarable(Redeclarable<DeclT> *DBase) {
-//     auto *D = static_cast<DeclT *>(DBase);
-//     VisitNamedDecl(D);
-//     NamedDecl *Prev = findSurvivor(D);
-//     if (Prev)
-//       unlinkRedeclChain(S.getASTContext(), DBase, Prev);
-//     return Prev;
-//   }
-
-//   void VisitFunctionDecl(FunctionDecl *D) { VisitRedeclarable(D); }
-//   void VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { VisitRedeclarable(D); }
-//   void VisitTypedefNameDecl(TypedefNameDecl *D) { VisitRedeclarable(D); }
-//   void VisitUsingShadowDecl(UsingShadowDecl *D) { VisitRedeclarable(D); }
-//   void VisitVarDecl(VarDecl *D) { VisitRedeclarable(D); }
-
-//   void VisitTagDecl(TagDecl *D) {
-//     // Some members of a definition are visible outside of it: the enumerators
-//     // of an unscoped enumeration, and in C the tags and enumerators declared
-//     // in a structure or union.
-//     if (D->isThisDeclarationADefinition())
-//       VisitDeclContext(D);
-
-//     NamedDecl *Prev = VisitRedeclarable(D);
-
-//     // A class definition is kept in DefinitionData outside the
-//     // redeclaration chain
-//     auto *RD = dyn_cast_if_present<CXXRecordDecl>(Prev);
-//     if (!RD)
-//       return;
-//     if (CXXRecordDecl *Def = RD->getDefinition();
-//         Def && Def->getTranslationUnitDecl() == DiscardedTU)
-//       for (auto *R : RD->redecls())
-//         cast<CXXRecordDecl>(R)->DefinitionData = nullptr;
-//   }
-
-//   void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
-//     VisitRedeclarable(D);
-//     Visit(D->getTemplatedDecl());
-//   }
-
-//   void VisitNamespaceDecl(NamespaceDecl *D) {
-//     // Handle cases of nested redeclarations like:
-//     // PTU1: namespace outer { namespace ns { class Foo; } }
-//     // PTU2: namespace outer { namespace ns { class Foo { ... }; error; } }
-//     // Foo's redeclaration needs to be restored
-//     VisitDeclContext(D);
-//     VisitRedeclarable(D);
-//   }
-
-//   void VisitTranslationUnitDecl(TranslationUnitDecl *D) { VisitDeclContext(D); }
-// };
-
 void IncrementalParser::CleanUpPTU(TranslationUnitDecl *MostRecentTU) {
-  // ASTDeclUnmerger(S, MostRecentTU).Visit(MostRecentTU);
   MutationActions->RestorePTU(MostRecentTU);
 
   // Lookup alone is not enough: the redeclaration chain still reaches these.



More information about the cfe-commits mailing list