[clang] [SSAF][Analyses] Add an AST visitor for the contribution model (PR #191933)

Ziqing Luo via cfe-commits cfe-commits at lists.llvm.org
Tue Apr 21 14:05:40 PDT 2026


https://github.com/ziqingluo-90 updated https://github.com/llvm/llvm-project/pull/191933

>From a4ccace9e00f6d08f5a00f17a12e1071fff6bd53 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Thu, 9 Apr 2026 18:43:40 -0700
Subject: [PATCH 01/25] [NFC][SSAF] Move EntityPointerLevel to a separate
 folder

EntityPointerLevel will later be shared with other summaries besides
UnsafeBufferUsage. This commit moves it to a separate file.
---
 .../EntityPointerLevel/EntityPointerLevel.h   |  99 +++++++
 .../UnsafeBufferUsage/UnsafeBufferUsage.h     |  68 +----
 .../UnsafeBufferUsageExtractor.h              |   5 -
 .../Analyses/CMakeLists.txt                   |   1 +
 .../EntityPointerLevel/EntityPointerLevel.cpp | 244 ++++++++++++++++++
 .../UnsafeBufferUsage/UnsafeBufferUsage.cpp   |   4 -
 .../UnsafeBufferUsageExtractor.cpp            | 220 +---------------
 .../UnsafeBufferUsageTest.cpp                 |   4 +-
 8 files changed, 353 insertions(+), 292 deletions(-)
 create mode 100644 clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
 create mode 100644 clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
new file mode 100644
index 0000000000000..52caa52e1120d
--- /dev/null
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
@@ -0,0 +1,99 @@
+//===- EntityPointerLevel.h -------------------------------------*- 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
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVEL_H
+#define LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVEL_H
+
+#include "clang/AST/Expr.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityId.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityName.h"
+#include <set>
+
+namespace clang::ssaf {
+
+/// An EntityPointerLevel represents a level of the declared pointer/array
+/// type of an entity.  In the fully-expanded spelling of the declared type, a
+/// EntityPointerLevel is associated with a '*' (or a '[]`) in that declaration.
+///
+/// For example, for 'int *p[10];', there are two EntityPointerLevels. One
+/// is associated with 'int *[10]' of 'p' and the other is associated with 'int
+/// *' of 'p'.
+///
+/// An EntityPointerLevel can be identified by an EntityId and an unsigned
+/// integer indicating the pointer level: '(EntityId, PointerLevel)'.
+/// An EntityPointerLevel 'P' is valid iff 'P.EntityId' has a pointer type with
+/// at least 'P.PointerLevel' levels (This implies 'P.PointerLevel > 0').
+///
+/// For the same example 'int *p[10];', the EntityPointerLevels below are valid:
+/// - '(p, 2)' is associated with the 'int *' part of the declared type of 'p';
+/// - '(p, 1)' is associated with the 'int *[10]' part of the declared type of
+/// 'p'.
+class EntityPointerLevel {
+  EntityId Entity;
+  unsigned PointerLevel;
+
+  friend class EntityPointerLevelTranslator;
+  friend EntityPointerLevel buildEntityPointerLevel(EntityId, unsigned);
+
+  EntityPointerLevel(EntityId Entity, unsigned PointerLevel)
+      : Entity(Entity), PointerLevel(PointerLevel) {}
+
+public:
+  EntityId getEntity() const { return Entity; }
+  unsigned getPointerLevel() const { return PointerLevel; }
+
+  bool operator==(const EntityPointerLevel &Other) const {
+    return std::tie(Entity, PointerLevel) ==
+           std::tie(Other.Entity, Other.PointerLevel);
+  }
+
+  bool operator!=(const EntityPointerLevel &Other) const {
+    return !(*this == Other);
+  }
+
+  bool operator<(const EntityPointerLevel &Other) const {
+    return std::tie(Entity, PointerLevel) <
+           std::tie(Other.Entity, Other.PointerLevel);
+  }
+
+  /// Compares `EntityPointerLevel`s; additionally, partially compares
+  /// `EntityPointerLevel` with `EntityId`.
+  struct Comparator {
+    using is_transparent = void;
+    bool operator()(const EntityPointerLevel &L,
+                    const EntityPointerLevel &R) const {
+      return L < R;
+    }
+    bool operator()(const EntityId &L, const EntityPointerLevel &R) const {
+      return L < R.getEntity();
+    }
+    bool operator()(const EntityPointerLevel &L, const EntityId &R) const {
+      return L.getEntity() < R;
+    }
+  };
+};
+
+using EntityPointerLevelSet =
+    std::set<EntityPointerLevel, EntityPointerLevel::Comparator>;
+
+/// Translate a pointer/array type expression 'E' to a (set of)
+/// EntityPointerLevel(s) associated with the declared type of the base address
+/// of `E`. If the base address of `E` is not associated with an entity, the
+/// translation result is an empty set.
+///
+/// \param E the pointer expression to be translated
+/// \param Ctx the AST context of `E`
+/// \param AddEntity the callback provided by the caller to convert EntityNames
+/// to EntityIds.
+llvm::Expected<EntityPointerLevelSet>
+translateEntityPointerLevel(const Expr *E, ASTContext &Ctx,
+                            std::function<EntityId(EntityName EN)> AddEntity);
+
+EntityPointerLevel buildEntityPointerLevel(EntityId, unsigned);
+} // namespace clang::ssaf
+#endif // LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVEL_H
diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h
index 4e217c2eb87ef..250bad5b72f75 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h
@@ -9,7 +9,7 @@
 #ifndef LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_UNSAFEBUFFERUSAGE_UNSAFEBUFFERUSAGE_H
 #define LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_UNSAFEBUFFERUSAGE_UNSAFEBUFFERUSAGE_H
 
-#include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityId.h"
+#include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/SummaryName.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/EntitySummary.h"
 #include "llvm/ADT/StringRef.h"
@@ -18,72 +18,6 @@
 
 namespace clang::ssaf {
 
-/// An EntityPointerLevel represents a level of the declared pointer/array
-/// type of an entity.  In the fully-expanded spelling of the declared type, a
-/// EntityPointerLevel is associated with a '*' (or a '[]`) in that declaration.
-///
-/// For example, for 'int *p[10];', there are two EntityPointerLevels. One
-/// is associated with 'int *[10]' of 'p' and the other is associated with 'int
-/// *' of 'p'.
-///
-/// An EntityPointerLevel can be identified by an EntityId and an unsigned
-/// integer indicating the pointer level: '(EntityId, PointerLevel)'.
-/// An EntityPointerLevel 'P' is valid iff 'P.EntityId' has a pointer type with
-/// at least 'P.PointerLevel' levels (This implies 'P.PointerLevel > 0').
-///
-/// For the same example 'int *p[10];', the EntityPointerLevels below are valid:
-/// - '(p, 2)' is associated with the 'int *' part of the declared type of 'p';
-/// - '(p, 1)' is associated with the 'int *[10]' part of the declared type of
-/// 'p'.
-class EntityPointerLevel {
-  EntityId Entity;
-  unsigned PointerLevel;
-
-  friend class UnsafeBufferUsageEntitySummary;
-  friend class UnsafeBufferUsageTUSummaryExtractor;
-  friend EntityPointerLevel buildEntityPointerLevel(EntityId, unsigned);
-
-  EntityPointerLevel(EntityId Entity, unsigned PointerLevel)
-      : Entity(Entity), PointerLevel(PointerLevel) {}
-
-public:
-  EntityId getEntity() const { return Entity; }
-  unsigned getPointerLevel() const { return PointerLevel; }
-
-  bool operator==(const EntityPointerLevel &Other) const {
-    return std::tie(Entity, PointerLevel) ==
-           std::tie(Other.Entity, Other.PointerLevel);
-  }
-
-  bool operator!=(const EntityPointerLevel &Other) const {
-    return !(*this == Other);
-  }
-
-  bool operator<(const EntityPointerLevel &Other) const {
-    return std::tie(Entity, PointerLevel) <
-           std::tie(Other.Entity, Other.PointerLevel);
-  }
-
-  /// Compares `EntityPointerLevel`s; additionally, partially compares
-  /// `EntityPointerLevel` with `EntityId`.
-  struct Comparator {
-    using is_transparent = void;
-    bool operator()(const EntityPointerLevel &L,
-                    const EntityPointerLevel &R) const {
-      return L < R;
-    }
-    bool operator()(const EntityId &L, const EntityPointerLevel &R) const {
-      return L < R.getEntity();
-    }
-    bool operator()(const EntityPointerLevel &L, const EntityId &R) const {
-      return L.getEntity() < R;
-    }
-  };
-};
-
-using EntityPointerLevelSet =
-    std::set<EntityPointerLevel, EntityPointerLevel::Comparator>;
-
 /// An UnsafeBufferUsageEntitySummary is an immutable set of unsafe buffers, in
 /// the form of EntityPointerLevel.
 class UnsafeBufferUsageEntitySummary final : public EntitySummary {
diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h
index 765b2c37562ce..13d4e18b4e81f 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h
@@ -22,11 +22,6 @@ class UnsafeBufferUsageTUSummaryExtractor : public TUSummaryExtractor {
   UnsafeBufferUsageTUSummaryExtractor(TUSummaryBuilder &Builder)
       : TUSummaryExtractor(Builder) {}
 
-  static EntityPointerLevel buildEntityPointerLevel(EntityId Entity,
-                                                    unsigned PointerLevel) {
-    return {Entity, PointerLevel};
-  }
-
   EntityId addEntity(EntityName EN) { return SummaryBuilder.addEntity(EN); }
 
   std::unique_ptr<UnsafeBufferUsageEntitySummary>
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt b/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt
index 926b610aa8dee..c15ff3b3c42e7 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt
@@ -5,6 +5,7 @@ set(LLVM_LINK_COMPONENTS
 add_clang_library(clangScalableStaticAnalysisFrameworkAnalyses 
   CallGraph/CallGraphExtractor.cpp
   CallGraph/CallGraphJSONFormat.cpp
+  EntityPointerLevel/EntityPointerLevel.cpp
   UnsafeBufferUsage/UnsafeBufferUsage.cpp
   UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
 
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
new file mode 100644
index 0000000000000..49a135b13877a
--- /dev/null
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
@@ -0,0 +1,244 @@
+//===- EntityPointerLevel.cpp ----------------------------------*- 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/StmtVisitor.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/ASTEntityMapping.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityName.h"
+
+using namespace clang;
+using namespace ssaf;
+
+static bool hasPointerType(const Expr *E) {
+  auto Ty = E->getType();
+  return !Ty.isNull() && !Ty->isFunctionPointerType() &&
+         (Ty->isPointerType() || Ty->isArrayType());
+}
+
+static llvm::Error makeUnsupportedStmtKindError(const Stmt *Unsupported) {
+  return llvm::createStringError(
+      "unsupported expression kind for translation to "
+      "EntityPointerLevel: %s",
+      Unsupported->getStmtClassName());
+}
+
+static llvm::Error makeCreateEntityNameError(const NamedDecl *FailedDecl,
+                                             ASTContext &Ctx) {
+  std::string LocStr = FailedDecl->getSourceRange().getBegin().printToString(
+      Ctx.getSourceManager());
+  return llvm::createStringError(
+      "failed to create entity name for %s declared at %s",
+      FailedDecl->getNameAsString().c_str(), LocStr.c_str());
+}
+
+// Translate a pointer type expression 'E' to a (set of) EntityPointerLevel(s)
+// associated with the declared type of the base address of `E`. If the base
+// address of `E` is not associated with an entity, the translation result is an
+// empty set.
+//
+// The translation is a process of traversing into the pointer 'E' until its
+// base address can be represented by an entity, with the number of dereferences
+// tracked by incrementing the pointer level.  Naturally, taking address of, as
+// the inverse operation of dereference, is tracked by decrementing the pointer
+// level.
+//
+// For example, suppose there are pointers and arrays declared as
+//   int *ptr, **p1, **p2;
+//   int arr[10][10];
+// , the translation of expressions involving these base addresses will be:
+//   Translate(ptr + 5)            -> {(ptr, 1)}
+//   Translate(arr[5])             -> {(arr, 2)}
+//   Translate(cond ? p1[5] : p2)  -> {(p1, 2), (p2, 1)}
+//   Translate(&arr[5])            -> {(arr, 1)}
+class ssaf::EntityPointerLevelTranslator
+    : ConstStmtVisitor<EntityPointerLevelTranslator,
+                       Expected<EntityPointerLevelSet>> {
+  friend class StmtVisitorBase;
+
+  // Fallback method for all unsupported expression kind:
+  llvm::Error fallback(const Stmt *E) {
+    return makeUnsupportedStmtKindError(E);
+  }
+
+  static EntityPointerLevel incrementPointerLevel(const EntityPointerLevel &E) {
+    return EntityPointerLevel(E.getEntity(), E.getPointerLevel() + 1);
+  }
+
+  static EntityPointerLevel decrementPointerLevel(const EntityPointerLevel &E) {
+    assert(E.getPointerLevel() > 0);
+    return EntityPointerLevel(E.getEntity(), E.getPointerLevel() - 1);
+  }
+
+  EntityPointerLevel createEntityPointerLevelFor(const EntityName &Name) {
+    return EntityPointerLevel(AddEntity(Name), 1);
+  }
+
+  // The common helper function for Translate(*base):
+  // Translate(*base) -> Translate(base) with .pointerLevel + 1
+  Expected<EntityPointerLevelSet> translateDereferencePointer(const Expr *Ptr) {
+    assert(hasPointerType(Ptr));
+
+    Expected<EntityPointerLevelSet> SubResult = Visit(Ptr);
+    if (!SubResult)
+      return SubResult.takeError();
+
+    auto Incremented = llvm::map_range(*SubResult, incrementPointerLevel);
+    return EntityPointerLevelSet{Incremented.begin(), Incremented.end()};
+  }
+
+  std::function<EntityId(EntityName EN)> AddEntity;
+  ASTContext &Ctx;
+
+public:
+  EntityPointerLevelTranslator(std::function<EntityId(EntityName EN)> AddEntity,
+                               ASTContext &Ctx)
+      : AddEntity(AddEntity), Ctx(Ctx) {}
+
+  Expected<EntityPointerLevelSet> translate(const Expr *E) { return Visit(E); }
+
+private:
+  Expected<EntityPointerLevelSet> VisitStmt(const Stmt *E) {
+    return fallback(E);
+  }
+
+  // Translate(base + x)           -> Translate(base)
+  // Translate(x + base)           -> Translate(base)
+  // Translate(base - x)           -> Translate(base)
+  // Translate(base {+=, -=, =} x) -> Translate(base)
+  // Translate(x, base)            -> Translate(base)
+  Expected<EntityPointerLevelSet> VisitBinaryOperator(const BinaryOperator *E) {
+    switch (E->getOpcode()) {
+    case clang::BO_Add:
+      if (hasPointerType(E->getLHS()))
+        return Visit(E->getLHS());
+      return Visit(E->getRHS());
+    case clang::BO_Sub:
+    case clang::BO_AddAssign:
+    case clang::BO_SubAssign:
+    case clang::BO_Assign:
+      return Visit(E->getLHS());
+    case clang::BO_Comma:
+      return Visit(E->getRHS());
+    default:
+      return fallback(E);
+    }
+  }
+
+  // Translate({++, --}base)   -> Translate(base)
+  // Translate(base{++, --})   -> Translate(base)
+  // Translate(*base)          -> Translate(base) with .pointerLevel += 1
+  // Translate(&base)          -> {}, if Translate(base) is {}
+  //                           -> Translate(base) with .pointerLevel -= 1
+  Expected<EntityPointerLevelSet> VisitUnaryOperator(const UnaryOperator *E) {
+    switch (E->getOpcode()) {
+    case clang::UO_PostInc:
+    case clang::UO_PostDec:
+    case clang::UO_PreInc:
+    case clang::UO_PreDec:
+      return Visit(E->getSubExpr());
+    case clang::UO_AddrOf: {
+      Expected<EntityPointerLevelSet> SubResult = Visit(E->getSubExpr());
+      if (!SubResult)
+        return SubResult.takeError();
+
+      auto Decremented = llvm::map_range(*SubResult, decrementPointerLevel);
+      return EntityPointerLevelSet{Decremented.begin(), Decremented.end()};
+    }
+    case clang::UO_Deref:
+      return translateDereferencePointer(E->getSubExpr());
+    default:
+      return fallback(E);
+    }
+  }
+
+  // Translate((T*)base) -> Translate(p) if p has pointer type
+  //                     -> {} otherwise
+  Expected<EntityPointerLevelSet> VisitCastExpr(const CastExpr *E) {
+    if (hasPointerType(E->getSubExpr()))
+      return Visit(E->getSubExpr());
+    return EntityPointerLevelSet{};
+  }
+
+  // Translate(f(...)) -> {} if it is an indirect call
+  //                   -> {(f_return, 1)}, otherwise
+  Expected<EntityPointerLevelSet> VisitCallExpr(const CallExpr *E) {
+    if (auto *FD = E->getDirectCallee())
+      if (auto FDEntityName = getEntityNameForReturn(FD))
+        return EntityPointerLevelSet{
+            createEntityPointerLevelFor(*FDEntityName)};
+    return EntityPointerLevelSet{};
+  }
+
+  // Translate(base[x]) -> Translate(*base)
+  Expected<EntityPointerLevelSet>
+  VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
+    return translateDereferencePointer(E->getBase());
+  }
+
+  // Translate(cond ? base1 : base2) := Translate(base1) U Translate(base2)
+  Expected<EntityPointerLevelSet>
+  VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
+    Expected<EntityPointerLevelSet> ReT = Visit(E->getTrueExpr());
+    Expected<EntityPointerLevelSet> ReF = Visit(E->getFalseExpr());
+
+    if (ReT && ReF) {
+      ReT->insert(ReF->begin(), ReF->end());
+      return ReT;
+    }
+    if (!ReF && !ReT)
+      return llvm::joinErrors(ReT.takeError(), ReF.takeError());
+    if (!ReF)
+      return ReF.takeError();
+    return ReT.takeError();
+  }
+
+  Expected<EntityPointerLevelSet> VisitParenExpr(const ParenExpr *E) {
+    return Visit(E->getSubExpr());
+  }
+
+  // Translate("string-literal") -> {}
+  // Buffer accesses on string literals are unsafe, but string literals are not
+  // entities so there is no EntityPointerLevel associated with it.
+  Expected<EntityPointerLevelSet> VisitStringLiteral(const StringLiteral *E) {
+    return EntityPointerLevelSet{};
+  }
+
+  // Translate(DRE) -> {(Decl, 1)}
+  Expected<EntityPointerLevelSet> VisitDeclRefExpr(const DeclRefExpr *E) {
+    if (auto EntityName = getEntityName(E->getDecl()))
+      return EntityPointerLevelSet{createEntityPointerLevelFor(*EntityName)};
+    return makeCreateEntityNameError(E->getDecl(), Ctx);
+  }
+
+  // Translate({., ->}f) -> {(MemberDecl, 1)}
+  Expected<EntityPointerLevelSet> VisitMemberExpr(const MemberExpr *E) {
+    if (auto EntityName = getEntityName(E->getMemberDecl()))
+      return EntityPointerLevelSet{createEntityPointerLevelFor(*EntityName)};
+    return makeCreateEntityNameError(E->getMemberDecl(), Ctx);
+  }
+
+  Expected<EntityPointerLevelSet>
+  VisitOpaqueValueExpr(const OpaqueValueExpr *S) {
+    return Visit(S->getSourceExpr());
+  }
+};
+
+Expected<EntityPointerLevelSet> clang::ssaf::translateEntityPointerLevel(
+    const Expr *E, ASTContext &Ctx,
+    std::function<EntityId(EntityName EN)> AddEntity) {
+  EntityPointerLevelTranslator Translator(AddEntity, Ctx);
+
+  return Translator.translate(E);
+}
+
+EntityPointerLevel clang::ssaf::buildEntityPointerLevel(EntityId Id,
+                                                        unsigned PtrLv) {
+  return EntityPointerLevel({Id, PtrLv});
+}
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp
index d325e8df79c20..84f3f9cbb3852 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp
@@ -21,10 +21,6 @@ using Object = llvm::json::Object;
 
 static constexpr llvm::StringLiteral SummarySerializationKey = "UnsafeBuffers";
 
-EntityPointerLevel ssaf::buildEntityPointerLevel(EntityId Id, unsigned PtrLv) {
-  return EntityPointerLevel(Id, PtrLv);
-}
-
 UnsafeBufferUsageEntitySummary
 ssaf::buildUnsafeBufferUsageEntitySummary(EntityPointerLevelSet UnsafeBuffers) {
   return UnsafeBufferUsageEntitySummary(std::move(UnsafeBuffers));
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
index c609168e4dc7d..b29eaa6b903d0 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
@@ -11,8 +11,8 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
-#include "clang/AST/StmtVisitor.h"
 #include "clang/Analysis/Analyses/UnsafeBufferUsage.h"
+#include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/ASTEntityMapping.h"
 #include "llvm/ADT/STLExtras.h"
@@ -24,22 +24,6 @@ namespace {
 using namespace clang;
 using namespace ssaf;
 
-static bool hasPointerType(const Expr *E) {
-  auto Ty = E->getType();
-  return !Ty.isNull() && !Ty->isFunctionPointerType() &&
-         (Ty->isPointerType() || Ty->isArrayType());
-}
-
-constexpr inline auto buildEntityPointerLevel =
-    UnsafeBufferUsageTUSummaryExtractor::buildEntityPointerLevel;
-
-static llvm::Error makeUnsupportedStmtKindError(const Stmt *Unsupported) {
-  return llvm::createStringError(
-      "unsupported expression kind for translation to "
-      "EntityPointerLevel: %s",
-      Unsupported->getStmtClassName());
-}
-
 static llvm::Error makeCreateEntityNameError(const NamedDecl *FailedDecl,
                                              ASTContext &Ctx) {
   std::string LocStr = FailedDecl->getSourceRange().getBegin().printToString(
@@ -59,208 +43,17 @@ static llvm::Error makeAddEntitySummaryError(const NamedDecl *FailedContributor,
       FailedContributor->getNameAsString().c_str(), LocStr.c_str());
 }
 
-// Translate a pointer type expression 'E' to a (set of) EntityPointerLevel(s)
-// associated with the declared type of the base address of `E`. If the base
-// address of `E` is not associated with an entity, the translation result is an
-// empty set.
-//
-// The translation is a process of traversing into the pointer 'E' until its
-// base address can be represented by an entity, with the number of dereferences
-// tracked by incrementing the pointer level.  Naturally, taking address of, as
-// the inverse operation of dereference, is tracked by decrementing the pointer
-// level.
-//
-// For example, suppose there are pointers and arrays declared as
-//   int *ptr, **p1, **p2;
-//   int arr[10][10];
-// , the translation of expressions involving these base addresses will be:
-//   Translate(ptr + 5)            -> {(ptr, 1)}
-//   Translate(arr[5])             -> {(arr, 2)}
-//   Translate(cond ? p1[5] : p2)  -> {(p1, 2), (p2, 1)}
-//   Translate(&arr[5])            -> {(arr, 1)}
-class EntityPointerLevelTranslator
-    : ConstStmtVisitor<EntityPointerLevelTranslator,
-                       Expected<EntityPointerLevelSet>> {
-  friend class StmtVisitorBase;
-
-  // Fallback method for all unsupported expression kind:
-  llvm::Error fallback(const Stmt *E) {
-    return makeUnsupportedStmtKindError(E);
-  }
-
-  static EntityPointerLevel incrementPointerLevel(const EntityPointerLevel &E) {
-    return buildEntityPointerLevel(E.getEntity(), E.getPointerLevel() + 1);
-  }
-
-  static EntityPointerLevel decrementPointerLevel(const EntityPointerLevel &E) {
-    assert(E.getPointerLevel() > 0);
-    return buildEntityPointerLevel(E.getEntity(), E.getPointerLevel() - 1);
-  }
-
-  EntityPointerLevel createEntityPointerLevelFor(const EntityName &Name) {
-    return buildEntityPointerLevel(Extractor.addEntity(Name), 1);
-  }
-
-  // The common helper function for Translate(*base):
-  // Translate(*base) -> Translate(base) with .pointerLevel + 1
-  Expected<EntityPointerLevelSet> translateDereferencePointer(const Expr *Ptr) {
-    assert(hasPointerType(Ptr));
-
-    Expected<EntityPointerLevelSet> SubResult = Visit(Ptr);
-    if (!SubResult)
-      return SubResult.takeError();
-
-    auto Incremented = llvm::map_range(*SubResult, incrementPointerLevel);
-    return EntityPointerLevelSet{Incremented.begin(), Incremented.end()};
-  }
-
-  UnsafeBufferUsageTUSummaryExtractor &Extractor;
-  ASTContext &Ctx;
-
-public:
-  EntityPointerLevelTranslator(UnsafeBufferUsageTUSummaryExtractor &Extractor,
-                               ASTContext &Ctx)
-      : Extractor(Extractor), Ctx(Ctx) {}
-
-  Expected<EntityPointerLevelSet> translate(const Expr *E) { return Visit(E); }
-
-private:
-  Expected<EntityPointerLevelSet> VisitStmt(const Stmt *E) {
-    return fallback(E);
-  }
-
-  // Translate(base + x)           -> Translate(base)
-  // Translate(x + base)           -> Translate(base)
-  // Translate(base - x)           -> Translate(base)
-  // Translate(base {+=, -=, =} x) -> Translate(base)
-  // Translate(x, base)            -> Translate(base)
-  Expected<EntityPointerLevelSet> VisitBinaryOperator(const BinaryOperator *E) {
-    switch (E->getOpcode()) {
-    case clang::BO_Add:
-      if (hasPointerType(E->getLHS()))
-        return Visit(E->getLHS());
-      return Visit(E->getRHS());
-    case clang::BO_Sub:
-    case clang::BO_AddAssign:
-    case clang::BO_SubAssign:
-    case clang::BO_Assign:
-      return Visit(E->getLHS());
-    case clang::BO_Comma:
-      return Visit(E->getRHS());
-    default:
-      return fallback(E);
-    }
-  }
-
-  // Translate({++, --}base)   -> Translate(base)
-  // Translate(base{++, --})   -> Translate(base)
-  // Translate(*base)          -> Translate(base) with .pointerLevel += 1
-  // Translate(&base)          -> {}, if Translate(base) is {}
-  //                           -> Translate(base) with .pointerLevel -= 1
-  Expected<EntityPointerLevelSet> VisitUnaryOperator(const UnaryOperator *E) {
-    switch (E->getOpcode()) {
-    case clang::UO_PostInc:
-    case clang::UO_PostDec:
-    case clang::UO_PreInc:
-    case clang::UO_PreDec:
-      return Visit(E->getSubExpr());
-    case clang::UO_AddrOf: {
-      Expected<EntityPointerLevelSet> SubResult = Visit(E->getSubExpr());
-      if (!SubResult)
-        return SubResult.takeError();
-
-      auto Decremented = llvm::map_range(*SubResult, decrementPointerLevel);
-      return EntityPointerLevelSet{Decremented.begin(), Decremented.end()};
-    }
-    case clang::UO_Deref:
-      return translateDereferencePointer(E->getSubExpr());
-    default:
-      return fallback(E);
-    }
-  }
-
-  // Translate((T*)base) -> Translate(p) if p has pointer type
-  //                     -> {} otherwise
-  Expected<EntityPointerLevelSet> VisitCastExpr(const CastExpr *E) {
-    if (hasPointerType(E->getSubExpr()))
-      return Visit(E->getSubExpr());
-    return EntityPointerLevelSet{};
-  }
-
-  // Translate(f(...)) -> {} if it is an indirect call
-  //                   -> {(f_return, 1)}, otherwise
-  Expected<EntityPointerLevelSet> VisitCallExpr(const CallExpr *E) {
-    if (auto *FD = E->getDirectCallee())
-      if (auto FDEntityName = getEntityNameForReturn(FD))
-        return EntityPointerLevelSet{
-            createEntityPointerLevelFor(*FDEntityName)};
-    return EntityPointerLevelSet{};
-  }
-
-  // Translate(base[x]) -> Translate(*base)
-  Expected<EntityPointerLevelSet>
-  VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
-    return translateDereferencePointer(E->getBase());
-  }
-
-  // Translate(cond ? base1 : base2) := Translate(base1) U Translate(base2)
-  Expected<EntityPointerLevelSet>
-  VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
-    Expected<EntityPointerLevelSet> ReT = Visit(E->getTrueExpr());
-    Expected<EntityPointerLevelSet> ReF = Visit(E->getFalseExpr());
-
-    if (ReT && ReF) {
-      ReT->insert(ReF->begin(), ReF->end());
-      return ReT;
-    }
-    if (!ReF && !ReT)
-      return llvm::joinErrors(ReT.takeError(), ReF.takeError());
-    if (!ReF)
-      return ReF.takeError();
-    return ReT.takeError();
-  }
-
-  Expected<EntityPointerLevelSet> VisitParenExpr(const ParenExpr *E) {
-    return Visit(E->getSubExpr());
-  }
-
-  // Translate("string-literal") -> {}
-  // Buffer accesses on string literals are unsafe, but string literals are not
-  // entities so there is no EntityPointerLevel associated with it.
-  Expected<EntityPointerLevelSet> VisitStringLiteral(const StringLiteral *E) {
-    return EntityPointerLevelSet{};
-  }
-
-  // Translate(DRE) -> {(Decl, 1)}
-  Expected<EntityPointerLevelSet> VisitDeclRefExpr(const DeclRefExpr *E) {
-    if (auto EntityName = getEntityName(E->getDecl()))
-      return EntityPointerLevelSet{createEntityPointerLevelFor(*EntityName)};
-    return makeCreateEntityNameError(E->getDecl(), Ctx);
-  }
-
-  // Translate({., ->}f) -> {(MemberDecl, 1)}
-  Expected<EntityPointerLevelSet> VisitMemberExpr(const MemberExpr *E) {
-    if (auto EntityName = getEntityName(E->getMemberDecl()))
-      return EntityPointerLevelSet{createEntityPointerLevelFor(*EntityName)};
-    return makeCreateEntityNameError(E->getMemberDecl(), Ctx);
-  }
-
-  Expected<EntityPointerLevelSet>
-  VisitOpaqueValueExpr(const OpaqueValueExpr *S) {
-    return Visit(S->getSourceExpr());
-  }
-};
-
 Expected<EntityPointerLevelSet>
 buildEntityPointerLevels(std::set<const Expr *> &&UnsafePointers,
                          UnsafeBufferUsageTUSummaryExtractor &Extractor,
-                         ASTContext &Ctx) {
+                         ASTContext &Ctx,
+                         std::function<EntityId(EntityName)> AddEntity) {
   EntityPointerLevelSet Result{};
-  EntityPointerLevelTranslator Translator{Extractor, Ctx};
   llvm::Error AllErrors = llvm::ErrorSuccess();
 
   for (const Expr *Ptr : UnsafePointers) {
-    Expected<EntityPointerLevelSet> Translation = Translator.translate(Ptr);
+    Expected<EntityPointerLevelSet> Translation =
+        translateEntityPointerLevel(Ptr, Ctx, AddEntity);
 
     if (Translation) {
       // Filter out those temporary invalid EntityPointerLevels associated with
@@ -297,8 +90,9 @@ static std::set<const Expr *> findUnsafePointersInContributor(const Decl *D) {
 std::unique_ptr<UnsafeBufferUsageEntitySummary>
 UnsafeBufferUsageTUSummaryExtractor::extractEntitySummary(
     const Decl *Contributor, ASTContext &Ctx, llvm::Error &Error) {
+  auto AddEntity = [this](EntityName EN) { return addEntity(EN); };
   Expected<EntityPointerLevelSet> EPLs = buildEntityPointerLevels(
-      findUnsafePointersInContributor(Contributor), *this, Ctx);
+      findUnsafePointersInContributor(Contributor), *this, Ctx, AddEntity);
 
   if (EPLs)
     return std::make_unique<UnsafeBufferUsageEntitySummary>(
diff --git a/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp b/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
index 51d422c1921af..d2c513b7c70a2 100644
--- a/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
+++ b/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
@@ -10,6 +10,7 @@
 #include "TestFixture.h"
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
 #include "clang/Frontend/ASTUnit.h"
+#include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/ASTEntityMapping.h"
@@ -63,9 +64,6 @@ const FunctionDecl *findFnByName(StringRef Name, ASTContext &Ctx) {
   return findDeclByName<FunctionDecl>(Name, Ctx);
 }
 
-constexpr inline auto buildEntityPointerLevel =
-    UnsafeBufferUsageTUSummaryExtractor::buildEntityPointerLevel;
-
 class UnsafeBufferUsageTest : public TestFixture {
 protected:
   TUSummary TUSum;

>From 3994ca430a89be4b890a340fcf4c8652fd04ce7e Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Thu, 9 Apr 2026 19:01:09 -0700
Subject: [PATCH 02/25] [SSAF][UnsafeBufferUsage] Add APIs to the
 EntityPointerLevel module for UnsafeBufferUsage

- UnsafeBufferUsage serialization uses EntityPointerLevel's API to
  serialize EntityPointerLevels.
- Add APIs to EntityPointerLevel for creating EPLs from Decls and
  incrementing EPL's pointer level.
- Improve UnsafeBufferUsage serialization error messages with a test.
---
 .../EntityPointerLevel/EntityPointerLevel.h   |  31 +++-
 .../EntityPointerLevelFormat.h                |  33 ++++
 .../UnsafeBufferUsage/UnsafeBufferUsage.h     |   8 +-
 .../EntityPointerLevel/EntityPointerLevel.cpp | 141 +++++++++++++-----
 .../UnsafeBufferUsage/UnsafeBufferUsage.cpp   |  28 ++--
 .../UnsafeBufferUsageExtractor.cpp            |   4 +-
 .../tu-summary-serialization.test             |  16 +-
 7 files changed, 191 insertions(+), 70 deletions(-)
 create mode 100644 clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
index 52caa52e1120d..6f5687fd186c9 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
@@ -16,9 +16,10 @@
 
 namespace clang::ssaf {
 
-/// An EntityPointerLevel represents a level of the declared pointer/array
-/// type of an entity.  In the fully-expanded spelling of the declared type, a
-/// EntityPointerLevel is associated with a '*' (or a '[]`) in that declaration.
+/// An EntityPointerLevel is associated with a level of the declared
+/// pointer/array type of an entity.  In the fully-expanded spelling of the
+/// declared type, a EntityPointerLevel is associated with a '*' (or a '[]`) in
+/// that declaration.
 ///
 /// For example, for 'int *p[10];', there are two EntityPointerLevels. One
 /// is associated with 'int *[10]' of 'p' and the other is associated with 'int
@@ -38,10 +39,11 @@ class EntityPointerLevel {
   unsigned PointerLevel;
 
   friend class EntityPointerLevelTranslator;
+  // For unittests:
   friend EntityPointerLevel buildEntityPointerLevel(EntityId, unsigned);
 
-  EntityPointerLevel(EntityId Entity, unsigned PointerLevel)
-      : Entity(Entity), PointerLevel(PointerLevel) {}
+  EntityPointerLevel(std::pair<EntityId, unsigned> Pair)
+      : Entity(Pair.first), PointerLevel(Pair.second) {}
 
 public:
   EntityId getEntity() const { return Entity; }
@@ -95,5 +97,24 @@ translateEntityPointerLevel(const Expr *E, ASTContext &Ctx,
                             std::function<EntityId(EntityName EN)> AddEntity);
 
 EntityPointerLevel buildEntityPointerLevel(EntityId, unsigned);
+
+/// Create an EntityPointerLevel (EPL) from a NamedDecl of a pointer/array type.
+///
+/// \param E the pointer expression to be translated
+/// \param Ctx the AST context of `E`
+/// \param AddEntity the callback provided by the caller to convert EntityNames
+/// to EntityIds.
+/// \param IsFunRet true iff the created EPL is associated with the return type
+/// of a function entity.
+llvm::Expected<EntityPointerLevel>
+creatEntityPointerLevel(const NamedDecl *ND, ASTContext &Ctx,
+                        std::function<EntityId(EntityName EN)> AddEntity,
+                        bool IsFunRet = false);
+
+/// Creates a new EntityPointerLevel (EPL) from `E` by incrementing `E`'s
+/// pointer level.
+/// \return the EPL that is associated with the pointee (or array element) type
+/// of `E`'s associated pointer/array tyoe of the same entity.
+EntityPointerLevel incrementPointerLevel(const EntityPointerLevel &E);
 } // namespace clang::ssaf
 #endif // LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVEL_H
diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
new file mode 100644
index 0000000000000..766e425338e96
--- /dev/null
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
@@ -0,0 +1,33 @@
+//===- EntityPointerLevelFormat.h -------------------------------*- 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
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVELFORMAT_H
+#define LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVELFORMAT_H
+#include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/Serialization/JSONFormat.h"
+
+template <typename... Ts>
+static inline llvm::Error makeSawButExpectedError(const llvm::json::Value &Saw,
+                                                  llvm::StringRef Expected,
+                                                  const Ts &...ExpectedArgs) {
+  std::string Fmt = ("saw %s but expected " + Expected).str();
+  std::string SawStr = llvm::formatv("{0:2}", Saw).str();
+
+  return llvm::createStringError(Fmt.c_str(), SawStr.c_str(), ExpectedArgs...);
+}
+
+namespace clang::ssaf {
+llvm::json::Value
+entityPointerLevelToJSON(const EntityPointerLevel &EPL,
+                         JSONFormat::EntityIdToJSONFn EntityId2JSON);
+
+Expected<EntityPointerLevel>
+entityPointerLevelFromJSON(const llvm::json::Value &EPLData,
+                           JSONFormat::EntityIdFromJSONFn EntityIdFromJSON);
+} // namespace clang::ssaf
+#endif // LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVELFORMAT_H
\ No newline at end of file
diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h
index 250bad5b72f75..27bda9f773085 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h
@@ -12,14 +12,10 @@
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/SummaryName.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/EntitySummary.h"
-#include "llvm/ADT/StringRef.h"
-#include "llvm/ADT/iterator_range.h"
-#include <set>
 
 namespace clang::ssaf {
-
-/// An UnsafeBufferUsageEntitySummary is an immutable set of unsafe buffers, in
-/// the form of EntityPointerLevel.
+/// An UnsafeBufferUsageEntitySummary contains a set of EntityPointerLevels
+/// extracted from unsafe buffer pointers contributed by an entity.
 class UnsafeBufferUsageEntitySummary final : public EntitySummary {
   const EntityPointerLevelSet UnsafeBuffers;
 
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
index 49a135b13877a..78afdf956eb57 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
@@ -10,32 +10,34 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/StmtVisitor.h"
+#include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/ASTEntityMapping.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityName.h"
+#include <optional>
 
 using namespace clang;
 using namespace ssaf;
 
-static bool hasPointerType(const Expr *E) {
-  auto Ty = E->getType();
-  return !Ty.isNull() && !Ty->isFunctionPointerType() &&
-         (Ty->isPointerType() || Ty->isArrayType());
+template <typename DeclOrExpr>
+static bool hasPtrOrArrType(const DeclOrExpr &E) {
+  return llvm::isa<PointerType>(E.getType().getCanonicalType()) ||
+         llvm::isa<ArrayType>(E.getType().getCanonicalType());
 }
 
-static llvm::Error makeUnsupportedStmtKindError(const Stmt *Unsupported) {
-  return llvm::createStringError(
-      "unsupported expression kind for translation to "
-      "EntityPointerLevel: %s",
-      Unsupported->getStmtClassName());
+template <typename NodeTy, typename... Ts>
+static inline llvm::Error makeErrAtNode(ASTContext &Ctx, const NodeTy &N,
+                                        StringRef Fmt, const Ts &...Args) {
+  std::string LocStr = N.getBeginLoc().printToString(Ctx.getSourceManager());
+  llvm::SmallVector<char> FmtData;
+
+  (Fmt + " at %s").toStringRef(FmtData);
+  return llvm::createStringError(FmtData.data(), Args..., LocStr.c_str());
 }
 
-static llvm::Error makeCreateEntityNameError(const NamedDecl *FailedDecl,
-                                             ASTContext &Ctx) {
-  std::string LocStr = FailedDecl->getSourceRange().getBegin().printToString(
-      Ctx.getSourceManager());
-  return llvm::createStringError(
-      "failed to create entity name for %s declared at %s",
-      FailedDecl->getNameAsString().c_str(), LocStr.c_str());
+static inline llvm::Error makeEntityNameErr(ASTContext &Ctx,
+                                            const NamedDecl &D) {
+  return makeErrAtNode(Ctx, D, "failed to create entity name for %s",
+                       D.getNameAsString().data());
 }
 
 // Translate a pointer type expression 'E' to a (set of) EntityPointerLevel(s)
@@ -58,32 +60,25 @@ static llvm::Error makeCreateEntityNameError(const NamedDecl *FailedDecl,
 //   Translate(cond ? p1[5] : p2)  -> {(p1, 2), (p2, 1)}
 //   Translate(&arr[5])            -> {(arr, 1)}
 class ssaf::EntityPointerLevelTranslator
-    : ConstStmtVisitor<EntityPointerLevelTranslator,
-                       Expected<EntityPointerLevelSet>> {
+    : public ConstStmtVisitor<EntityPointerLevelTranslator,
+                              Expected<EntityPointerLevelSet>> {
   friend class StmtVisitorBase;
 
   // Fallback method for all unsupported expression kind:
   llvm::Error fallback(const Stmt *E) {
-    return makeUnsupportedStmtKindError(E);
-  }
-
-  static EntityPointerLevel incrementPointerLevel(const EntityPointerLevel &E) {
-    return EntityPointerLevel(E.getEntity(), E.getPointerLevel() + 1);
-  }
-
-  static EntityPointerLevel decrementPointerLevel(const EntityPointerLevel &E) {
-    assert(E.getPointerLevel() > 0);
-    return EntityPointerLevel(E.getEntity(), E.getPointerLevel() - 1);
+    return makeErrAtNode(Ctx, *E,
+                         "attempt to translate %s to EntityPointerLevels",
+                         E->getStmtClassName());
   }
 
   EntityPointerLevel createEntityPointerLevelFor(const EntityName &Name) {
-    return EntityPointerLevel(AddEntity(Name), 1);
+    return EntityPointerLevel({AddEntity(Name), 1});
   }
 
   // The common helper function for Translate(*base):
   // Translate(*base) -> Translate(base) with .pointerLevel + 1
   Expected<EntityPointerLevelSet> translateDereferencePointer(const Expr *Ptr) {
-    assert(hasPointerType(Ptr));
+    assert(hasPtrOrArrType(*Ptr));
 
     Expected<EntityPointerLevelSet> SubResult = Visit(Ptr);
     if (!SubResult)
@@ -102,6 +97,29 @@ class ssaf::EntityPointerLevelTranslator
       : AddEntity(AddEntity), Ctx(Ctx) {}
 
   Expected<EntityPointerLevelSet> translate(const Expr *E) { return Visit(E); }
+  Expected<EntityPointerLevel> translate(const NamedDecl *D, bool IsRet) {
+    if (IsRet && !isa<FunctionDecl>(D))
+      return makeErrAtNode(
+          Ctx, *D,
+          "attempt to call getEntityNameForReturn on a NamedDecl of %s kind",
+          D->getDeclKindName());
+
+    std::optional<EntityName> EN =
+        IsRet ? getEntityNameForReturn(cast<FunctionDecl>(D))
+              : getEntityName(D);
+    if (EN)
+      return createEntityPointerLevelFor(*EN);
+    return makeEntityNameErr(Ctx, *D);
+  }
+
+  static EntityPointerLevel incrementPointerLevel(const EntityPointerLevel &E) {
+    return EntityPointerLevel({E.getEntity(), E.getPointerLevel() + 1});
+  }
+
+  static EntityPointerLevel decrementPointerLevel(const EntityPointerLevel &E) {
+    assert(E.getPointerLevel() > 0);
+    return EntityPointerLevel({E.getEntity(), E.getPointerLevel() - 1});
+  }
 
 private:
   Expected<EntityPointerLevelSet> VisitStmt(const Stmt *E) {
@@ -116,7 +134,7 @@ class ssaf::EntityPointerLevelTranslator
   Expected<EntityPointerLevelSet> VisitBinaryOperator(const BinaryOperator *E) {
     switch (E->getOpcode()) {
     case clang::BO_Add:
-      if (hasPointerType(E->getLHS()))
+      if (hasPtrOrArrType(*E->getLHS()))
         return Visit(E->getLHS());
       return Visit(E->getRHS());
     case clang::BO_Sub:
@@ -161,7 +179,7 @@ class ssaf::EntityPointerLevelTranslator
   // Translate((T*)base) -> Translate(p) if p has pointer type
   //                     -> {} otherwise
   Expected<EntityPointerLevelSet> VisitCastExpr(const CastExpr *E) {
-    if (hasPointerType(E->getSubExpr()))
+    if (hasPtrOrArrType(*E->getSubExpr()))
       return Visit(E->getSubExpr());
     return EntityPointerLevelSet{};
   }
@@ -214,14 +232,14 @@ class ssaf::EntityPointerLevelTranslator
   Expected<EntityPointerLevelSet> VisitDeclRefExpr(const DeclRefExpr *E) {
     if (auto EntityName = getEntityName(E->getDecl()))
       return EntityPointerLevelSet{createEntityPointerLevelFor(*EntityName)};
-    return makeCreateEntityNameError(E->getDecl(), Ctx);
+    return makeEntityNameErr(Ctx, *E->getDecl());
   }
 
   // Translate({., ->}f) -> {(MemberDecl, 1)}
   Expected<EntityPointerLevelSet> VisitMemberExpr(const MemberExpr *E) {
     if (auto EntityName = getEntityName(E->getMemberDecl()))
       return EntityPointerLevelSet{createEntityPointerLevelFor(*EntityName)};
-    return makeCreateEntityNameError(E->getMemberDecl(), Ctx);
+    return makeEntityNameErr(Ctx, *E->getMemberDecl());
   }
 
   Expected<EntityPointerLevelSet>
@@ -238,7 +256,62 @@ Expected<EntityPointerLevelSet> clang::ssaf::translateEntityPointerLevel(
   return Translator.translate(E);
 }
 
+/// Create an EntityPointerLevel from a ValueDecl of a pointer type.
+Expected<EntityPointerLevel> clang::ssaf::creatEntityPointerLevel(
+    const NamedDecl *D, ASTContext &Ctx,
+    std::function<EntityId(EntityName EN)> AddEntity, bool IsFunRet) {
+  EntityPointerLevelTranslator Translator(AddEntity, Ctx);
+
+  return Translator.translate(D, IsFunRet);
+}
+
+EntityPointerLevel
+clang::ssaf::incrementPointerLevel(const EntityPointerLevel &E) {
+  return EntityPointerLevelTranslator::incrementPointerLevel(E);
+}
+
 EntityPointerLevel clang::ssaf::buildEntityPointerLevel(EntityId Id,
                                                         unsigned PtrLv) {
   return EntityPointerLevel({Id, PtrLv});
 }
+
+// Writes an EntityPointerLevel as
+// Array [
+//   Object { "@" : [entity-id]},
+//   [pointer-level-integer]
+// ]
+llvm::json::Value clang::ssaf::entityPointerLevelToJSON(
+    const EntityPointerLevel &EPL, JSONFormat::EntityIdToJSONFn EntityId2JSON) {
+  return llvm::json::Array{EntityId2JSON(EPL.getEntity()),
+                           llvm::json::Value(EPL.getPointerLevel())};
+}
+
+Expected<EntityPointerLevel> clang::ssaf::entityPointerLevelFromJSON(
+    const llvm::json::Value &EPLData,
+    JSONFormat::EntityIdFromJSONFn EntityIdFromJSON) {
+  auto *AsArr = EPLData.getAsArray();
+
+  if (!AsArr || AsArr->size() != 2)
+    return makeSawButExpectedError(
+        EPLData, "an array with exactly two elements representing "
+                 "EntityId and PointerLevel, respectively");
+
+  auto *EntityIdObj = (*AsArr)[0].getAsObject();
+
+  if (!EntityIdObj)
+    return makeSawButExpectedError((*AsArr)[0],
+                                   "an object representing EntityId");
+
+  Expected<EntityId> Id = EntityIdFromJSON(*EntityIdObj);
+
+  if (!Id)
+    return Id.takeError();
+
+  std::optional<uint64_t> PtrLv = (*AsArr)[1].getAsInteger();
+
+  if (!PtrLv)
+    return makeSawButExpectedError((*AsArr)[1],
+                                   "an integer representing PointerLevel");
+
+  return buildEntityPointerLevel(*Id, *PtrLv);
+}
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp
index 84f3f9cbb3852..47e03476d1063 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp
@@ -7,8 +7,9 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h"
+#include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
+#include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.h"
-#include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityId.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Serialization/JSONFormat.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Support/JSON.h"
@@ -37,8 +38,7 @@ static Object serialize(const EntitySummary &S,
   Array UnsafeBuffersData;
 
   for (const auto &EPL : getUnsafeBuffers(SS))
-    UnsafeBuffersData.push_back(
-        Array{Fn(EPL.getEntity()), EPL.getPointerLevel()});
+    UnsafeBuffersData.push_back(entityPointerLevelToJSON(EPL, Fn));
   return Object{{SummarySerializationKey.data(), std::move(UnsafeBuffersData)}};
 }
 
@@ -48,28 +48,18 @@ deserializeImpl(const Object &Data, JSONFormat::EntityIdFromJSONFn Fn) {
       Data.getArray(SummarySerializationKey.data());
 
   if (!UnsafeBuffersData)
-    return llvm::createStringError("expected a json::Object with a key %s",
+    return makeSawButExpectedError(Object(Data), "an Object with a key %s",
                                    SummarySerializationKey.data());
 
   EntityPointerLevelSet EPLs;
 
   for (const auto &EltData : *UnsafeBuffersData) {
-    const Array *EltDataAsArr = EltData.getAsArray();
+    llvm::Expected<EntityPointerLevel> EPL =
+        entityPointerLevelFromJSON(EltData, Fn);
 
-    if (!EltDataAsArr || EltDataAsArr->size() != 2)
-      return llvm::createStringError("expected a json::Array of size 2");
-
-    const Object *IdData = (*EltDataAsArr)[0].getAsObject();
-    std::optional<uint64_t> PtrLvData = (*EltDataAsArr)[1].getAsInteger();
-
-    if (!IdData || !PtrLvData)
-      return llvm::createStringError("expected a json::Value of integer type");
-
-    llvm::Expected<EntityId> Id = Fn(*IdData);
-
-    if (!Id)
-      return Id.takeError();
-    EPLs.insert(buildEntityPointerLevel(Id.get(), *PtrLvData));
+    if (!EPL)
+      return EPL.takeError();
+    EPLs.insert(*EPL);
   }
   return std::make_unique<UnsafeBufferUsageEntitySummary>(
       buildUnsafeBufferUsageEntitySummary(std::move(EPLs)));
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
index b29eaa6b903d0..c412855028efb 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
@@ -9,14 +9,14 @@
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
-#include "clang/AST/Decl.h"
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
 #include "clang/Analysis/Analyses/UnsafeBufferUsage.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/ASTEntityMapping.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityId.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityName.h"
 #include "llvm/ADT/STLExtras.h"
-#include "llvm/ADT/iterator_range.h"
 #include "llvm/Support/Error.h"
 #include <memory>
 
diff --git a/clang/test/Analysis/Scalable/UnsafeBufferUsage/tu-summary-serialization.test b/clang/test/Analysis/Scalable/UnsafeBufferUsage/tu-summary-serialization.test
index 6a12949f3bbb4..55357acb1db08 100644
--- a/clang/test/Analysis/Scalable/UnsafeBufferUsage/tu-summary-serialization.test
+++ b/clang/test/Analysis/Scalable/UnsafeBufferUsage/tu-summary-serialization.test
@@ -6,13 +6,21 @@
 
 // RUN: not clang-ssaf-format -type=tu %S/Inputs/tu-summary-no-key.json 2>&1 \
 // RUN: | FileCheck %s --check-prefix=CHECK-NO-KEY
-// CHECK-NO-KEY: expected a json::Object with a key UnsafeBuffers
-
+// CHECK-NO-KEY: saw {
+// CHECK-NO-KEY:   "NotUnsafeBuffers": [
+// CHECK-NO-KEY:     [
+// CHECK-NO-KEY:       {
+// CHECK-NO-KEY:         "@": 0
+// CHECK-NO-KEY:       },
+// CHECK-NO-KEY:       1
+// CHECK-NO-KEY:     ]
+// CHECK-NO-KEY:   ]
+// CHECK-NO-KEY: } but expected an Object with a key UnsafeBuffers
 
 // RUN: not clang-ssaf-format -type=tu %S/Inputs/tu-summary-bad-element.json 2>&1 \
 // RUN: | FileCheck %s --check-prefix=CHECK-BAD-ELEMENT
-// CHECK-BAD-ELEMENT: expected a json::Array of size 2
+// CHECK-BAD-ELEMENT: saw 42 but expected an array with exactly two elements representing EntityId and PointerLevel, respectively 
 
 // RUN: not clang-ssaf-format -type=tu %S/Inputs/tu-summary-bad-ptr-level.json 2>&1 \
 // RUN:   | FileCheck %s --check-prefix=CHECK-BAD-PTR-LEVEL
-// CHECK-BAD-PTR-LEVEL: expected a json::Value of integer type
+// CHECK-BAD-PTR-LEVEL: saw "not-an-integer" but expected an integer representing PointerLevel

>From 11bc5e09f34e30a9e1972631afd0071eda080851 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 13 Apr 2026 10:49:09 -0700
Subject: [PATCH 03/25] Update
 clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Balázs Benics <benicsbalazs at gmail.com>
---
 .../Analyses/EntityPointerLevel/EntityPointerLevel.cpp       | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
index 78afdf956eb57..ebbb060605a6c 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
@@ -28,10 +28,7 @@ template <typename NodeTy, typename... Ts>
 static inline llvm::Error makeErrAtNode(ASTContext &Ctx, const NodeTy &N,
                                         StringRef Fmt, const Ts &...Args) {
   std::string LocStr = N.getBeginLoc().printToString(Ctx.getSourceManager());
-  llvm::SmallVector<char> FmtData;
-
-  (Fmt + " at %s").toStringRef(FmtData);
-  return llvm::createStringError(FmtData.data(), Args..., LocStr.c_str());
+  return llvm::createStringError((Fmt + " at %s").str().c_str(), Args..., LocStr.c_str());
 }
 
 static inline llvm::Error makeEntityNameErr(ASTContext &Ctx,

>From 3b4bddf9b30a1db848bec33878c636e9ad768c27 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 13 Apr 2026 11:08:46 -0700
Subject: [PATCH 04/25] Update
 clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Balázs Benics <benicsbalazs at gmail.com>
---
 .../Analyses/EntityPointerLevel/EntityPointerLevelFormat.h     | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
index 766e425338e96..574e8d27f8356 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
@@ -30,4 +30,5 @@ Expected<EntityPointerLevel>
 entityPointerLevelFromJSON(const llvm::json::Value &EPLData,
                            JSONFormat::EntityIdFromJSONFn EntityIdFromJSON);
 } // namespace clang::ssaf
-#endif // LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVELFORMAT_H
\ No newline at end of file
+
+#endif // LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVELFORMAT_H

>From ab919452501d381fa197dac2c2da7391526da6d4 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 13 Apr 2026 11:09:16 -0700
Subject: [PATCH 05/25] Update
 clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Balázs Benics <benicsbalazs at gmail.com>
---
 .../Analyses/EntityPointerLevel/EntityPointerLevelFormat.h       | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
index 574e8d27f8356..4d62a58adfdd7 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
@@ -8,6 +8,7 @@
 
 #ifndef LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVELFORMAT_H
 #define LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVELFORMAT_H
+
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Serialization/JSONFormat.h"
 

>From d44fad76c7012ee394c664568aad66061358e8b0 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 13 Apr 2026 12:11:52 -0700
Subject: [PATCH 06/25] address comments

---
 .../EntityPointerLevel/EntityPointerLevel.h   | 14 +++----
 .../EntityPointerLevelFormat.h                |  8 ++--
 .../EntityPointerLevel/EntityPointerLevel.cpp | 39 ++++++++++---------
 .../tu-summary-serialization.test             | 22 +++++------
 4 files changed, 43 insertions(+), 40 deletions(-)

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
index 6f5687fd186c9..ed8400f65e310 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
@@ -12,6 +12,7 @@
 #include "clang/AST/Expr.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityId.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityName.h"
+#include "llvm/ADT/STLFunctionalExtras.h"
 #include <set>
 
 namespace clang::ssaf {
@@ -92,23 +93,22 @@ using EntityPointerLevelSet =
 /// \param Ctx the AST context of `E`
 /// \param AddEntity the callback provided by the caller to convert EntityNames
 /// to EntityIds.
-llvm::Expected<EntityPointerLevelSet>
-translateEntityPointerLevel(const Expr *E, ASTContext &Ctx,
-                            std::function<EntityId(EntityName EN)> AddEntity);
+llvm::Expected<EntityPointerLevelSet> translateEntityPointerLevel(
+    const Expr *E, ASTContext &Ctx,
+    llvm::function_ref<EntityId(EntityName EN)> AddEntity);
 
 EntityPointerLevel buildEntityPointerLevel(EntityId, unsigned);
 
 /// Create an EntityPointerLevel (EPL) from a NamedDecl of a pointer/array type.
 ///
-/// \param E the pointer expression to be translated
-/// \param Ctx the AST context of `E`
+/// \param ND the NamedDecl of a pointer/array type.
 /// \param AddEntity the callback provided by the caller to convert EntityNames
 /// to EntityIds.
 /// \param IsFunRet true iff the created EPL is associated with the return type
 /// of a function entity.
 llvm::Expected<EntityPointerLevel>
-creatEntityPointerLevel(const NamedDecl *ND, ASTContext &Ctx,
-                        std::function<EntityId(EntityName EN)> AddEntity,
+creatEntityPointerLevel(const NamedDecl *ND,
+                        llvm::function_ref<EntityId(EntityName EN)> AddEntity,
                         bool IsFunRet = false);
 
 /// Creates a new EntityPointerLevel (EPL) from `E` by incrementing `E`'s
diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
index 4d62a58adfdd7..4e7a9eff32d5c 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
@@ -12,15 +12,17 @@
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Serialization/JSONFormat.h"
 
+namespace {
 template <typename... Ts>
-static inline llvm::Error makeSawButExpectedError(const llvm::json::Value &Saw,
-                                                  llvm::StringRef Expected,
-                                                  const Ts &...ExpectedArgs) {
+llvm::Error makeSawButExpectedError(const llvm::json::Value &Saw,
+                                    llvm::StringRef Expected,
+                                    const Ts &...ExpectedArgs) {
   std::string Fmt = ("saw %s but expected " + Expected).str();
   std::string SawStr = llvm::formatv("{0:2}", Saw).str();
 
   return llvm::createStringError(Fmt.c_str(), SawStr.c_str(), ExpectedArgs...);
 }
+} // namespace
 
 namespace clang::ssaf {
 llvm::json::Value
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
index ebbb060605a6c..22151c2de1c84 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
@@ -18,25 +18,25 @@
 using namespace clang;
 using namespace ssaf;
 
-template <typename DeclOrExpr>
-static bool hasPtrOrArrType(const DeclOrExpr &E) {
-  return llvm::isa<PointerType>(E.getType().getCanonicalType()) ||
-         llvm::isa<ArrayType>(E.getType().getCanonicalType());
+namespace {
+template <typename DeclOrExpr> bool hasPtrOrArrType(const DeclOrExpr *E) {
+  return llvm::isa<PointerType, ArrayType>(E->getType().getCanonicalType());
 }
 
 template <typename NodeTy, typename... Ts>
-static inline llvm::Error makeErrAtNode(ASTContext &Ctx, const NodeTy &N,
-                                        StringRef Fmt, const Ts &...Args) {
+llvm::Error makeErrAtNode(ASTContext &Ctx, const NodeTy &N, StringRef Fmt,
+                          const Ts &...Args) {
   std::string LocStr = N.getBeginLoc().printToString(Ctx.getSourceManager());
   return llvm::createStringError((Fmt + " at %s").str().c_str(), Args..., LocStr.c_str());
 }
 
-static inline llvm::Error makeEntityNameErr(ASTContext &Ctx,
-                                            const NamedDecl &D) {
+llvm::Error makeEntityNameErr(ASTContext &Ctx, const NamedDecl &D) {
   return makeErrAtNode(Ctx, D, "failed to create entity name for %s",
                        D.getNameAsString().data());
 }
+} // namespace
 
+namespace clang::ssaf {
 // Translate a pointer type expression 'E' to a (set of) EntityPointerLevel(s)
 // associated with the declared type of the base address of `E`. If the base
 // address of `E` is not associated with an entity, the translation result is an
@@ -56,9 +56,9 @@ static inline llvm::Error makeEntityNameErr(ASTContext &Ctx,
 //   Translate(arr[5])             -> {(arr, 2)}
 //   Translate(cond ? p1[5] : p2)  -> {(p1, 2), (p2, 1)}
 //   Translate(&arr[5])            -> {(arr, 1)}
-class ssaf::EntityPointerLevelTranslator
-    : public ConstStmtVisitor<EntityPointerLevelTranslator,
-                              Expected<EntityPointerLevelSet>> {
+class EntityPointerLevelTranslator
+    : ConstStmtVisitor<EntityPointerLevelTranslator,
+                       Expected<EntityPointerLevelSet>> {
   friend class StmtVisitorBase;
 
   // Fallback method for all unsupported expression kind:
@@ -75,7 +75,7 @@ class ssaf::EntityPointerLevelTranslator
   // The common helper function for Translate(*base):
   // Translate(*base) -> Translate(base) with .pointerLevel + 1
   Expected<EntityPointerLevelSet> translateDereferencePointer(const Expr *Ptr) {
-    assert(hasPtrOrArrType(*Ptr));
+    assert(hasPtrOrArrType(Ptr));
 
     Expected<EntityPointerLevelSet> SubResult = Visit(Ptr);
     if (!SubResult)
@@ -131,7 +131,7 @@ class ssaf::EntityPointerLevelTranslator
   Expected<EntityPointerLevelSet> VisitBinaryOperator(const BinaryOperator *E) {
     switch (E->getOpcode()) {
     case clang::BO_Add:
-      if (hasPtrOrArrType(*E->getLHS()))
+      if (hasPtrOrArrType(E->getLHS()))
         return Visit(E->getLHS());
       return Visit(E->getRHS());
     case clang::BO_Sub:
@@ -176,7 +176,7 @@ class ssaf::EntityPointerLevelTranslator
   // Translate((T*)base) -> Translate(p) if p has pointer type
   //                     -> {} otherwise
   Expected<EntityPointerLevelSet> VisitCastExpr(const CastExpr *E) {
-    if (hasPtrOrArrType(*E->getSubExpr()))
+    if (hasPtrOrArrType(E->getSubExpr()))
       return Visit(E->getSubExpr());
     return EntityPointerLevelSet{};
   }
@@ -244,10 +244,11 @@ class ssaf::EntityPointerLevelTranslator
     return Visit(S->getSourceExpr());
   }
 };
+} // namespace clang::ssaf
 
 Expected<EntityPointerLevelSet> clang::ssaf::translateEntityPointerLevel(
     const Expr *E, ASTContext &Ctx,
-    std::function<EntityId(EntityName EN)> AddEntity) {
+    llvm::function_ref<EntityId(EntityName EN)> AddEntity) {
   EntityPointerLevelTranslator Translator(AddEntity, Ctx);
 
   return Translator.translate(E);
@@ -255,11 +256,11 @@ Expected<EntityPointerLevelSet> clang::ssaf::translateEntityPointerLevel(
 
 /// Create an EntityPointerLevel from a ValueDecl of a pointer type.
 Expected<EntityPointerLevel> clang::ssaf::creatEntityPointerLevel(
-    const NamedDecl *D, ASTContext &Ctx,
-    std::function<EntityId(EntityName EN)> AddEntity, bool IsFunRet) {
-  EntityPointerLevelTranslator Translator(AddEntity, Ctx);
+    const NamedDecl *ND, llvm::function_ref<EntityId(EntityName EN)> AddEntity,
+    bool IsFunRet) {
+  EntityPointerLevelTranslator Translator(AddEntity, ND->getASTContext());
 
-  return Translator.translate(D, IsFunRet);
+  return Translator.translate(ND, IsFunRet);
 }
 
 EntityPointerLevel
diff --git a/clang/test/Analysis/Scalable/UnsafeBufferUsage/tu-summary-serialization.test b/clang/test/Analysis/Scalable/UnsafeBufferUsage/tu-summary-serialization.test
index 55357acb1db08..ff13aa7f8ca27 100644
--- a/clang/test/Analysis/Scalable/UnsafeBufferUsage/tu-summary-serialization.test
+++ b/clang/test/Analysis/Scalable/UnsafeBufferUsage/tu-summary-serialization.test
@@ -5,17 +5,17 @@
 // Negative tests:
 
 // RUN: not clang-ssaf-format -type=tu %S/Inputs/tu-summary-no-key.json 2>&1 \
-// RUN: | FileCheck %s --check-prefix=CHECK-NO-KEY
-// CHECK-NO-KEY: saw {
-// CHECK-NO-KEY:   "NotUnsafeBuffers": [
-// CHECK-NO-KEY:     [
-// CHECK-NO-KEY:       {
-// CHECK-NO-KEY:         "@": 0
-// CHECK-NO-KEY:       },
-// CHECK-NO-KEY:       1
-// CHECK-NO-KEY:     ]
-// CHECK-NO-KEY:   ]
-// CHECK-NO-KEY: } but expected an Object with a key UnsafeBuffers
+// RUN: | FileCheck %s --check-prefix=CHECK-MISSING-KEY
+// CHECK-MISSING-KEY: saw {
+// CHECK-MISSING-KEY-NEXT:   "NotUnsafeBuffers": [
+// CHECK-MISSING-KEY-NEXT:     [
+// CHECK-MISSING-KEY-NEXT:       {
+// CHECK-MISSING-KEY-NEXT:         "@": 0
+// CHECK-MISSING-KEY-NEXT:       },
+// CHECK-MISSING-KEY-NEXT:       1
+// CHECK-MISSING-KEY-NEXT:     ]
+// CHECK-MISSING-KEY-NEXT:   ]
+// CHECK-MISSING-KEY-NEXT: } but expected an Object with a key UnsafeBuffers
 
 // RUN: not clang-ssaf-format -type=tu %S/Inputs/tu-summary-bad-element.json 2>&1 \
 // RUN: | FileCheck %s --check-prefix=CHECK-BAD-ELEMENT

>From 39fbbba0f8753a295c32cb17ad82308722d0655d Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 13 Apr 2026 14:33:15 -0700
Subject: [PATCH 07/25] fix format

---
 .../Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h          | 6 ------
 .../Analyses/EntityPointerLevel/EntityPointerLevel.cpp      | 3 ++-
 2 files changed, 2 insertions(+), 7 deletions(-)

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h
index ea01a0f0b19f7..27bda9f773085 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h
@@ -14,14 +14,8 @@
 #include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/EntitySummary.h"
 
 namespace clang::ssaf {
-<<<<<<< users/ziqingluo/PR-172429193-pre-2
 /// An UnsafeBufferUsageEntitySummary contains a set of EntityPointerLevels
 /// extracted from unsafe buffer pointers contributed by an entity.
-=======
-
-/// An UnsafeBufferUsageEntitySummary is an immutable set of unsafe buffers, in
-/// the form of EntityPointerLevel.
->>>>>>> main
 class UnsafeBufferUsageEntitySummary final : public EntitySummary {
   const EntityPointerLevelSet UnsafeBuffers;
 
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
index 22151c2de1c84..7e4200467ce9e 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
@@ -27,7 +27,8 @@ template <typename NodeTy, typename... Ts>
 llvm::Error makeErrAtNode(ASTContext &Ctx, const NodeTy &N, StringRef Fmt,
                           const Ts &...Args) {
   std::string LocStr = N.getBeginLoc().printToString(Ctx.getSourceManager());
-  return llvm::createStringError((Fmt + " at %s").str().c_str(), Args..., LocStr.c_str());
+  return llvm::createStringError((Fmt + " at %s").str().c_str(), Args...,
+                                 LocStr.c_str());
 }
 
 llvm::Error makeEntityNameErr(ASTContext &Ctx, const NamedDecl &D) {

>From 65abbbd4e682d67ee4fe642f8898cb5bb52ed6f6 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 13 Apr 2026 17:26:04 -0700
Subject: [PATCH 08/25] [SSAF][UnsafeBufferUsage] Remove
 UnsafeBufferUsageExtractor.h

- Removed UnsafeBufferUsageExtractor.h
- Registered UnsafeBufferUsageExtractor
- Changed unit tests to enable the extractor with `HandleTranslationUnit`
- Fixed bugs in `UnsafeBufferUsageExtractor::HandleTranslationUnit`
---
 .../UnsafeBufferUsageExtractor.h              |  35 --
 .../SSAFBuiltinForceLinker.h                  |   5 +
 .../UnsafeBufferUsageExtractor.cpp            | 142 ++++----
 .../UnsafeBufferUsageTest.cpp                 | 313 ++++++++++--------
 4 files changed, 258 insertions(+), 237 deletions(-)
 delete mode 100644 clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h
deleted file mode 100644
index 13d4e18b4e81f..0000000000000
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h
+++ /dev/null
@@ -1,35 +0,0 @@
-//===- UnsafeBufferUsageExtractor.h -----------------------------*- 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
-//
-//===----------------------------------------------------------------------===//
-#ifndef LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_UNSAFEBUFFERUSAGE_UNSAFEBUFFERUSAGEBUILDER_H
-#define LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_UNSAFEBUFFERUSAGE_UNSAFEBUFFERUSAGEBUILDER_H
-
-#include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h"
-#include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityId.h"
-#include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityName.h"
-#include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/TUSummaryBuilder.h"
-#include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/TUSummaryExtractor.h"
-#include "llvm/Support/Error.h"
-#include <memory>
-
-namespace clang::ssaf {
-class UnsafeBufferUsageTUSummaryExtractor : public TUSummaryExtractor {
-public:
-  UnsafeBufferUsageTUSummaryExtractor(TUSummaryBuilder &Builder)
-      : TUSummaryExtractor(Builder) {}
-
-  EntityId addEntity(EntityName EN) { return SummaryBuilder.addEntity(EN); }
-
-  std::unique_ptr<UnsafeBufferUsageEntitySummary>
-  extractEntitySummary(const Decl *Contributor, ASTContext &Ctx,
-                       llvm::Error &Error);
-
-  void HandleTranslationUnit(ASTContext &Ctx) override;
-};
-} // namespace clang::ssaf
-
-#endif // LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_UNSAFEBUFFERUSAGE_UNSAFEBUFFERUSAGEBUILDER_H
diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/SSAFBuiltinForceLinker.h b/clang/include/clang/ScalableStaticAnalysisFramework/SSAFBuiltinForceLinker.h
index 2030dc8a12030..916ef1ce783c4 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/SSAFBuiltinForceLinker.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/SSAFBuiltinForceLinker.h
@@ -36,6 +36,11 @@ extern volatile int UnsafeBufferUsageSSAFJSONFormatAnchorSource;
 [[maybe_unused]] static int UnsafeBufferUsageSSAFJSONFormatAnchorDestination =
     UnsafeBufferUsageSSAFJSONFormatAnchorSource;
 
+extern volatile int UnsafeBufferUsageTUSummaryExtractorAnchorSource;
+[[maybe_unused]] static int
+    UnsafeBufferUsageTUSummaryExtractorAnchorDestination =
+        UnsafeBufferUsageTUSummaryExtractorAnchorSource;
+
 // This anchor is used to force the linker to link the CallGraphExtractor.
 extern volatile int CallGraphExtractorAnchorSource;
 [[maybe_unused]] static int CallGraphExtractorAnchorDestination =
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
index c412855028efb..72944bd0be323 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
@@ -6,7 +6,6 @@
 //
 //===----------------------------------------------------------------------===//
 
-#include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
@@ -16,6 +15,9 @@
 #include "clang/ScalableStaticAnalysisFramework/Core/ASTEntityMapping.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityId.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityName.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/ExtractorRegistry.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/TUSummaryBuilder.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/TUSummaryExtractor.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Error.h"
 #include <memory>
@@ -24,8 +26,8 @@ namespace {
 using namespace clang;
 using namespace ssaf;
 
-static llvm::Error makeCreateEntityNameError(const NamedDecl *FailedDecl,
-                                             ASTContext &Ctx) {
+llvm::Error makeCreateEntityNameError(const NamedDecl *FailedDecl,
+                                      ASTContext &Ctx) {
   std::string LocStr = FailedDecl->getSourceRange().getBegin().printToString(
       Ctx.getSourceManager());
   return llvm::createStringError(
@@ -33,19 +35,8 @@ static llvm::Error makeCreateEntityNameError(const NamedDecl *FailedDecl,
       FailedDecl->getNameAsString().c_str(), LocStr.c_str());
 }
 
-static llvm::Error makeAddEntitySummaryError(const NamedDecl *FailedContributor,
-                                             ASTContext &Ctx) {
-  std::string LocStr =
-      FailedContributor->getSourceRange().getBegin().printToString(
-          Ctx.getSourceManager());
-  return llvm::createStringError(
-      "failed to add entity summary for contributor %s declared at %s",
-      FailedContributor->getNameAsString().c_str(), LocStr.c_str());
-}
-
 Expected<EntityPointerLevelSet>
 buildEntityPointerLevels(std::set<const Expr *> &&UnsafePointers,
-                         UnsafeBufferUsageTUSummaryExtractor &Extractor,
                          ASTContext &Ctx,
                          std::function<EntityId(EntityName)> AddEntity) {
   EntityPointerLevelSet Result{};
@@ -71,7 +62,6 @@ buildEntityPointerLevels(std::set<const Expr *> &&UnsafePointers,
     return AllErrors;
   return Result;
 }
-} // namespace
 
 static std::set<const Expr *> findUnsafePointersInContributor(const Decl *D) {
   if (isa<FunctionDecl>(D) || isa<VarDecl>(D))
@@ -86,78 +76,84 @@ static std::set<const Expr *> findUnsafePointersInContributor(const Decl *D) {
   }
   return {};
 }
+} // namespace
 
-std::unique_ptr<UnsafeBufferUsageEntitySummary>
-UnsafeBufferUsageTUSummaryExtractor::extractEntitySummary(
-    const Decl *Contributor, ASTContext &Ctx, llvm::Error &Error) {
-  auto AddEntity = [this](EntityName EN) { return addEntity(EN); };
-  Expected<EntityPointerLevelSet> EPLs = buildEntityPointerLevels(
-      findUnsafePointersInContributor(Contributor), *this, Ctx, AddEntity);
-
-  if (EPLs)
-    return std::make_unique<UnsafeBufferUsageEntitySummary>(
-        UnsafeBufferUsageEntitySummary(std::move(*EPLs)));
-  Error = EPLs.takeError();
-  return nullptr;
-}
+class clang::ssaf::UnsafeBufferUsageTUSummaryExtractor
+    : public TUSummaryExtractor {
+public:
+  UnsafeBufferUsageTUSummaryExtractor(TUSummaryBuilder &Builder)
+      : TUSummaryExtractor(Builder) {}
 
-void UnsafeBufferUsageTUSummaryExtractor::HandleTranslationUnit(
-    ASTContext &Ctx) {
+  EntityId addEntity(EntityName EN) { return SummaryBuilder.addEntity(EN); }
 
-  // FIXME: I suppose finding contributor Decls is commonly needed by all/many
-  // extractors
-  class ContributorFinder : public DynamicRecursiveASTVisitor {
-  public:
-    std::vector<const NamedDecl *> Contributors;
+  Expected<std::unique_ptr<UnsafeBufferUsageEntitySummary>>
+  extractEntitySummary(const Decl *Contributor, ASTContext &Ctx) {
+    auto AddEntity = [this](EntityName EN) { return addEntity(EN); };
+    Expected<EntityPointerLevelSet> EPLs = buildEntityPointerLevels(
+        findUnsafePointersInContributor(Contributor), Ctx, AddEntity);
 
-    bool VisitFunctionDecl(FunctionDecl *D) override {
-      Contributors.push_back(D);
-      return true;
-    }
+    if (EPLs)
+      return std::make_unique<UnsafeBufferUsageEntitySummary>(
+          UnsafeBufferUsageEntitySummary(std::move(*EPLs)));
+    return EPLs.takeError();
+  }
 
-    bool VisitRecordDecl(RecordDecl *D) override {
-      Contributors.push_back(D);
-      return true;
-    }
+  void HandleTranslationUnit(ASTContext &Ctx) override {
 
-    bool VisitVarDecl(VarDecl *D) override {
-      DeclContext *DC = D->getDeclContext();
+    // FIXME: I suppose finding contributor Decls is commonly needed by all/many
+    // extractors
+    class ContributorFinder : public DynamicRecursiveASTVisitor {
+    public:
+      std::vector<const NamedDecl *> Contributors;
 
-      if (DC->isFileContext() || DC->isNamespace())
+      bool VisitFunctionDecl(FunctionDecl *D) override {
         Contributors.push_back(D);
-      return false;
-    }
-  } ContributorFinder;
+        return true;
+      }
 
-  ContributorFinder.VisitTranslationUnitDecl(Ctx.getTranslationUnitDecl());
+      bool VisitRecordDecl(RecordDecl *D) override {
+        Contributors.push_back(D);
+        return true;
+      }
 
-  llvm::Error Errors = llvm::ErrorSuccess();
-  auto addError = [&Errors](llvm::Error Err) {
-    Errors = llvm::joinErrors(std::move(Errors), std::move(Err));
-  };
+      bool VisitVarDecl(VarDecl *D) override {
+        DeclContext *DC = D->getDeclContext();
 
-  for (auto *CD : ContributorFinder.Contributors) {
-    llvm::Error Error = llvm::ErrorSuccess();
-    auto EntitySummary = extractEntitySummary(CD, Ctx, Error);
+        if (DC->isFileContext() || DC->isNamespace())
+          Contributors.push_back(D);
+        return true;
+      }
+    } ContributorFinder;
 
-    if (Error)
-      addError(std::move(Error));
-    if (EntitySummary->empty())
-      continue;
+    ContributorFinder.VisitTranslationUnitDecl(Ctx.getTranslationUnitDecl());
 
-    auto ContributorName = getEntityName(CD);
+    ContributorFinder.TraverseAST(Ctx);
+    for (auto *CD : ContributorFinder.Contributors) {
+      auto EntitySummary = extractEntitySummary(CD, Ctx);
 
-    if (!ContributorName) {
-      addError(makeCreateEntityNameError(CD, Ctx));
-      continue;
-    }
+      if (!EntitySummary)
+        llvm::reportFatalInternalError(EntitySummary.takeError());
+      assert(*EntitySummary);
+      if ((*EntitySummary)->empty())
+        continue;
+
+      auto ContributorName = getEntityName(CD);
 
-    auto [EntitySummaryPtr, Success] = SummaryBuilder.addSummary(
-        addEntity(*ContributorName), std::move(EntitySummary));
+      if (!ContributorName)
+        llvm::reportFatalInternalError(makeCreateEntityNameError(CD, Ctx));
 
-    if (!Success)
-      addError(makeAddEntitySummaryError(CD, Ctx));
+      auto [Ignored, InsertionSucceeded] = SummaryBuilder.addSummary(
+          addEntity(*ContributorName), std::move(*EntitySummary));
+
+      assert(InsertionSucceeded && "duplicated contributor extraction");
+    }
   }
-  // FIXME: handle errors!
-  llvm::consumeError(std::move(Errors));
-}
+};
+
+// NOLINTNEXTLINE(misc-use-internal-linkage)
+volatile int UnsafeBufferUsageTUSummaryExtractorAnchorSource = 0;
+
+static clang::ssaf::TUSummaryExtractorRegistry::Add<
+    ssaf::UnsafeBufferUsageTUSummaryExtractor>
+    RegisterExtractor(UnsafeBufferUsageEntitySummary::Name,
+                      "The TUSummaryExtractor for unsafe buffer pointers");
\ No newline at end of file
diff --git a/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp b/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
index d2c513b7c70a2..59c2cd38ffacf 100644
--- a/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
+++ b/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
@@ -11,20 +11,23 @@
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
-#include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.h"
+#include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/ASTEntityMapping.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityId.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityIdTable.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityName.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/ExtractorRegistry.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/TUSummary.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/TUSummaryBuilder.h"
+#include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/TUSummaryExtractor.h"
 #include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Error.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include <initializer_list>
 #include <memory>
 #include <optional>
 
@@ -33,7 +36,6 @@ using namespace ssaf;
 using testing::UnorderedElementsAre;
 
 namespace {
-
 template <typename SomeDecl = NamedDecl>
 const SomeDecl *findDeclByName(StringRef Name, ASTContext &Ctx) {
   class NamedDeclFinder : public DynamicRecursiveASTVisitor {
@@ -68,52 +70,82 @@ class UnsafeBufferUsageTest : public TestFixture {
 protected:
   TUSummary TUSum;
   TUSummaryBuilder Builder;
-  UnsafeBufferUsageTUSummaryExtractor Extractor;
+  std::unique_ptr<TUSummaryExtractor> Extractor;
   std::unique_ptr<ASTUnit> AST;
 
   UnsafeBufferUsageTest()
       : TUSum(BuildNamespace(BuildNamespaceKind::CompilationUnit, "Mock.cpp")),
-        Builder(TUSum), Extractor(Builder) {}
+        Builder(TUSum), Extractor(nullptr) {}
 
-  template <typename ContributorDecl = NamedDecl>
-  std::unique_ptr<UnsafeBufferUsageEntitySummary>
-  setUpTest(StringRef Code, StringRef ContributorName) {
+  bool setUpTest(StringRef Code) {
     AST = tooling::buildASTFromCodeWithArgs(
         Code, {"-Wno-unused-value", "-Wno-int-to-pointer-cast"});
 
-    const auto *ContributorDefn =
-        findDeclByName<ContributorDecl>(ContributorName, AST->getASTContext());
+    for (auto &E : clang::ssaf::TUSummaryExtractorRegistry::entries()) {
+      if (E.getName() == UnsafeBufferUsageEntitySummary::Name) {
+        Extractor = E.instantiate(Builder);
+        break;
+      }
+    }
+
+    if (!Extractor) {
+      ADD_FAILURE() << "failed to find UnsafeBufferUsageTUSummaryExtractor";
+      return false;
+    }
+    Extractor->HandleTranslationUnit(AST->getASTContext());
+    return true;
+  }
 
-    if (!ContributorDefn)
+  template <typename ContributorDecl = NamedDecl>
+  const UnsafeBufferUsageEntitySummary *
+  getEntitySummary(StringRef ContributorEntityName) {
+    auto *ContributorDefn = findDeclByName<ContributorDecl>(
+        ContributorEntityName, AST->getASTContext());
+
+    if (!ContributorDefn) {
+      ADD_FAILURE() << "failed to find Decl of \"" << ContributorEntityName
+                    << "\"";
       return nullptr;
+    }
 
     std::optional<EntityName> EN = getEntityName(ContributorDefn);
 
-    if (!EN)
+    if (!EN) {
+      ADD_FAILURE() << "failed to get EntityName for contributor \""
+                    << ContributorEntityName << "\"";
       return nullptr;
+    }
 
-    llvm::Error Error = llvm::ErrorSuccess();
-    auto Sum = Extractor.extractEntitySummary(ContributorDefn,
-                                              AST->getASTContext(), Error);
+    EntityId ContributorEntityId = Builder.addEntity(*EN);
+    auto &TUSumData = getData(TUSum);
+    auto EntitiesSumIter =
+        TUSumData.find(UnsafeBufferUsageEntitySummary::summaryName());
 
-    if (Error) {
-      llvm::consumeError(std::move(Error));
+    // If none entity summary was collected, it may not be an entry in
+    // `TUSumData`:
+    if (EntitiesSumIter == TUSumData.end())
       return nullptr;
-    }
-    return Sum;
+
+    auto EntitySumIter = EntitiesSumIter->second.find(ContributorEntityId);
+
+    // If entity summary is empty, it may not exist:
+    if (EntitySumIter == EntitiesSumIter->second.end())
+      return nullptr;
+    return static_cast<const UnsafeBufferUsageEntitySummary *>(
+        EntitySumIter->second.get());
   }
 
   std::optional<EntityId> getEntityId(StringRef Name) {
     if (const auto *D = findDeclByName(Name, AST->getASTContext()))
       if (auto EntityName = getEntityName(D))
-        return Extractor.addEntity(*EntityName);
+        return Builder.addEntity(*EntityName);
     return std::nullopt;
   }
 
   std::optional<EntityId> getEntityIdForReturn(StringRef FunName) {
     if (const auto *D = findFnByName(FunName, AST->getASTContext()))
       if (auto EntityName = getEntityNameForReturn(D))
-        return Extractor.addEntity(*EntityName);
+        return Builder.addEntity(*EntityName);
     return std::nullopt;
   }
 
@@ -153,8 +185,8 @@ getSubsetOf(const EntityPointerLevelSet &Set, EntityId Entity) {
 }
 
 TEST_F(UnsafeBufferUsageTest, EntityPointerLevelComparison) {
-  EntityId E1 = Extractor.addEntity({"c:@F at foo", "", {}});
-  EntityId E2 = Extractor.addEntity({"c:@F at bar", "", {}});
+  EntityId E1 = Builder.addEntity({"c:@F at foo", "", {}});
+  EntityId E2 = Builder.addEntity({"c:@F at bar", "", {}});
 
   auto P1 = buildEntityPointerLevel(E1, 2);
   auto P2 = buildEntityPointerLevel(E1, 2);
@@ -172,9 +204,9 @@ TEST_F(UnsafeBufferUsageTest, EntityPointerLevelComparison) {
 }
 
 TEST_F(UnsafeBufferUsageTest, UnsafeBufferUsageEntityPointerLevelSetTest) {
-  EntityId E1 = Extractor.addEntity({"c:@F at foo", "", {}});
-  EntityId E2 = Extractor.addEntity({"c:@F at bar", "", {}});
-  EntityId E3 = Extractor.addEntity({"c:@F at baz", "", {}});
+  EntityId E1 = Builder.addEntity({"c:@F at foo", "", {}});
+  EntityId E2 = Builder.addEntity({"c:@F at bar", "", {}});
+  EntityId E3 = Builder.addEntity({"c:@F at baz", "", {}});
 
   auto P1 = buildEntityPointerLevel(E1, 1);
   auto P2 = buildEntityPointerLevel(E1, 2);
@@ -195,13 +227,14 @@ TEST_F(UnsafeBufferUsageTest, UnsafeBufferUsageEntityPointerLevelSetTest) {
 //////////////////////////////////////////////////////////////
 
 TEST_F(UnsafeBufferUsageTest, UnsafeBufferUsageSerializeTest) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int ***p, int ****q, int x) {
       p[5][5][5];
       q[5][5][5][5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
   ASSERT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U},
                                      {"p", 2U},
@@ -241,40 +274,43 @@ TEST_F(UnsafeBufferUsageTest, UnsafeBufferUsageSerializeTest) {
 //////////////////////////////////////////////////////////////
 
 TEST_F(UnsafeBufferUsageTest, SimpleFunctionWithUnsafePointer) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int *p) {
       p[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, PointerArithmetic) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int *p, int *q) {
       *(p + 5);
       *(q - 3);
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U}, {"q", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, PointerIncrementDecrement) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int *p, int *q, int *r, int *s) {
       (++p)[5];
       (q++)[5];
       (--r)[5];
       (s--)[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum,
@@ -282,40 +318,43 @@ TEST_F(UnsafeBufferUsageTest, PointerIncrementDecrement) {
 }
 
 TEST_F(UnsafeBufferUsageTest, PointerAssignment) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int *p, int *q) {
       (p = q + 5)[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U}, {"q", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, CompoundAssignment) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int *p, int *q) {
       (p += 5)[5];
       (q -= 3)[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U}, {"q", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, MultiLevelPointer) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int **p, int **q, int **r) {
       (*p)[5];
       *(*q);
       *(q[5]);
       r[5][5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum,
@@ -323,13 +362,14 @@ TEST_F(UnsafeBufferUsageTest, MultiLevelPointer) {
 }
 
 TEST_F(UnsafeBufferUsageTest, ConditionalOperator) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int **p, int **q, int cond) {
       (cond ? *p : *q)[5];
       cond ? p[5] : q[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum,
@@ -337,78 +377,84 @@ TEST_F(UnsafeBufferUsageTest, ConditionalOperator) {
 }
 
 TEST_F(UnsafeBufferUsageTest, CastExpression) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(void *p, int q) {
       ((int*)p)[5];
       ((int*)q)[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, CommaOperator) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int *p, int x) {
       (x++, p)[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, CommaOperator2) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int **p, int **q, int x) {
       (p[x] = 0, q[x] = 0)[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U}, {"q", 1U}, {"q", 2U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, ParenthesizedExpression) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int *p) {
       (((p)))[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, ArrayParameter) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int arr[], int arr2[][10]) {
       int n = 5;
       arr[100];
       arr2[5][n];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"arr", 1U}, {"arr2", 1U}, {"arr2", 2U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, FunctionCall) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     int ** (*fp)();
     int ** foo() {
       fp = &foo;
       foo()[5];
       (*fp())[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   // No (foo, 2) becasue indirect calls are ignored.
@@ -416,7 +462,7 @@ TEST_F(UnsafeBufferUsageTest, FunctionCall) {
 }
 
 TEST_F(UnsafeBufferUsageTest, StructMemberAccess) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     struct S {
       int *ptr;
       int (*ptr_to_arr)[10];
@@ -426,206 +472,215 @@ TEST_F(UnsafeBufferUsageTest, StructMemberAccess) {
       obj.ptr[5];
       (*obj.ptr_to_arr)[n];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"ptr", 1U}, {"ptr_to_arr", 2U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, StringLiteralSubscript) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo() {
       "hello"[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
-  EXPECT_NE(Sum, nullptr);
   // String literals should not generate pointer kind variables
-  EXPECT_EQ(*Sum, makeSet(__LINE__, {}));
+  EXPECT_EQ(Sum, nullptr);
 }
 
 TEST_F(UnsafeBufferUsageTest, OpaqueValueExpr) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int *p, int *q) {
        (p ?: q)[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U}, {"q", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, AddressOfOperator) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int x) {
       (&x)[5];
     }
-  )cpp",
-                       "foo");
-
-  EXPECT_NE(Sum, nullptr);
-  // Address-of should not generate pointer kind variables for 'x'
-  EXPECT_EQ(*Sum, makeSet(__LINE__, {}));
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
+  // Address-of should not generate pointer kind variables for 'x':
+  EXPECT_EQ(Sum, nullptr);
 }
 
 TEST_F(UnsafeBufferUsageTest, AddressOfThenDereference) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo(int *p, int *q) {
       (*(&p))[5];
       (&(*q))[5];
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1}, {"q", 1}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, PointerToArrayOfPointers) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     void foo() {
       int * arr[10];
-      int * (*p)[10] = arr;
+      int * (*p)[10] = &arr;
 
-      (*p)[5][5]; // '(*p)[5]' is unsafe 
+      (*p)[5][5]; // '(*p)[5]' is unsafe
                   // '(*p)' is fine because 5 < 10
     }
-  )cpp",
-                       "foo");
+  )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 3}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, UnsafePointerInGlobalVariableInitializer) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
       int *gp;
       int x = gp[5];
-    )cpp",
-                       {"x"});
+    )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("x");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"gp", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, UnsafePointerInFieldInitializer) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
       int *gp;
       struct Foo {
         int field = gp[5];
       };
-    )cpp",
-                       {"Foo"});
+    )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("Foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"gp", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, UnsafePointerInFieldInitializer2) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
       int *gp;
       union Foo {
         int field = gp[5];
         int x;
       };
-    )cpp",
-                       {"Foo"});
+    )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("Foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"gp", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, InitializerList) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
       int *gp;
       struct Foo {
         int field;
         int x;
       };
       Foo FooObj{gp[5], 0};
-    )cpp",
-                       {"FooObj"});
+    )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("FooObj");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"gp", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, UnsafePointerInCXXCtorInitializer) {
-  auto Sum = setUpTest<CXXConstructorDecl>(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
       struct Foo {
         int member;
         Foo(int *p) : member(p[5]) {}
       };
-    )cpp",
-                                           {"Foo"});
+    )cpp"),
+            true);
+  const auto *Sum = getEntitySummary<CXXConstructorDecl>("Foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, UnsafePointerInDefaultArg) {
-  auto Sum = setUpTest(R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     int * gp;
     void foo(int x = gp[5]);
-    )cpp",
-                       {"foo"});
+    )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"gp", 1U}}));
 }
 
 TEST_F(UnsafeBufferUsageTest, NestedDefinitions) {
-  StringRef Code = R"cpp(
+  ASSERT_EQ(setUpTest(R"cpp(
     int * a = [](){
       struct Foo {
         void bar(int * ptr) { ptr[3] = 0; }
       };
       return nullptr;
     }();
-    )cpp";
-  auto Sum = setUpTest(Code, {"bar"});
+    )cpp"),
+            true);
+  const auto *Sum = getEntitySummary("bar");
 
   EXPECT_NE(Sum, nullptr);
   // The closest contributor owns the fact:
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"ptr", 1U}}));
 
-  Sum = setUpTest(Code, {"Foo"});
+  Sum = getEntitySummary("Foo");
 
-  EXPECT_NE(Sum, nullptr);
-  EXPECT_TRUE(Sum->empty());
+  EXPECT_EQ(Sum, nullptr);
 
-  Sum = setUpTest(Code, {"a"});
+  Sum = getEntitySummary("a");
 
-  EXPECT_NE(Sum, nullptr);
-  EXPECT_TRUE(Sum->empty());
+  EXPECT_EQ(Sum, nullptr);
 }
 
 TEST_F(UnsafeBufferUsageTest, NestedDefinitions2) {
-  StringRef Code = R"cpp(
+  bool SetupSuccess = setUpTest(R"cpp(
     int main(void) {
        struct Foo {
           void bar(int * ptr) { ptr[3] = 0; }
        };
     }
-    )cpp";
-  auto Sum = setUpTest(Code, {"bar"});
+    )cpp");
+
+  ASSERT_EQ(SetupSuccess, true);
+
+  const auto *Sum = getEntitySummary("bar");
 
   EXPECT_NE(Sum, nullptr);
   // The closest contributor owns the fact:
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"ptr", 1U}}));
 
-  Sum = setUpTest(Code, {"Foo"});
+  Sum = getEntitySummary("Foo");
 
-  EXPECT_NE(Sum, nullptr);
-  EXPECT_TRUE(Sum->empty());
+  EXPECT_EQ(Sum, nullptr);
 
-  Sum = setUpTest(Code, {"main"});
+  Sum = getEntitySummary("main");
 
-  EXPECT_NE(Sum, nullptr);
-  EXPECT_TRUE(Sum->empty());
+  EXPECT_EQ(Sum, nullptr);
 }
 
 } // namespace

>From 9407fc4e97ff188dff2c76ba7bcc12fbe6dbf194 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 13 Apr 2026 17:45:15 -0700
Subject: [PATCH 09/25] [NFC][SSAF] Extract common code in Analyses to a shared
 file

Created SSAFAnalysesCommon.h for the SSAF analyses implementation.
---
 .../EntityPointerLevelFormat.h                | 12 -----
 .../EntityPointerLevel/EntityPointerLevel.cpp | 30 +++--------
 .../Analyses/SSAFAnalysesCommon.h             | 50 +++++++++++++++++++
 .../UnsafeBufferUsage/UnsafeBufferUsage.cpp   |  1 +
 .../UnsafeBufferUsageExtractor.cpp            | 12 +----
 5 files changed, 59 insertions(+), 46 deletions(-)
 create mode 100644 clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
index 4e7a9eff32d5c..7b125edb1fb7f 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h
@@ -12,18 +12,6 @@
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Serialization/JSONFormat.h"
 
-namespace {
-template <typename... Ts>
-llvm::Error makeSawButExpectedError(const llvm::json::Value &Saw,
-                                    llvm::StringRef Expected,
-                                    const Ts &...ExpectedArgs) {
-  std::string Fmt = ("saw %s but expected " + Expected).str();
-  std::string SawStr = llvm::formatv("{0:2}", Saw).str();
-
-  return llvm::createStringError(Fmt.c_str(), SawStr.c_str(), ExpectedArgs...);
-}
-} // namespace
-
 namespace clang::ssaf {
 llvm::json::Value
 entityPointerLevelToJSON(const EntityPointerLevel &EPL,
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
index 7e4200467ce9e..69bec9b19dae4 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
@@ -7,6 +7,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
+#include "SSAFAnalysesCommon.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/StmtVisitor.h"
@@ -18,25 +19,6 @@
 using namespace clang;
 using namespace ssaf;
 
-namespace {
-template <typename DeclOrExpr> bool hasPtrOrArrType(const DeclOrExpr *E) {
-  return llvm::isa<PointerType, ArrayType>(E->getType().getCanonicalType());
-}
-
-template <typename NodeTy, typename... Ts>
-llvm::Error makeErrAtNode(ASTContext &Ctx, const NodeTy &N, StringRef Fmt,
-                          const Ts &...Args) {
-  std::string LocStr = N.getBeginLoc().printToString(Ctx.getSourceManager());
-  return llvm::createStringError((Fmt + " at %s").str().c_str(), Args...,
-                                 LocStr.c_str());
-}
-
-llvm::Error makeEntityNameErr(ASTContext &Ctx, const NamedDecl &D) {
-  return makeErrAtNode(Ctx, D, "failed to create entity name for %s",
-                       D.getNameAsString().data());
-}
-} // namespace
-
 namespace clang::ssaf {
 // Translate a pointer type expression 'E' to a (set of) EntityPointerLevel(s)
 // associated with the declared type of the base address of `E`. If the base
@@ -64,7 +46,7 @@ class EntityPointerLevelTranslator
 
   // Fallback method for all unsupported expression kind:
   llvm::Error fallback(const Stmt *E) {
-    return makeErrAtNode(Ctx, *E,
+    return makeErrAtNode(Ctx, E,
                          "attempt to translate %s to EntityPointerLevels",
                          E->getStmtClassName());
   }
@@ -98,7 +80,7 @@ class EntityPointerLevelTranslator
   Expected<EntityPointerLevel> translate(const NamedDecl *D, bool IsRet) {
     if (IsRet && !isa<FunctionDecl>(D))
       return makeErrAtNode(
-          Ctx, *D,
+          Ctx, D,
           "attempt to call getEntityNameForReturn on a NamedDecl of %s kind",
           D->getDeclKindName());
 
@@ -107,7 +89,7 @@ class EntityPointerLevelTranslator
               : getEntityName(D);
     if (EN)
       return createEntityPointerLevelFor(*EN);
-    return makeEntityNameErr(Ctx, *D);
+    return makeEntityNameErr(Ctx, D);
   }
 
   static EntityPointerLevel incrementPointerLevel(const EntityPointerLevel &E) {
@@ -230,14 +212,14 @@ class EntityPointerLevelTranslator
   Expected<EntityPointerLevelSet> VisitDeclRefExpr(const DeclRefExpr *E) {
     if (auto EntityName = getEntityName(E->getDecl()))
       return EntityPointerLevelSet{createEntityPointerLevelFor(*EntityName)};
-    return makeEntityNameErr(Ctx, *E->getDecl());
+    return makeEntityNameErr(Ctx, E->getDecl());
   }
 
   // Translate({., ->}f) -> {(MemberDecl, 1)}
   Expected<EntityPointerLevelSet> VisitMemberExpr(const MemberExpr *E) {
     if (auto EntityName = getEntityName(E->getMemberDecl()))
       return EntityPointerLevelSet{createEntityPointerLevelFor(*EntityName)};
-    return makeEntityNameErr(Ctx, *E->getMemberDecl());
+    return makeEntityNameErr(Ctx, E->getMemberDecl());
   }
 
   Expected<EntityPointerLevelSet>
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
new file mode 100644
index 0000000000000..c14e2a98751d2
--- /dev/null
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
@@ -0,0 +1,50 @@
+//===- SSAFAnalysesCommon.h -------------------------------------*- 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
+//
+//===----------------------------------------------------------------------===//
+//
+//  Common code in SSAF analyses implementations
+//
+//===----------------------------------------------------------------------===//
+#ifndef LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_SSAFANALYSESCOMMON_H
+#define LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_SSAFANALYSESCOMMON_H
+
+#include "clang/AST/Decl.h"
+#include "clang/AST/DeclObjC.h"
+#include "clang/AST/DynamicRecursiveASTVisitor.h"
+#include "llvm/ADT/Twine.h"
+#include "llvm/Support/JSON.h"
+
+using namespace clang;
+
+template <typename NodeTy, typename... Ts>
+llvm::Error makeErrAtNode(ASTContext &Ctx, const NodeTy *N, StringRef Fmt,
+                          const Ts &...Args) {
+  std::string LocStr = N->getBeginLoc().printToString(Ctx.getSourceManager());
+  return llvm::createStringError((Fmt + " at %s").str().c_str(), Args...,
+                                 LocStr.c_str());
+}
+
+template <typename... Ts>
+llvm::Error makeSawButExpectedError(const llvm::json::Value &Saw,
+                                    llvm::StringRef Expected,
+                                    const Ts &...ExpectedArgs) {
+  std::string Fmt = ("saw %s but expected " + Expected).str();
+  std::string SawStr = llvm::formatv("{0:2}", Saw).str();
+
+  return llvm::createStringError(Fmt.c_str(), SawStr.c_str(), ExpectedArgs...);
+}
+
+template <typename DeclOrExpr> bool hasPtrOrArrType(const DeclOrExpr *E) {
+  return llvm::isa<PointerType, ArrayType>(E->getType().getCanonicalType());
+}
+
+inline llvm::Error makeEntityNameErr(ASTContext &Ctx, const NamedDecl *D) {
+  return makeErrAtNode(Ctx, D, "failed to create entity name for %s",
+                       D->getNameAsString().data());
+}
+
+#endif // LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_SSAFANALYSESCOMMON_H
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp
index 47e03476d1063..ea5d2297b9836 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.cpp
@@ -7,6 +7,7 @@
 //===----------------------------------------------------------------------===//
 
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h"
+#include "SSAFAnalysesCommon.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevelFormat.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.h"
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
index 72944bd0be323..f79bc5c8574d6 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
@@ -6,6 +6,7 @@
 //
 //===----------------------------------------------------------------------===//
 
+#include "SSAFAnalysesCommon.h"
 #include "clang/AST/ASTConsumer.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
@@ -26,15 +27,6 @@ namespace {
 using namespace clang;
 using namespace ssaf;
 
-llvm::Error makeCreateEntityNameError(const NamedDecl *FailedDecl,
-                                      ASTContext &Ctx) {
-  std::string LocStr = FailedDecl->getSourceRange().getBegin().printToString(
-      Ctx.getSourceManager());
-  return llvm::createStringError(
-      "failed to create entity name for %s declared at %s",
-      FailedDecl->getNameAsString().c_str(), LocStr.c_str());
-}
-
 Expected<EntityPointerLevelSet>
 buildEntityPointerLevels(std::set<const Expr *> &&UnsafePointers,
                          ASTContext &Ctx,
@@ -140,7 +132,7 @@ class clang::ssaf::UnsafeBufferUsageTUSummaryExtractor
       auto ContributorName = getEntityName(CD);
 
       if (!ContributorName)
-        llvm::reportFatalInternalError(makeCreateEntityNameError(CD, Ctx));
+        llvm::reportFatalInternalError(makeEntityNameErr(Ctx, CD));
 
       auto [Ignored, InsertionSucceeded] = SummaryBuilder.addSummary(
           addEntity(*ContributorName), std::move(*EntitySummary));

>From f4ab72cbf0ac61161b32f39c60766215c636da6a Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 13 Apr 2026 19:16:38 -0700
Subject: [PATCH 10/25] [SSAF][Analyses] Add an AST visitor for the
 contribution model

Add an AST visitor that respects the contribution model and will be
shared across SSAF analyses.
---
 .../EntityPointerLevel/EntityPointerLevel.h   |  11 +-
 .../Analyses/CMakeLists.txt                   |   3 +-
 .../Analyses/SSAFAnalysesCommon.cpp           | 106 ++++++++++++++++++
 .../Analyses/SSAFAnalysesCommon.h             |  12 ++
 .../UnsafeBufferUsageExtractor.cpp            | 104 +++++++----------
 5 files changed, 165 insertions(+), 71 deletions(-)
 create mode 100644 clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
index ed8400f65e310..0e120a40eebb8 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
@@ -22,9 +22,9 @@ namespace clang::ssaf {
 /// declared type, a EntityPointerLevel is associated with a '*' (or a '[]`) in
 /// that declaration.
 ///
-/// For example, for 'int *p[10];', there are two EntityPointerLevels. One
-/// is associated with 'int *[10]' of 'p' and the other is associated with 'int
-/// *' of 'p'.
+/// For example, for 'int *p[10];', there are two EntityPointerLevels.
+/// One is associated with 'int *[10]' of 'p' and the other is associated with
+/// 'int *' of 'p'.
 ///
 /// An EntityPointerLevel can be identified by an EntityId and an unsigned
 /// integer indicating the pointer level: '(EntityId, PointerLevel)'.
@@ -34,7 +34,7 @@ namespace clang::ssaf {
 /// For the same example 'int *p[10];', the EntityPointerLevels below are valid:
 /// - '(p, 2)' is associated with the 'int *' part of the declared type of 'p';
 /// - '(p, 1)' is associated with the 'int *[10]' part of the declared type of
-/// 'p'.
+///   'p'.
 class EntityPointerLevel {
   EntityId Entity;
   unsigned PointerLevel;
@@ -97,6 +97,8 @@ llvm::Expected<EntityPointerLevelSet> translateEntityPointerLevel(
     const Expr *E, ASTContext &Ctx,
     llvm::function_ref<EntityId(EntityName EN)> AddEntity);
 
+/// Creates a `EntityPointerLevel` from a pair of an EntityId and a pointer
+/// level:
 EntityPointerLevel buildEntityPointerLevel(EntityId, unsigned);
 
 /// Create an EntityPointerLevel (EPL) from a NamedDecl of a pointer/array type.
@@ -117,4 +119,5 @@ creatEntityPointerLevel(const NamedDecl *ND,
 /// of `E`'s associated pointer/array tyoe of the same entity.
 EntityPointerLevel incrementPointerLevel(const EntityPointerLevel &E);
 } // namespace clang::ssaf
+
 #endif // LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_ENTITYPOINTERLEVEL_ENTITYPOINTERLEVEL_H
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt b/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt
index c15ff3b3c42e7..88dcef0c5a2fa 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt
@@ -2,10 +2,11 @@ set(LLVM_LINK_COMPONENTS
   Support
   )
 
-add_clang_library(clangScalableStaticAnalysisFrameworkAnalyses 
+add_clang_library(clangScalableStaticAnalysisFrameworkAnalyses
   CallGraph/CallGraphExtractor.cpp
   CallGraph/CallGraphJSONFormat.cpp
   EntityPointerLevel/EntityPointerLevel.cpp
+  SSAFAnalysesCommon.cpp
   UnsafeBufferUsage/UnsafeBufferUsage.cpp
   UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
 
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
new file mode 100644
index 0000000000000..31962bdee7f92
--- /dev/null
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
@@ -0,0 +1,106 @@
+//===- SSAFAnalysesCommon.cpp ---------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "SSAFAnalysesCommon.h"
+
+namespace {
+// Traverses the AST and finds contributors.
+class ContributorFinder : public DynamicRecursiveASTVisitor {
+public:
+  std::vector<const NamedDecl *> Contributors;
+
+  bool VisitFunctionDecl(FunctionDecl *D) override {
+    Contributors.push_back(D);
+    return true;
+  }
+
+  bool VisitRecordDecl(RecordDecl *D) override {
+    Contributors.push_back(D);
+    return true;
+  }
+
+  bool VisitVarDecl(VarDecl *D) override {
+    DeclContext *DC = D->getDeclContext();
+
+    if (DC->isFileContext() || DC->isNamespace())
+      Contributors.push_back(D);
+    return true;
+  }
+};
+
+// An AST visitor that skips the root node's strict-descendants that are
+// callable Decls and record Decls, because those are separate contributors.
+//
+// Clients need to implement their own `MatchAction`, which is a function that
+// takes a `DynTypedNode`, decides if it matches and performs any further
+// callback actions.
+class ContributorFactFinder : public DynamicRecursiveASTVisitor {
+  llvm::function_ref<void(const DynTypedNode &)> MatchAction;
+  const NamedDecl *RootDecl = nullptr;
+
+  template <typename NodeTy> void match(const NodeTy &Node) {
+    MatchAction(DynTypedNode::create(Node));
+  }
+
+public:
+  ContributorFactFinder(
+      llvm::function_ref<void(const DynTypedNode &)> MatchAction)
+      : MatchAction(MatchAction) {
+    ShouldVisitTemplateInstantiations = true;
+    ShouldVisitImplicitCode = false;
+  }
+
+  // The entry point:
+  void findMatches(const NamedDecl *Contributor) {
+    RootDecl = Contributor;
+    TraverseDecl(const_cast<NamedDecl *>(Contributor));
+  }
+
+  bool TraverseDecl(Decl *Node) override {
+    if (!Node)
+      return true;
+    // To skip callables:
+    if (Node != RootDecl && isa<FunctionDecl, CXXConstructorDecl, BlockDecl,
+                                ObjCMethodDecl, RecordDecl>(Node))
+      return true;
+    match(*Node);
+    return DynamicRecursiveASTVisitor::TraverseDecl(Node);
+  }
+
+  bool TraverseStmt(Stmt *Node) override {
+    if (!Node)
+      return true;
+    match(*Node);
+    return DynamicRecursiveASTVisitor::TraverseStmt(Node);
+  }
+
+  bool TraverseLambdaExpr(LambdaExpr *L) override {
+    // TODO: lambda captures of pointer variables (by copy or by reference)
+    // are currently not tracked. Each capture initializes an implicit closure
+    // field from the captured variable, which constitutes a pointer assignment
+    // edge that should be recorded here.
+    return true; // Skip lambda as it is a callable.
+  }
+};
+} // namespace
+
+namespace clang::ssaf {
+
+void findContributors(ASTContext &Ctx,
+                      std::vector<const NamedDecl *> &Contributors) {
+  ContributorFinder Finder;
+  Finder.TraverseAST(Ctx);
+  Contributors = std::move(Finder.Contributors);
+}
+
+void findMatchesIn(const NamedDecl *Contributor,
+                   llvm::function_ref<void(const DynTypedNode &)> MatchAction) {
+  ContributorFactFinder{MatchAction}.findMatches(Contributor);
+}
+
+} // namespace clang::ssaf
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
index c14e2a98751d2..b47f03421a6cf 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
@@ -12,6 +12,7 @@
 #ifndef LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_SSAFANALYSESCOMMON_H
 #define LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_SSAFANALYSESCOMMON_H
 
+#include "clang/AST/ASTTypeTraits.h"
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
@@ -47,4 +48,15 @@ inline llvm::Error makeEntityNameErr(ASTContext &Ctx, const NamedDecl *D) {
                        D->getNameAsString().data());
 }
 
+namespace clang::ssaf {
+
+/// Find all contributors in an AST.
+void findContributors(ASTContext &Ctx,
+                      std::vector<const NamedDecl *> &Contributors);
+/// Perform `MatchAction` on each Stmt and Decl belonging to the `Contributor`.
+void findMatchesIn(const NamedDecl *Contributor,
+                   llvm::function_ref<void(const DynTypedNode &)> MatchAction);
+
+} // namespace clang::ssaf
+
 #endif // LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_SSAFANALYSESCOMMON_H
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
index f79bc5c8574d6..d8b8829a19106 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
@@ -21,41 +21,17 @@
 #include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/TUSummaryExtractor.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Error.h"
-#include <memory>
+#include "llvm/Support/ErrorHandling.h"
 
-namespace {
 using namespace clang;
 using namespace ssaf;
 
-Expected<EntityPointerLevelSet>
-buildEntityPointerLevels(std::set<const Expr *> &&UnsafePointers,
-                         ASTContext &Ctx,
-                         std::function<EntityId(EntityName)> AddEntity) {
-  EntityPointerLevelSet Result{};
-  llvm::Error AllErrors = llvm::ErrorSuccess();
-
-  for (const Expr *Ptr : UnsafePointers) {
-    Expected<EntityPointerLevelSet> Translation =
-        translateEntityPointerLevel(Ptr, Ctx, AddEntity);
-
-    if (Translation) {
-      // Filter out those temporary invalid EntityPointerLevels associated with
-      // `&E` pointers:
-      auto FilteredTranslation = llvm::make_filter_range(
-          *Translation, [](const EntityPointerLevel &E) -> bool {
-            return E.getPointerLevel() > 0;
-          });
-      Result.insert(FilteredTranslation.begin(), FilteredTranslation.end());
-      continue;
-    }
-    AllErrors = llvm::joinErrors(std::move(AllErrors), Translation.takeError());
-  }
-  if (AllErrors)
-    return AllErrors;
-  return Result;
-}
+static std::set<const Expr *>
+findUnsafePointersInContributor(const DynTypedNode &Node) {
+  const Decl *D = Node.get<Decl>();
 
-static std::set<const Expr *> findUnsafePointersInContributor(const Decl *D) {
+  if (!D)
+    return {};
   if (isa<FunctionDecl>(D) || isa<VarDecl>(D))
     return findUnsafePointers(D);
   if (auto *RD = dyn_cast<RecordDecl>(D)) {
@@ -68,7 +44,6 @@ static std::set<const Expr *> findUnsafePointersInContributor(const Decl *D) {
   }
   return {};
 }
-} // namespace
 
 class clang::ssaf::UnsafeBufferUsageTUSummaryExtractor
     : public TUSummaryExtractor {
@@ -79,48 +54,45 @@ class clang::ssaf::UnsafeBufferUsageTUSummaryExtractor
   EntityId addEntity(EntityName EN) { return SummaryBuilder.addEntity(EN); }
 
   Expected<std::unique_ptr<UnsafeBufferUsageEntitySummary>>
-  extractEntitySummary(const Decl *Contributor, ASTContext &Ctx) {
-    auto AddEntity = [this](EntityName EN) { return addEntity(EN); };
-    Expected<EntityPointerLevelSet> EPLs = buildEntityPointerLevels(
-        findUnsafePointersInContributor(Contributor), Ctx, AddEntity);
-
-    if (EPLs)
-      return std::make_unique<UnsafeBufferUsageEntitySummary>(
-          UnsafeBufferUsageEntitySummary(std::move(*EPLs)));
-    return EPLs.takeError();
-  }
+  extractEntitySummary(const NamedDecl *Contributor, ASTContext &Ctx) {
+    std::set<const Expr *> UnsafePointers;
 
-  void HandleTranslationUnit(ASTContext &Ctx) override {
+    auto MatchAction = [&UnsafePointers](const DynTypedNode &Node) {
+      auto Result = findUnsafePointersInContributor(Node);
+      UnsafePointers.insert(Result.begin(), Result.end());
+    };
+    findMatchesIn(Contributor, MatchAction);
 
-    // FIXME: I suppose finding contributor Decls is commonly needed by all/many
-    // extractors
-    class ContributorFinder : public DynamicRecursiveASTVisitor {
-    public:
-      std::vector<const NamedDecl *> Contributors;
+    EntityPointerLevelSet Results;
 
-      bool VisitFunctionDecl(FunctionDecl *D) override {
-        Contributors.push_back(D);
-        return true;
-      }
+    for (const Expr *Ptr : UnsafePointers) {
+      Expected<EntityPointerLevelSet> Translation =
+          translateEntityPointerLevel(Ptr, Ctx, [this](const EntityName &EN) {
+            return SummaryBuilder.addEntity(EN);
+          });
 
-      bool VisitRecordDecl(RecordDecl *D) override {
-        Contributors.push_back(D);
-        return true;
+      if (Translation) {
+        // Filter out those temporary invalid EntityPointerLevels associated
+        // with `&E` pointers. They need no transformation of entities:
+        auto FilteredTranslation = llvm::make_filter_range(
+            *Translation, [](const EntityPointerLevel &E) -> bool {
+              return E.getPointerLevel() > 0;
+            });
+        Results.insert(FilteredTranslation.begin(), FilteredTranslation.end());
+        continue;
       }
+      return Translation.takeError();
+    }
 
-      bool VisitVarDecl(VarDecl *D) override {
-        DeclContext *DC = D->getDeclContext();
-
-        if (DC->isFileContext() || DC->isNamespace())
-          Contributors.push_back(D);
-        return true;
-      }
-    } ContributorFinder;
+    return std::make_unique<UnsafeBufferUsageEntitySummary>(
+        UnsafeBufferUsageEntitySummary(std::move(Results)));
+  }
 
-    ContributorFinder.VisitTranslationUnitDecl(Ctx.getTranslationUnitDecl());
+  void HandleTranslationUnit(ASTContext &Ctx) override {
+    std::vector<const NamedDecl *> Contributors;
 
-    ContributorFinder.TraverseAST(Ctx);
-    for (auto *CD : ContributorFinder.Contributors) {
+    findContributors(Ctx, Contributors);
+    for (auto *CD : Contributors) {
       auto EntitySummary = extractEntitySummary(CD, Ctx);
 
       if (!EntitySummary)
@@ -148,4 +120,4 @@ volatile int UnsafeBufferUsageTUSummaryExtractorAnchorSource = 0;
 static clang::ssaf::TUSummaryExtractorRegistry::Add<
     ssaf::UnsafeBufferUsageTUSummaryExtractor>
     RegisterExtractor(UnsafeBufferUsageEntitySummary::Name,
-                      "The TUSummaryExtractor for unsafe buffer pointers");
\ No newline at end of file
+                      "The TUSummaryExtractor for unsafe buffer pointers");

>From f4ab5e00ea532531a9b3fc3bc3b71966bd6533e5 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Wed, 15 Apr 2026 11:06:18 -0700
Subject: [PATCH 11/25] clean up code

---
 .../EntityPointerLevel/EntityPointerLevel.h   |   2 +-
 .../SSAFBuiltinForceLinker.h                  |   4 +
 .../EntityPointerLevel/EntityPointerLevel.cpp |   2 +-
 .../UnsafeBufferUsageExtractor.cpp            | 106 +++++++++---------
 .../UnsafeBufferUsageTest.cpp                 |   3 +-
 5 files changed, 63 insertions(+), 54 deletions(-)

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
index ed8400f65e310..506b81170f757 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
@@ -107,7 +107,7 @@ EntityPointerLevel buildEntityPointerLevel(EntityId, unsigned);
 /// \param IsFunRet true iff the created EPL is associated with the return type
 /// of a function entity.
 llvm::Expected<EntityPointerLevel>
-creatEntityPointerLevel(const NamedDecl *ND,
+createEntityPointerLevel(const NamedDecl *ND,
                         llvm::function_ref<EntityId(EntityName EN)> AddEntity,
                         bool IsFunRet = false);
 
diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/SSAFBuiltinForceLinker.h b/clang/include/clang/ScalableStaticAnalysisFramework/SSAFBuiltinForceLinker.h
index 916ef1ce783c4..5616976e10f77 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/SSAFBuiltinForceLinker.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/SSAFBuiltinForceLinker.h
@@ -32,10 +32,14 @@ extern volatile int SSAFAnalysisRegistryAnchorSource;
 [[maybe_unused]] static int SSAFAnalysisRegistryAnchorDestination =
     SSAFAnalysisRegistryAnchorSource;
 
+// This anchor is used to force the linker to link the UnsafeBufferUsage
+// JSON format.
 extern volatile int UnsafeBufferUsageSSAFJSONFormatAnchorSource;
 [[maybe_unused]] static int UnsafeBufferUsageSSAFJSONFormatAnchorDestination =
     UnsafeBufferUsageSSAFJSONFormatAnchorSource;
 
+// This anchor is used to force the linker to link the
+// UnsafeBufferUsageTUSummaryExtractor.
 extern volatile int UnsafeBufferUsageTUSummaryExtractorAnchorSource;
 [[maybe_unused]] static int
     UnsafeBufferUsageTUSummaryExtractorAnchorDestination =
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
index 7e4200467ce9e..dee8cf3465c1e 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
@@ -256,7 +256,7 @@ Expected<EntityPointerLevelSet> clang::ssaf::translateEntityPointerLevel(
 }
 
 /// Create an EntityPointerLevel from a ValueDecl of a pointer type.
-Expected<EntityPointerLevel> clang::ssaf::creatEntityPointerLevel(
+Expected<EntityPointerLevel> clang::ssaf::createEntityPointerLevel(
     const NamedDecl *ND, llvm::function_ref<EntityId(EntityName EN)> AddEntity,
     bool IsFunRet) {
   EntityPointerLevelTranslator Translator(AddEntity, ND->getASTContext());
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
index 72944bd0be323..712c2d39e3695 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
@@ -78,8 +78,8 @@ static std::set<const Expr *> findUnsafePointersInContributor(const Decl *D) {
 }
 } // namespace
 
-class clang::ssaf::UnsafeBufferUsageTUSummaryExtractor
-    : public TUSummaryExtractor {
+namespace clang::ssaf {
+class UnsafeBufferUsageTUSummaryExtractor : public TUSummaryExtractor {
 public:
   UnsafeBufferUsageTUSummaryExtractor(TUSummaryBuilder &Builder)
       : TUSummaryExtractor(Builder) {}
@@ -87,68 +87,74 @@ class clang::ssaf::UnsafeBufferUsageTUSummaryExtractor
   EntityId addEntity(EntityName EN) { return SummaryBuilder.addEntity(EN); }
 
   Expected<std::unique_ptr<UnsafeBufferUsageEntitySummary>>
-  extractEntitySummary(const Decl *Contributor, ASTContext &Ctx) {
-    auto AddEntity = [this](EntityName EN) { return addEntity(EN); };
-    Expected<EntityPointerLevelSet> EPLs = buildEntityPointerLevels(
-        findUnsafePointersInContributor(Contributor), Ctx, AddEntity);
-
-    if (EPLs)
-      return std::make_unique<UnsafeBufferUsageEntitySummary>(
-          UnsafeBufferUsageEntitySummary(std::move(*EPLs)));
-    return EPLs.takeError();
-  }
+  extractEntitySummary(const Decl *Contributor, ASTContext &Ctx);
 
-  void HandleTranslationUnit(ASTContext &Ctx) override {
+  void HandleTranslationUnit(ASTContext &Ctx) override;
+};
+} // namespace clang::ssaf
+
+Expected<std::unique_ptr<UnsafeBufferUsageEntitySummary>>
+clang::ssaf::UnsafeBufferUsageTUSummaryExtractor::extractEntitySummary(
+    const Decl *Contributor, ASTContext &Ctx) {
+  auto AddEntity = [this](EntityName EN) { return addEntity(EN); };
+  Expected<EntityPointerLevelSet> EPLs = buildEntityPointerLevels(
+      findUnsafePointersInContributor(Contributor), Ctx, AddEntity);
+
+  if (EPLs)
+    return std::make_unique<UnsafeBufferUsageEntitySummary>(
+        UnsafeBufferUsageEntitySummary(std::move(*EPLs)));
+  return EPLs.takeError();
+}
 
-    // FIXME: I suppose finding contributor Decls is commonly needed by all/many
-    // extractors
-    class ContributorFinder : public DynamicRecursiveASTVisitor {
-    public:
-      std::vector<const NamedDecl *> Contributors;
+void clang::ssaf::UnsafeBufferUsageTUSummaryExtractor::HandleTranslationUnit(
+    ASTContext &Ctx) {
 
-      bool VisitFunctionDecl(FunctionDecl *D) override {
-        Contributors.push_back(D);
-        return true;
-      }
+  // FIXME: I suppose finding contributor Decls is commonly needed by all/many
+  // extractors
+  class ContributorFinder : public DynamicRecursiveASTVisitor {
+  public:
+    std::vector<const NamedDecl *> Contributors;
 
-      bool VisitRecordDecl(RecordDecl *D) override {
-        Contributors.push_back(D);
-        return true;
-      }
+    bool VisitFunctionDecl(FunctionDecl *D) override {
+      Contributors.push_back(D);
+      return true;
+    }
 
-      bool VisitVarDecl(VarDecl *D) override {
-        DeclContext *DC = D->getDeclContext();
+    bool VisitRecordDecl(RecordDecl *D) override {
+      Contributors.push_back(D);
+      return true;
+    }
 
-        if (DC->isFileContext() || DC->isNamespace())
-          Contributors.push_back(D);
-        return true;
-      }
-    } ContributorFinder;
+    bool VisitVarDecl(VarDecl *D) override {
+      DeclContext *DC = D->getDeclContext();
 
-    ContributorFinder.VisitTranslationUnitDecl(Ctx.getTranslationUnitDecl());
+      if (DC->isFileContext() || DC->isNamespace())
+        Contributors.push_back(D);
+      return true;
+    }
+  } ContributorFinder;
 
-    ContributorFinder.TraverseAST(Ctx);
-    for (auto *CD : ContributorFinder.Contributors) {
-      auto EntitySummary = extractEntitySummary(CD, Ctx);
+  ContributorFinder.TraverseAST(Ctx);
+  for (auto *CD : ContributorFinder.Contributors) {
+    auto EntitySummary = extractEntitySummary(CD, Ctx);
 
-      if (!EntitySummary)
-        llvm::reportFatalInternalError(EntitySummary.takeError());
-      assert(*EntitySummary);
-      if ((*EntitySummary)->empty())
-        continue;
+    if (!EntitySummary)
+      llvm::reportFatalInternalError(EntitySummary.takeError());
+    assert(*EntitySummary);
+    if ((*EntitySummary)->empty())
+      continue;
 
-      auto ContributorName = getEntityName(CD);
+    auto ContributorName = getEntityName(CD);
 
-      if (!ContributorName)
-        llvm::reportFatalInternalError(makeCreateEntityNameError(CD, Ctx));
+    if (!ContributorName)
+      llvm::reportFatalInternalError(makeCreateEntityNameError(CD, Ctx));
 
-      auto [Ignored, InsertionSucceeded] = SummaryBuilder.addSummary(
-          addEntity(*ContributorName), std::move(*EntitySummary));
+    auto [Ignored, InsertionSucceeded] = SummaryBuilder.addSummary(
+        addEntity(*ContributorName), std::move(*EntitySummary));
 
-      assert(InsertionSucceeded && "duplicated contributor extraction");
-    }
+    assert(InsertionSucceeded && "duplicated contributor extraction");
   }
-};
+}
 
 // NOLINTNEXTLINE(misc-use-internal-linkage)
 volatile int UnsafeBufferUsageTUSummaryExtractorAnchorSource = 0;
diff --git a/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp b/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
index 59c2cd38ffacf..11c3e4e01c5bc 100644
--- a/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
+++ b/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
@@ -11,7 +11,6 @@
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
-#include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/ASTEntityMapping.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityId.h"
@@ -457,7 +456,7 @@ TEST_F(UnsafeBufferUsageTest, FunctionCall) {
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
-  // No (foo, 2) becasue indirect calls are ignored.
+  // No (foo, 2) because indirect calls are ignored.
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"foo", 1U, true}}));
 }
 

>From 21b98e0e8a504087a4c8185ac7653084c56b51db Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Wed, 15 Apr 2026 11:37:39 -0700
Subject: [PATCH 12/25] clean up

---
 .../EntityPointerLevel/EntityPointerLevel.h       |  2 +-
 .../EntityPointerLevel/EntityPointerLevel.cpp     | 10 +++++-----
 .../Analyses/SSAFAnalysesCommon.h                 | 15 ++++++---------
 .../UnsafeBufferUsageExtractor.cpp                |  2 --
 4 files changed, 12 insertions(+), 17 deletions(-)

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
index ed8400f65e310..506b81170f757 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
@@ -107,7 +107,7 @@ EntityPointerLevel buildEntityPointerLevel(EntityId, unsigned);
 /// \param IsFunRet true iff the created EPL is associated with the return type
 /// of a function entity.
 llvm::Expected<EntityPointerLevel>
-creatEntityPointerLevel(const NamedDecl *ND,
+createEntityPointerLevel(const NamedDecl *ND,
                         llvm::function_ref<EntityId(EntityName EN)> AddEntity,
                         bool IsFunRet = false);
 
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
index 69bec9b19dae4..68a452ee61b43 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
@@ -68,12 +68,12 @@ class EntityPointerLevelTranslator
     return EntityPointerLevelSet{Incremented.begin(), Incremented.end()};
   }
 
-  std::function<EntityId(EntityName EN)> AddEntity;
+  llvm::function_ref<EntityId(EntityName EN)> AddEntity;
   ASTContext &Ctx;
 
 public:
-  EntityPointerLevelTranslator(std::function<EntityId(EntityName EN)> AddEntity,
-                               ASTContext &Ctx)
+  EntityPointerLevelTranslator(
+      llvm::function_ref<EntityId(EntityName EN)> AddEntity, ASTContext &Ctx)
       : AddEntity(AddEntity), Ctx(Ctx) {}
 
   Expected<EntityPointerLevelSet> translate(const Expr *E) { return Visit(E); }
@@ -156,7 +156,7 @@ class EntityPointerLevelTranslator
     }
   }
 
-  // Translate((T*)base) -> Translate(p) if p has pointer type
+  // Translate((T*)base) -> Translate(base) if base has pointer type
   //                     -> {} otherwise
   Expected<EntityPointerLevelSet> VisitCastExpr(const CastExpr *E) {
     if (hasPtrOrArrType(E->getSubExpr()))
@@ -238,7 +238,7 @@ Expected<EntityPointerLevelSet> clang::ssaf::translateEntityPointerLevel(
 }
 
 /// Create an EntityPointerLevel from a ValueDecl of a pointer type.
-Expected<EntityPointerLevel> clang::ssaf::creatEntityPointerLevel(
+Expected<EntityPointerLevel> clang::ssaf::createEntityPointerLevel(
     const NamedDecl *ND, llvm::function_ref<EntityId(EntityName EN)> AddEntity,
     bool IsFunRet) {
   EntityPointerLevelTranslator Translator(AddEntity, ND->getASTContext());
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
index c14e2a98751d2..bce1129891df0 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
@@ -13,16 +13,11 @@
 #define LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_SSAFANALYSESCOMMON_H
 
 #include "clang/AST/Decl.h"
-#include "clang/AST/DeclObjC.h"
-#include "clang/AST/DynamicRecursiveASTVisitor.h"
-#include "llvm/ADT/Twine.h"
 #include "llvm/Support/JSON.h"
 
-using namespace clang;
-
 template <typename NodeTy, typename... Ts>
-llvm::Error makeErrAtNode(ASTContext &Ctx, const NodeTy *N, StringRef Fmt,
-                          const Ts &...Args) {
+llvm::Error makeErrAtNode(clang::ASTContext &Ctx, const NodeTy *N,
+                          llvm::StringRef Fmt, const Ts &...Args) {
   std::string LocStr = N->getBeginLoc().printToString(Ctx.getSourceManager());
   return llvm::createStringError((Fmt + " at %s").str().c_str(), Args...,
                                  LocStr.c_str());
@@ -39,10 +34,12 @@ llvm::Error makeSawButExpectedError(const llvm::json::Value &Saw,
 }
 
 template <typename DeclOrExpr> bool hasPtrOrArrType(const DeclOrExpr *E) {
-  return llvm::isa<PointerType, ArrayType>(E->getType().getCanonicalType());
+  return llvm::isa<clang::PointerType, clang::ArrayType>(
+      E->getType().getCanonicalType());
 }
 
-inline llvm::Error makeEntityNameErr(ASTContext &Ctx, const NamedDecl *D) {
+inline llvm::Error makeEntityNameErr(clang::ASTContext &Ctx,
+                                     const clang::NamedDecl *D) {
   return makeErrAtNode(Ctx, D, "failed to create entity name for %s",
                        D->getNameAsString().data());
 }
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
index f79bc5c8574d6..df313aa8a5c25 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
@@ -117,8 +117,6 @@ class clang::ssaf::UnsafeBufferUsageTUSummaryExtractor
       }
     } ContributorFinder;
 
-    ContributorFinder.VisitTranslationUnitDecl(Ctx.getTranslationUnitDecl());
-
     ContributorFinder.TraverseAST(Ctx);
     for (auto *CD : ContributorFinder.Contributors) {
       auto EntitySummary = extractEntitySummary(CD, Ctx);

>From ef430c6cb4a6c325fce9d2919b873b57960bbdf2 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Wed, 15 Apr 2026 11:41:01 -0700
Subject: [PATCH 13/25] fix format

---
 .../Analyses/EntityPointerLevel/EntityPointerLevel.h          | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
index 506b81170f757..9d517097966f0 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
@@ -108,8 +108,8 @@ EntityPointerLevel buildEntityPointerLevel(EntityId, unsigned);
 /// of a function entity.
 llvm::Expected<EntityPointerLevel>
 createEntityPointerLevel(const NamedDecl *ND,
-                        llvm::function_ref<EntityId(EntityName EN)> AddEntity,
-                        bool IsFunRet = false);
+                         llvm::function_ref<EntityId(EntityName EN)> AddEntity,
+                         bool IsFunRet = false);
 
 /// Creates a new EntityPointerLevel (EPL) from `E` by incrementing `E`'s
 /// pointer level.

>From bae2ead1cd034a1e7505318c5455e7565082e9ae Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Wed, 15 Apr 2026 12:34:30 -0700
Subject: [PATCH 14/25] fix merge issues

---
 .../Analyses/SSAFAnalysesCommon.cpp                          | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
index 31962bdee7f92..2d55511135d10 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
@@ -8,6 +8,8 @@
 
 #include "SSAFAnalysesCommon.h"
 
+using namespace clang;
+
 namespace {
 // Traverses the AST and finds contributors.
 class ContributorFinder : public DynamicRecursiveASTVisitor {
@@ -95,7 +97,8 @@ void findContributors(ASTContext &Ctx,
                       std::vector<const NamedDecl *> &Contributors) {
   ContributorFinder Finder;
   Finder.TraverseAST(Ctx);
-  Contributors = std::move(Finder.Contributors);
+  Contributors.insert(Contributors.end(), Finder.Contributors.begin(),
+                      Finder.Contributors.end());
 }
 
 void findMatchesIn(const NamedDecl *Contributor,

>From 25ccdfabba513cad38e5687fb122e1d85cd15982 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Wed, 15 Apr 2026 12:35:38 -0700
Subject: [PATCH 15/25] fix build issue

---
 .../Analyses/SSAFAnalysesCommon.h                                | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
index bce1129891df0..22274de5e471f 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
@@ -12,6 +12,7 @@
 #ifndef LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_SSAFANALYSESCOMMON_H
 #define LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_SSAFANALYSESCOMMON_H
 
+#include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
 #include "llvm/Support/JSON.h"
 

>From 47f1c1a54cd56179bf022e903b9c135c6b188389 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Wed, 15 Apr 2026 13:53:48 -0700
Subject: [PATCH 16/25] clean up

---
 .../Analyses/EntityPointerLevel/EntityPointerLevel.h     | 2 +-
 .../Analyses/SSAFAnalysesCommon.cpp                      | 4 ++--
 .../Analyses/SSAFAnalysesCommon.h                        | 2 +-
 .../UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp     | 9 +++------
 4 files changed, 7 insertions(+), 10 deletions(-)

diff --git a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
index 2642993d05842..429bb74fb417e 100644
--- a/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
+++ b/clang/include/clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h
@@ -116,7 +116,7 @@ createEntityPointerLevel(const NamedDecl *ND,
 /// Creates a new EntityPointerLevel (EPL) from `E` by incrementing `E`'s
 /// pointer level.
 /// \return the EPL that is associated with the pointee (or array element) type
-/// of `E`'s associated pointer/array tyoe of the same entity.
+/// of `E`'s associated pointer/array type of the same entity.
 EntityPointerLevel incrementPointerLevel(const EntityPointerLevel &E);
 } // namespace clang::ssaf
 
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
index 2d55511135d10..a00e7933165ef 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
@@ -67,8 +67,8 @@ class ContributorFactFinder : public DynamicRecursiveASTVisitor {
     if (!Node)
       return true;
     // To skip callables:
-    if (Node != RootDecl && isa<FunctionDecl, CXXConstructorDecl, BlockDecl,
-                                ObjCMethodDecl, RecordDecl>(Node))
+    if (Node != RootDecl &&
+        isa<FunctionDecl, BlockDecl, ObjCMethodDecl, RecordDecl>(Node))
       return true;
     match(*Node);
     return DynamicRecursiveASTVisitor::TraverseDecl(Node);
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
index b9dcfcc9a7aad..e6759c1fb6e39 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
@@ -42,7 +42,7 @@ template <typename DeclOrExpr> bool hasPtrOrArrType(const DeclOrExpr *E) {
 inline llvm::Error makeEntityNameErr(clang::ASTContext &Ctx,
                                      const clang::NamedDecl *D) {
   return makeErrAtNode(Ctx, D, "failed to create entity name for %s",
-                       D->getNameAsString().data());
+                       D->getNameAsString().c_str());
 }
 
 namespace clang::ssaf {
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
index 75137e7a5d640..770f20830c77b 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
@@ -14,7 +14,6 @@
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/ASTEntityMapping.h"
-#include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityId.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/Model/EntityName.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/ExtractorRegistry.h"
 #include "clang/ScalableStaticAnalysisFramework/Core/TUSummary/TUSummaryBuilder.h"
@@ -27,13 +26,13 @@ using namespace clang;
 using namespace ssaf;
 
 namespace {
-static std::set<const Expr *>
+std::set<const Expr *>
 findUnsafePointersInContributor(const DynTypedNode &Node) {
   const Decl *D = Node.get<Decl>();
 
   if (!D)
     return {};
-  if (isa<FunctionDecl>(D) || isa<VarDecl>(D))
+  if (isa<FunctionDecl, VarDecl>(D))
     return findUnsafePointers(D);
   if (auto *RD = dyn_cast<RecordDecl>(D)) {
     std::set<const Expr *> Result;
@@ -53,8 +52,6 @@ class UnsafeBufferUsageTUSummaryExtractor : public TUSummaryExtractor {
   UnsafeBufferUsageTUSummaryExtractor(TUSummaryBuilder &Builder)
       : TUSummaryExtractor(Builder) {}
 
-  EntityId addEntity(EntityName EN) { return SummaryBuilder.addEntity(EN); }
-
   Expected<std::unique_ptr<UnsafeBufferUsageEntitySummary>>
   extractEntitySummary(const NamedDecl *Contributor, ASTContext &Ctx);
 
@@ -118,7 +115,7 @@ void clang::ssaf::UnsafeBufferUsageTUSummaryExtractor::HandleTranslationUnit(
       llvm::reportFatalInternalError(makeEntityNameErr(Ctx, CD));
 
     auto [Ignored, InsertionSucceeded] = SummaryBuilder.addSummary(
-        addEntity(*ContributorName), std::move(*EntitySummary));
+        SummaryBuilder.addEntity(*ContributorName), std::move(*EntitySummary));
 
     assert(InsertionSucceeded && "duplicated contributor extraction");
   }

>From ce73ab70bec38f6d5740413a365c6d5dd24e4a91 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 20 Apr 2026 16:28:32 -0700
Subject: [PATCH 17/25] Update
 clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Balázs Benics <benicsbalazs at gmail.com>
---
 .../Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp        | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp b/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
index 11c3e4e01c5bc..b0393be62541c 100644
--- a/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
+++ b/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
@@ -74,7 +74,7 @@ class UnsafeBufferUsageTest : public TestFixture {
 
   UnsafeBufferUsageTest()
       : TUSum(BuildNamespace(BuildNamespaceKind::CompilationUnit, "Mock.cpp")),
-        Builder(TUSum), Extractor(nullptr) {}
+        Builder(TUSum) {}
 
   bool setUpTest(StringRef Code) {
     AST = tooling::buildASTFromCodeWithArgs(

>From 9356e1e4dd099ccf085df9a8d175cbce7a61ce9a Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 20 Apr 2026 16:33:19 -0700
Subject: [PATCH 18/25] Update
 clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Co-authored-by: Balázs Benics <benicsbalazs at gmail.com>
---
 .../Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp   | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
index 712c2d39e3695..84e076f1555de 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
@@ -162,4 +162,4 @@ volatile int UnsafeBufferUsageTUSummaryExtractorAnchorSource = 0;
 static clang::ssaf::TUSummaryExtractorRegistry::Add<
     ssaf::UnsafeBufferUsageTUSummaryExtractor>
     RegisterExtractor(UnsafeBufferUsageEntitySummary::Name,
-                      "The TUSummaryExtractor for unsafe buffer pointers");
\ No newline at end of file
+                      "The TUSummaryExtractor for unsafe buffer pointers");

>From 212474a0724d00edbaf1123ee063983fd3d14625 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 20 Apr 2026 16:59:32 -0700
Subject: [PATCH 19/25] address comments

---
 .../UnsafeBufferUsageTest.cpp                 | 148 +++++++-----------
 1 file changed, 59 insertions(+), 89 deletions(-)

diff --git a/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp b/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
index b0393be62541c..4a631a28897d0 100644
--- a/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
+++ b/clang/unittests/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsageTest.cpp
@@ -8,6 +8,7 @@
 
 #include "clang/ScalableStaticAnalysisFramework/Analyses/UnsafeBufferUsage/UnsafeBufferUsage.h"
 #include "TestFixture.h"
+#include "clang/AST/ASTConsumer.h"
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
 #include "clang/Frontend/ASTUnit.h"
 #include "clang/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.h"
@@ -69,7 +70,7 @@ class UnsafeBufferUsageTest : public TestFixture {
 protected:
   TUSummary TUSum;
   TUSummaryBuilder Builder;
-  std::unique_ptr<TUSummaryExtractor> Extractor;
+  std::unique_ptr<ASTConsumer> Extractor;
   std::unique_ptr<ASTUnit> AST;
 
   UnsafeBufferUsageTest()
@@ -80,12 +81,8 @@ class UnsafeBufferUsageTest : public TestFixture {
     AST = tooling::buildASTFromCodeWithArgs(
         Code, {"-Wno-unused-value", "-Wno-int-to-pointer-cast"});
 
-    for (auto &E : clang::ssaf::TUSummaryExtractorRegistry::entries()) {
-      if (E.getName() == UnsafeBufferUsageEntitySummary::Name) {
-        Extractor = E.instantiate(Builder);
-        break;
-      }
-    }
+    Extractor =
+        makeTUSummaryExtractor(UnsafeBufferUsageEntitySummary::Name, Builder);
 
     if (!Extractor) {
       ADD_FAILURE() << "failed to find UnsafeBufferUsageTUSummaryExtractor";
@@ -226,13 +223,12 @@ TEST_F(UnsafeBufferUsageTest, UnsafeBufferUsageEntityPointerLevelSetTest) {
 //////////////////////////////////////////////////////////////
 
 TEST_F(UnsafeBufferUsageTest, UnsafeBufferUsageSerializeTest) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int ***p, int ****q, int x) {
       p[5][5][5];
       q[5][5][5][5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
   ASSERT_NE(Sum, nullptr);
   EXPECT_EQ(*Sum, makeSet(__LINE__, {{"p", 1U},
@@ -273,12 +269,11 @@ TEST_F(UnsafeBufferUsageTest, UnsafeBufferUsageSerializeTest) {
 //////////////////////////////////////////////////////////////
 
 TEST_F(UnsafeBufferUsageTest, SimpleFunctionWithUnsafePointer) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int *p) {
       p[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -286,13 +281,12 @@ TEST_F(UnsafeBufferUsageTest, SimpleFunctionWithUnsafePointer) {
 }
 
 TEST_F(UnsafeBufferUsageTest, PointerArithmetic) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int *p, int *q) {
       *(p + 5);
       *(q - 3);
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -300,15 +294,14 @@ TEST_F(UnsafeBufferUsageTest, PointerArithmetic) {
 }
 
 TEST_F(UnsafeBufferUsageTest, PointerIncrementDecrement) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int *p, int *q, int *r, int *s) {
       (++p)[5];
       (q++)[5];
       (--r)[5];
       (s--)[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -317,12 +310,11 @@ TEST_F(UnsafeBufferUsageTest, PointerIncrementDecrement) {
 }
 
 TEST_F(UnsafeBufferUsageTest, PointerAssignment) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int *p, int *q) {
       (p = q + 5)[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -330,13 +322,12 @@ TEST_F(UnsafeBufferUsageTest, PointerAssignment) {
 }
 
 TEST_F(UnsafeBufferUsageTest, CompoundAssignment) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int *p, int *q) {
       (p += 5)[5];
       (q -= 3)[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -344,15 +335,14 @@ TEST_F(UnsafeBufferUsageTest, CompoundAssignment) {
 }
 
 TEST_F(UnsafeBufferUsageTest, MultiLevelPointer) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int **p, int **q, int **r) {
       (*p)[5];
       *(*q);
       *(q[5]);
       r[5][5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -361,13 +351,12 @@ TEST_F(UnsafeBufferUsageTest, MultiLevelPointer) {
 }
 
 TEST_F(UnsafeBufferUsageTest, ConditionalOperator) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int **p, int **q, int cond) {
       (cond ? *p : *q)[5];
       cond ? p[5] : q[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -376,13 +365,12 @@ TEST_F(UnsafeBufferUsageTest, ConditionalOperator) {
 }
 
 TEST_F(UnsafeBufferUsageTest, CastExpression) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(void *p, int q) {
       ((int*)p)[5];
       ((int*)q)[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -390,12 +378,11 @@ TEST_F(UnsafeBufferUsageTest, CastExpression) {
 }
 
 TEST_F(UnsafeBufferUsageTest, CommaOperator) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int *p, int x) {
       (x++, p)[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -403,12 +390,11 @@ TEST_F(UnsafeBufferUsageTest, CommaOperator) {
 }
 
 TEST_F(UnsafeBufferUsageTest, CommaOperator2) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int **p, int **q, int x) {
       (p[x] = 0, q[x] = 0)[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -416,12 +402,11 @@ TEST_F(UnsafeBufferUsageTest, CommaOperator2) {
 }
 
 TEST_F(UnsafeBufferUsageTest, ParenthesizedExpression) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int *p) {
       (((p)))[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -429,14 +414,13 @@ TEST_F(UnsafeBufferUsageTest, ParenthesizedExpression) {
 }
 
 TEST_F(UnsafeBufferUsageTest, ArrayParameter) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int arr[], int arr2[][10]) {
       int n = 5;
       arr[100];
       arr2[5][n];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -444,15 +428,14 @@ TEST_F(UnsafeBufferUsageTest, ArrayParameter) {
 }
 
 TEST_F(UnsafeBufferUsageTest, FunctionCall) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     int ** (*fp)();
     int ** foo() {
       fp = &foo;
       foo()[5];
       (*fp())[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -461,7 +444,7 @@ TEST_F(UnsafeBufferUsageTest, FunctionCall) {
 }
 
 TEST_F(UnsafeBufferUsageTest, StructMemberAccess) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     struct S {
       int *ptr;
       int (*ptr_to_arr)[10];
@@ -471,8 +454,7 @@ TEST_F(UnsafeBufferUsageTest, StructMemberAccess) {
       obj.ptr[5];
       (*obj.ptr_to_arr)[n];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -480,12 +462,11 @@ TEST_F(UnsafeBufferUsageTest, StructMemberAccess) {
 }
 
 TEST_F(UnsafeBufferUsageTest, StringLiteralSubscript) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo() {
       "hello"[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   // String literals should not generate pointer kind variables
@@ -493,12 +474,11 @@ TEST_F(UnsafeBufferUsageTest, StringLiteralSubscript) {
 }
 
 TEST_F(UnsafeBufferUsageTest, OpaqueValueExpr) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int *p, int *q) {
        (p ?: q)[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -506,25 +486,23 @@ TEST_F(UnsafeBufferUsageTest, OpaqueValueExpr) {
 }
 
 TEST_F(UnsafeBufferUsageTest, AddressOfOperator) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int x) {
       (&x)[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
   // Address-of should not generate pointer kind variables for 'x':
   EXPECT_EQ(Sum, nullptr);
 }
 
 TEST_F(UnsafeBufferUsageTest, AddressOfThenDereference) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo(int *p, int *q) {
       (*(&p))[5];
       (&(*q))[5];
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -532,7 +510,7 @@ TEST_F(UnsafeBufferUsageTest, AddressOfThenDereference) {
 }
 
 TEST_F(UnsafeBufferUsageTest, PointerToArrayOfPointers) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     void foo() {
       int * arr[10];
       int * (*p)[10] = &arr;
@@ -540,8 +518,7 @@ TEST_F(UnsafeBufferUsageTest, PointerToArrayOfPointers) {
       (*p)[5][5]; // '(*p)[5]' is unsafe
                   // '(*p)' is fine because 5 < 10
     }
-  )cpp"),
-            true);
+  )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -549,11 +526,10 @@ TEST_F(UnsafeBufferUsageTest, PointerToArrayOfPointers) {
 }
 
 TEST_F(UnsafeBufferUsageTest, UnsafePointerInGlobalVariableInitializer) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
       int *gp;
       int x = gp[5];
-    )cpp"),
-            true);
+    )cpp"));
   const auto *Sum = getEntitySummary("x");
 
   EXPECT_NE(Sum, nullptr);
@@ -561,13 +537,12 @@ TEST_F(UnsafeBufferUsageTest, UnsafePointerInGlobalVariableInitializer) {
 }
 
 TEST_F(UnsafeBufferUsageTest, UnsafePointerInFieldInitializer) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
       int *gp;
       struct Foo {
         int field = gp[5];
       };
-    )cpp"),
-            true);
+    )cpp"));
   const auto *Sum = getEntitySummary("Foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -575,14 +550,13 @@ TEST_F(UnsafeBufferUsageTest, UnsafePointerInFieldInitializer) {
 }
 
 TEST_F(UnsafeBufferUsageTest, UnsafePointerInFieldInitializer2) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
       int *gp;
       union Foo {
         int field = gp[5];
         int x;
       };
-    )cpp"),
-            true);
+    )cpp"));
   const auto *Sum = getEntitySummary("Foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -590,15 +564,14 @@ TEST_F(UnsafeBufferUsageTest, UnsafePointerInFieldInitializer2) {
 }
 
 TEST_F(UnsafeBufferUsageTest, InitializerList) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
       int *gp;
       struct Foo {
         int field;
         int x;
       };
       Foo FooObj{gp[5], 0};
-    )cpp"),
-            true);
+    )cpp"));
   const auto *Sum = getEntitySummary("FooObj");
 
   EXPECT_NE(Sum, nullptr);
@@ -606,13 +579,12 @@ TEST_F(UnsafeBufferUsageTest, InitializerList) {
 }
 
 TEST_F(UnsafeBufferUsageTest, UnsafePointerInCXXCtorInitializer) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
       struct Foo {
         int member;
         Foo(int *p) : member(p[5]) {}
       };
-    )cpp"),
-            true);
+    )cpp"));
   const auto *Sum = getEntitySummary<CXXConstructorDecl>("Foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -620,11 +592,10 @@ TEST_F(UnsafeBufferUsageTest, UnsafePointerInCXXCtorInitializer) {
 }
 
 TEST_F(UnsafeBufferUsageTest, UnsafePointerInDefaultArg) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     int * gp;
     void foo(int x = gp[5]);
-    )cpp"),
-            true);
+    )cpp"));
   const auto *Sum = getEntitySummary("foo");
 
   EXPECT_NE(Sum, nullptr);
@@ -632,15 +603,14 @@ TEST_F(UnsafeBufferUsageTest, UnsafePointerInDefaultArg) {
 }
 
 TEST_F(UnsafeBufferUsageTest, NestedDefinitions) {
-  ASSERT_EQ(setUpTest(R"cpp(
+  ASSERT_TRUE(setUpTest(R"cpp(
     int * a = [](){
       struct Foo {
         void bar(int * ptr) { ptr[3] = 0; }
       };
       return nullptr;
     }();
-    )cpp"),
-            true);
+    )cpp"));
   const auto *Sum = getEntitySummary("bar");
 
   EXPECT_NE(Sum, nullptr);
@@ -665,7 +635,7 @@ TEST_F(UnsafeBufferUsageTest, NestedDefinitions2) {
     }
     )cpp");
 
-  ASSERT_EQ(SetupSuccess, true);
+  ASSERT_TRUE(SetupSuccess);
 
   const auto *Sum = getEntitySummary("bar");
 

>From cd5634a0dfce86ea186e15b0e939a491d4bacd0c Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 20 Apr 2026 18:33:28 -0700
Subject: [PATCH 20/25] Move templates into clang::ssaf

---
 .../Analyses/CMakeLists.txt                     |  1 +
 .../Analyses/SSAFAnalysesCommon.cpp             | 17 +++++++++++++++++
 .../Analyses/SSAFAnalysesCommon.h               |  9 ++++-----
 3 files changed, 22 insertions(+), 5 deletions(-)
 create mode 100644 clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp

diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt b/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt
index c15ff3b3c42e7..12a334260cda7 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/CMakeLists.txt
@@ -6,6 +6,7 @@ add_clang_library(clangScalableStaticAnalysisFrameworkAnalyses
   CallGraph/CallGraphExtractor.cpp
   CallGraph/CallGraphJSONFormat.cpp
   EntityPointerLevel/EntityPointerLevel.cpp
+  SSAFAnalysesCommon.cpp
   UnsafeBufferUsage/UnsafeBufferUsage.cpp
   UnsafeBufferUsage/UnsafeBufferUsageExtractor.cpp
 
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
new file mode 100644
index 0000000000000..481c545edc32a
--- /dev/null
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
@@ -0,0 +1,17 @@
+//===- SSAFAnalysesCommon.cpp ---------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "SSAFAnalysesCommon.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+
+llvm::Error clang::ssaf::makeEntityNameErr(clang::ASTContext &Ctx,
+                                           const clang::NamedDecl *D) {
+  return makeErrAtNode(Ctx, D, "failed to create entity name for %s",
+                       D->getNameAsString().data());
+}
diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
index 22274de5e471f..4ae37ebdac765 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.h
@@ -16,6 +16,7 @@
 #include "clang/AST/Decl.h"
 #include "llvm/Support/JSON.h"
 
+namespace clang::ssaf {
 template <typename NodeTy, typename... Ts>
 llvm::Error makeErrAtNode(clang::ASTContext &Ctx, const NodeTy *N,
                           llvm::StringRef Fmt, const Ts &...Args) {
@@ -39,10 +40,8 @@ template <typename DeclOrExpr> bool hasPtrOrArrType(const DeclOrExpr *E) {
       E->getType().getCanonicalType());
 }
 
-inline llvm::Error makeEntityNameErr(clang::ASTContext &Ctx,
-                                     const clang::NamedDecl *D) {
-  return makeErrAtNode(Ctx, D, "failed to create entity name for %s",
-                       D->getNameAsString().data());
-}
+llvm::Error makeEntityNameErr(clang::ASTContext &Ctx,
+                              const clang::NamedDecl *D);
+} // namespace clang::ssaf
 
 #endif // LLVM_CLANG_SCALABLESTATICANALYSISFRAMEWORK_ANALYSES_SSAFANALYSESCOMMON_H

>From a69a290e3fc6888991fd1474aef1836021bfac58 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 20 Apr 2026 21:36:33 -0700
Subject: [PATCH 21/25] a class should own a std::function instead of a
 llvm::function_ref

---
 .../Analyses/EntityPointerLevel/EntityPointerLevel.cpp      | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
index 68a452ee61b43..52e6705ec43af 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/EntityPointerLevel/EntityPointerLevel.cpp
@@ -68,12 +68,12 @@ class EntityPointerLevelTranslator
     return EntityPointerLevelSet{Incremented.begin(), Incremented.end()};
   }
 
-  llvm::function_ref<EntityId(EntityName EN)> AddEntity;
+  std::function<EntityId(EntityName EN)> AddEntity;
   ASTContext &Ctx;
 
 public:
-  EntityPointerLevelTranslator(
-      llvm::function_ref<EntityId(EntityName EN)> AddEntity, ASTContext &Ctx)
+  EntityPointerLevelTranslator(std::function<EntityId(EntityName EN)> AddEntity,
+                               ASTContext &Ctx)
       : AddEntity(AddEntity), Ctx(Ctx) {}
 
   Expected<EntityPointerLevelSet> translate(const Expr *E) { return Visit(E); }

>From 699d592c2bb02375fbec0859ce7ddf595ba855ce Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 20 Apr 2026 23:12:40 -0700
Subject: [PATCH 22/25] fix build issue

---
 .../Analyses/SSAFAnalysesCommon.cpp                              | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
index 6b1eb6b243881..a536ac75870ac 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
@@ -9,6 +9,7 @@
 #include "SSAFAnalysesCommon.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
+#include "clang/AST/DynamicRecursiveASTVisitor.h"
 
 using namespace clang;
 

>From bc19b3d51dedf0c6b9c3a4df548d4e856585caab Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Mon, 20 Apr 2026 23:14:04 -0700
Subject: [PATCH 23/25] fix build issue

---
 .../Analyses/SSAFAnalysesCommon.cpp                              | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
index a536ac75870ac..437457c2f7455 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
@@ -9,6 +9,7 @@
 #include "SSAFAnalysesCommon.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Decl.h"
+#include "clang/AST/DeclObjC.h"
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
 
 using namespace clang;

>From 8a57cb180f85577b078583dd8b0e62115d87eeb9 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Tue, 21 Apr 2026 12:06:03 -0700
Subject: [PATCH 24/25] address comments

---
 .../Analyses/SSAFAnalysesCommon.cpp           | 30 ++++++++++---------
 1 file changed, 16 insertions(+), 14 deletions(-)

diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
index 437457c2f7455..7713114c79b23 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
@@ -18,15 +18,15 @@ namespace {
 // Traverses the AST and finds contributors.
 class ContributorFinder : public DynamicRecursiveASTVisitor {
 public:
-  std::vector<const NamedDecl *> Contributors;
+  std::set<const NamedDecl *> Contributors;
 
   bool VisitFunctionDecl(FunctionDecl *D) override {
-    Contributors.push_back(D);
+    Contributors.insert(D);
     return true;
   }
 
   bool VisitRecordDecl(RecordDecl *D) override {
-    Contributors.push_back(D);
+    Contributors.insert(D);
     return true;
   }
 
@@ -34,29 +34,31 @@ class ContributorFinder : public DynamicRecursiveASTVisitor {
     DeclContext *DC = D->getDeclContext();
 
     if (DC->isFileContext() || DC->isNamespace())
-      Contributors.push_back(D);
+      Contributors.insert(D);
     return true;
   }
 };
 
-// An AST visitor that skips the root node's strict-descendants that are
-// callable Decls and record Decls, because those are separate contributors.
-//
-// Clients need to implement their own `MatchAction`, which is a function that
-// takes a `DynTypedNode`, decides if it matches and performs any further
-// callback actions.
+/// An AST visitor that skips the root node's strict-descendants that are
+/// callable Decls and record Decls, because those are separate contributors.
+///
+/// Clients need to implement their own "MatchAction", which is a function that
+/// takes a `DynTypedNode`, decides if the node matches and performs any further
+/// callback actions.
+/// ContributorFactFinder takes a reference to a "MatchAction". It does not own
+/// the "MatchAction", which is usually stateful and may own containers.
 class ContributorFactFinder : public DynamicRecursiveASTVisitor {
-  llvm::function_ref<void(const DynTypedNode &)> MatchAction;
+  llvm::function_ref<void(const DynTypedNode &)> MatchActionRef;
   const NamedDecl *RootDecl = nullptr;
 
   template <typename NodeTy> void match(const NodeTy &Node) {
-    MatchAction(DynTypedNode::create(Node));
+    MatchActionRef(DynTypedNode::create(Node));
   }
 
 public:
   ContributorFactFinder(
-      llvm::function_ref<void(const DynTypedNode &)> MatchAction)
-      : MatchAction(MatchAction) {
+      llvm::function_ref<void(const DynTypedNode &)> MatchActionRef)
+      : MatchActionRef(MatchActionRef) {
     ShouldVisitTemplateInstantiations = true;
     ShouldVisitImplicitCode = false;
   }

>From e8131c7566aafc3a4d255100906f7b10ef96b743 Mon Sep 17 00:00:00 2001
From: Ziqing Luo <ziqing_luo at apple.com>
Date: Tue, 21 Apr 2026 13:34:44 -0700
Subject: [PATCH 25/25] add #include <set>

---
 .../Analyses/SSAFAnalysesCommon.cpp                              | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
index 7713114c79b23..d5458fbb2c1c7 100644
--- a/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
+++ b/clang/lib/ScalableStaticAnalysisFramework/Analyses/SSAFAnalysesCommon.cpp
@@ -11,6 +11,7 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DynamicRecursiveASTVisitor.h"
+#include <set>
 
 using namespace clang;
 



More information about the cfe-commits mailing list