[clang] [FlowSensitive][Nullability] 1/N add initial model for nullability analysis (PR #245392)

Jan Voung via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 23 17:53:16 PST 2026


https://github.com/jvoung updated https://github.com/llvm/llvm-project/pull/245392

>From b5d62e215343a6e004f2f35f71f2ce56c9c52eb9 Mon Sep 17 00:00:00 2001
From: Jan Voung <jvoung at gmail.com>
Date: Mon, 23 Nov 2026 21:30:10 +0000
Subject: [PATCH] [FlowSensitive][Nullability] 1/N add initial model for
 nullability analysis

For https://github.com/llvm/llvm-project/issues/245374

Adds initial modeling of pointer nullability state for raw pointers.
Is the pointer from a _Nullable annotated value, and is it definitely
null?

Tests currently only inspect the dataflow state. Next patch will
introduce a diagnoser to allow tests that emit diagnostics. Then will
handle comparisons, etc.
---
 .../Models/Nullability/PointerNullability.h   | 143 ++++++++++++++
 .../Nullability/PointerNullabilityAnalysis.h  |  60 ++++++
 .../Nullability/PointerNullabilityLattice.h   |  24 +++
 .../Nullability/PointerNullabilityMatchers.h  |  33 ++++
 .../Models/Nullability/ValueTransferer.h      |  39 ++++
 .../FlowSensitive/Models/CMakeLists.txt       |   2 +
 .../Models/Nullability/CMakeLists.txt         |  17 ++
 .../Models/Nullability/PointerNullability.cpp | 174 +++++++++++++++++
 .../PointerNullabilityAnalysis.cpp            | 136 +++++++++++++
 .../PointerNullabilityMatchers.cpp            |  34 ++++
 .../Models/Nullability/ValueTransferer.cpp    | 176 +++++++++++++++++
 .../Analysis/FlowSensitive/CMakeLists.txt     |   2 +
 .../Models/Nullability/AssignmentTest.cpp     | 184 ++++++++++++++++++
 .../Models/Nullability/CMakeLists.txt         |  24 +++
 .../Nullability/CheckNullabilityState.cpp     |  51 +++++
 .../Nullability/CheckNullabilityState.h       |  24 +++
 .../Models/Nullability/JoinTest.cpp           | 155 +++++++++++++++
 .../Nullability/PointerNullabilityTest.cpp    | 134 +++++++++++++
 18 files changed, 1412 insertions(+)
 create mode 100644 clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullability.h
 create mode 100644 clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityAnalysis.h
 create mode 100644 clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityLattice.h
 create mode 100644 clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityMatchers.h
 create mode 100644 clang/include/clang/Analysis/FlowSensitive/Models/Nullability/ValueTransferer.h
 create mode 100644 clang/lib/Analysis/FlowSensitive/Models/Nullability/CMakeLists.txt
 create mode 100644 clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullability.cpp
 create mode 100644 clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityAnalysis.cpp
 create mode 100644 clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityMatchers.cpp
 create mode 100644 clang/lib/Analysis/FlowSensitive/Models/Nullability/ValueTransferer.cpp
 create mode 100644 clang/unittests/Analysis/FlowSensitive/Models/Nullability/AssignmentTest.cpp
 create mode 100644 clang/unittests/Analysis/FlowSensitive/Models/Nullability/CMakeLists.txt
 create mode 100644 clang/unittests/Analysis/FlowSensitive/Models/Nullability/CheckNullabilityState.cpp
 create mode 100644 clang/unittests/Analysis/FlowSensitive/Models/Nullability/CheckNullabilityState.h
 create mode 100644 clang/unittests/Analysis/FlowSensitive/Models/Nullability/JoinTest.cpp
 create mode 100644 clang/unittests/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityTest.cpp

diff --git a/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullability.h b/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullability.h
new file mode 100644
index 00000000000000..70f52987e9a44d
--- /dev/null
+++ b/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullability.h
@@ -0,0 +1,143 @@
+//===-- PointerNullability.h - Pointer nullability properties ---*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file extends the dataflow framework's Value model to track nullability.
+// We attach two boolean properties to each modeled pointer value:
+//  - is_null: whether the pointer is known to be null.
+//    If this is false, dereferencing is safe.
+//  - from_nullable: whether the originating expression was considered nullable
+//    (e.g. a reference to a Nullable-annotated variable, or a nullptr literal)
+//    If this is false, dereferencing may be safe: we don't know the contract
+//    (Unspecified).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITY_H
+#define CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITY_H
+
+#include "clang/AST/Expr.h"
+#include "clang/AST/Type.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/Formula.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Basic/Specifiers.h"
+#include <optional>
+
+namespace clang::dataflow::nullability {
+
+/// Is this exactly a pointer type that we track outer nullability for?
+/// This unwraps sugar, i.e. it looks at the canonical type.
+///
+/// (For now, only regular `PointerType`s. Support for smart pointers will be
+/// added later; code that will need to handle them already uses this function
+/// rather than `isSupportedRawPointerType()`, so it won't need to change. In
+/// future we should consider supporting pointer-to-member, ObjC pointers, etc).
+bool isSupportedPointerType(QualType T);
+
+/// Is this exactly a raw (non-smart) pointer type that we track outer
+/// nullability for?
+/// This unwraps sugar, i.e. it looks at the canonical type.
+bool isSupportedRawPointerType(QualType T);
+
+/// Returns the `PointerValue` allocated to `PointerExpr` if available.
+/// Otherwise, returns nullptr.
+PointerValue *getRawPointerValue(const Expr *PointerExpr,
+                                 const Environment &Env);
+
+/// Returns the `PointerValue` for a raw or smart pointer expression, if
+/// available.
+/// Use this function only if the expression can actually be either a raw or
+/// smart pointer; otherwise, use `getRawPointerValue()`.
+/// (Smart pointers are not supported yet, so for now this is the same as
+/// `getRawPointerValue()`.)
+PointerValue *getPointerValue(const Expr *PointerExpr, const Environment &Env);
+
+// Returns true if the pointer has all properties necessary for representing
+// complete nullness information.
+// Otherwise, returns false.
+//
+// Pointers that are the value of some expression always have null state once
+// that expression has been analyzed. Other pointers, like the values of unused
+// parameters, may lack this state. This state is only set by
+// PointerNullabilityAnalysis, not by the dataflow framework.
+bool hasPointerNullState(const PointerValue &PointerVal);
+
+/// The properties representing nullness information for a pointer.
+///
+/// We attach these properties to every PointerValue taken by an expression.
+///
+/// A null pointer for `FromNullable` or `IsNull` represents "top", i.e. we have
+/// no information on this property.
+struct PointerNullState {
+  /// Did the pointer come from a known-nullable source?
+  const Formula *FromNullable;
+  /// Is the pointer's value null?
+  const Formula *IsNull;
+  // These are independent: sources with unknown nullability can yield nullptr!
+};
+
+/// Returns the properties representing the nullness information of a pointer.
+PointerNullState getPointerNullState(const PointerValue &PointerVal);
+
+/// Creates the nullness properties on `PointerVal` if not already initialised.
+///
+/// We call this when the framework produces a PointerValue for an expression.
+/// This ensures that the variable has usable "from nullable" and "is null"
+/// boolean variables, and that they are constrained based on the *original*
+/// source of the PointerValue.
+///
+/// For example:
+///    int _Null_unspecified* x = getNullable();
+///                               ~~~~~~~~~~~ <-- initPointerNullState(Nullable)
+///    *x;
+///     ~ <-- initPointerNullState(Unspecified) - no effect, already initialized
+///
+/// (We assume that the framework will not provide the same pointer from
+/// different initial sources, so the `Source` nullability is the same
+/// regardless of block evaluation order).
+void initPointerNullState(PointerValue &PointerVal,
+                          DataflowAnalysisContext &Ctx,
+                          std::optional<NullabilityKind> Source = std::nullopt);
+
+/// Initializes the nullness properties on `PointerVal` from `State`.
+///
+/// This overload may only be called on a freshly created `PointerValue` that
+/// does not yet have nullability properties.
+void initPointerNullState(PointerValue &PointerVal,
+                          DataflowAnalysisContext &Ctx, PointerNullState State);
+
+/// Variant of initPointerNullState, where the pointer is guaranteed null.
+void initNullPointer(PointerValue &PointerVal, DataflowAnalysisContext &Ctx);
+
+/// Returns true if `NullState` is known to be null or is from a nullable source
+/// and may be null.
+bool isNullable(PointerNullState NullState, const Environment &Env);
+
+/// Returns true if `PointerVal` is known to be null or is from a nullable
+/// source and may be null. Convenience overload for `isNullable` above.
+bool isNullable(const PointerValue &PointerVal, const Environment &Env);
+
+/// Returns the strongest provable assertion we can make for the given null
+/// state. If a pointer with that state may not be null, returns Nonnull. If it
+/// is known to be null or is from a nullable source and may be null, returns
+/// Nullable. Otherwise, returns Unspecified.
+NullabilityKind getNullability(PointerNullState PointerNullState,
+                               const Environment &Env);
+
+/// Returns the strongest provable assertion we can make about `PointerVal`.
+NullabilityKind getNullability(const PointerValue &PointerVal,
+                               const Environment &Env);
+
+/// Returns the strongest provable assertion we can make about the value of
+/// `E` in `Env`.
+NullabilityKind getNullability(const Expr *E, const Environment &Env);
+
+} // namespace clang::dataflow::nullability
+
+#endif // CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITY_H
diff --git a/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityAnalysis.h b/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityAnalysis.h
new file mode 100644
index 00000000000000..0fba4f572a990e
--- /dev/null
+++ b/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityAnalysis.h
@@ -0,0 +1,60 @@
+//===-- PointerNullabilityAnalysis.h - Nullability analysis -----*- 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 CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITYANALYSIS_H
+#define CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITYANALYSIS_H
+
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Type.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/CFGMatchSwitch.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/MatchSwitch.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityLattice.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+
+namespace clang::dataflow::nullability {
+
+/// Analyzes constructs in the source code to collect nullability information
+/// about pointers at each program point. This analysis and the corresponding
+/// lattice were based on the gradual analysis in 'Estep, Sam, Jenna Wise,
+/// Jonathan Aldrich, Éric Tanter, Johannes Bader, and Joshua Sunshine. "Gradual
+/// Program Analysis for Null Pointers." In 35th European Conference on
+/// Object-Oriented Programming (ECOOP). 2021.'
+class PointerNullabilityAnalysis
+    : public DataflowAnalysis<PointerNullabilityAnalysis,
+                              PointerNullabilityLattice> {
+public:
+  explicit PointerNullabilityAnalysis(ASTContext &Context, Environment &Env);
+
+  PointerNullabilityLattice initialElement() { return {}; }
+
+  void transfer(const CFGElement &Elt, PointerNullabilityLattice &Lattice,
+                Environment &Env);
+
+  void join(QualType Type, const Value &Val1, const Environment &Env1,
+            const Value &Val2, const Environment &Env2, Value &MergedVal,
+            Environment &MergedEnv) override;
+
+  // TODO: Add `compare` and `widen` overrides, as in
+  // https://github.com/google/crubit/blob/5f9ae7da1aa70e5a1c0e536baf32e5ec56a7c003/nullability/pointer_nullability_analysis.cc#L239
+  // Until then, this only handles loop-free code precisely: the framework's
+  // default comparison treats any two pointer values at a loop head as
+  // equivalent, so the loop body is not re-analyzed when a pointer's
+  // nullability changes along the back edge.
+
+private:
+  // Transfers (flow-sensitive) value properties through statements.
+  CFGMatchSwitch<TransferState<PointerNullabilityLattice>> ValueTransferer;
+};
+
+} // namespace clang::dataflow::nullability
+
+#endif // CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITYANALYSIS_H
diff --git a/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityLattice.h b/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityLattice.h
new file mode 100644
index 00000000000000..e2796eb33a1ab8
--- /dev/null
+++ b/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityLattice.h
@@ -0,0 +1,24 @@
+//===-- PointerNullabilityLattice.h - Nullability lattice -------*- 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 CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITYLATTICE_H
+#define CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITYLATTICE_H
+
+#include "clang/Analysis/FlowSensitive/NoopLattice.h"
+
+namespace clang::dataflow::nullability {
+
+// The analysis does not need any lattice state of its own yet. Pointer
+// nullability is tracked on `PointerValue`s in the `Environment`. This becomes
+// a real lattice once it needs non-flow-sensitive state and to cache const
+// member call results.
+using PointerNullabilityLattice = NoopLattice;
+
+} // namespace clang::dataflow::nullability
+
+#endif // CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITYLATTICE_H
diff --git a/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityMatchers.h b/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityMatchers.h
new file mode 100644
index 00000000000000..32793c2e775ba6
--- /dev/null
+++ b/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityMatchers.h
@@ -0,0 +1,33 @@
+//===-- PointerNullabilityMatchers.h - AST matchers -------------*- 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 CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITYMATCHERS_H
+#define CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITYMATCHERS_H
+
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullability.h"
+
+namespace clang::dataflow::nullability {
+
+AST_MATCHER(QualType, isSupportedPointer) {
+  return isSupportedPointerType(Node);
+}
+
+AST_MATCHER(QualType, isSupportedRawPointer) {
+  return isSupportedRawPointerType(Node);
+}
+
+ast_matchers::internal::Matcher<Stmt> isPointerExpr();
+ast_matchers::internal::Matcher<Stmt> isNullPointerLiteral();
+ast_matchers::internal::Matcher<Stmt> isAddrOf();
+
+} // namespace clang::dataflow::nullability
+
+#endif // CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_POINTERNULLABILITYMATCHERS_H
diff --git a/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/ValueTransferer.h b/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/ValueTransferer.h
new file mode 100644
index 00000000000000..53fc38571f3a42
--- /dev/null
+++ b/clang/include/clang/Analysis/FlowSensitive/Models/Nullability/ValueTransferer.h
@@ -0,0 +1,39 @@
+//===-- ValueTransferer.h - Value nullability transfer ----------*- 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 CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_VALUETRANSFERER_H
+#define CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_VALUETRANSFERER_H
+
+#include "clang/AST/Expr.h"
+#include "clang/Analysis/FlowSensitive/CFGMatchSwitch.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/MatchSwitch.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityLattice.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+
+namespace clang::dataflow::nullability {
+
+// Returns a switch over CFG elements that can be used to transfer
+// (flow-sensitive) value properties, i.e. to update the analysis state to
+// account for the impact of the CFG element.
+CFGMatchSwitch<TransferState<PointerNullabilityLattice>> buildValueTransferer();
+
+// If `E` is already associated with a `PointerValue`, returns it.
+// Otherwise, associates a newly created `PointerValue` with `E` and returns it.
+// Returns null iff `E` is not a raw pointer expression.
+PointerValue *ensureRawPointerHasValue(const Expr *E, Environment &Env);
+
+// Initialize the null state of `PointerVal` based on the nullability of the
+// type of `E`.
+void initPointerFromTypeNullability(
+    PointerValue &PointerVal, const Expr *E,
+    TransferState<PointerNullabilityLattice> &State);
+
+} // namespace clang::dataflow::nullability
+
+#endif // CLANG_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_VALUETRANSFERER_H
diff --git a/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt b/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt
index 41ab2c6fa786c5..773a3d0da6f0bf 100644
--- a/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt
+++ b/clang/lib/Analysis/FlowSensitive/Models/CMakeLists.txt
@@ -12,3 +12,5 @@ add_clang_library(clangAnalysisFlowSensitiveModels
   clangASTMatchers
   clangBasic
   )
+
+add_subdirectory(Nullability)
diff --git a/clang/lib/Analysis/FlowSensitive/Models/Nullability/CMakeLists.txt b/clang/lib/Analysis/FlowSensitive/Models/Nullability/CMakeLists.txt
new file mode 100644
index 00000000000000..88b157f5efb241
--- /dev/null
+++ b/clang/lib/Analysis/FlowSensitive/Models/Nullability/CMakeLists.txt
@@ -0,0 +1,17 @@
+set(LLVM_LINK_COMPONENTS
+  Support
+  )
+
+add_clang_library(clangAnalysisFlowSensitiveNullability
+  PointerNullability.cpp
+  PointerNullabilityAnalysis.cpp
+  PointerNullabilityMatchers.cpp
+  ValueTransferer.cpp
+
+  LINK_LIBS
+  clangAnalysis
+  clangAnalysisFlowSensitive
+  clangAST
+  clangASTMatchers
+  clangBasic
+  )
diff --git a/clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullability.cpp b/clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullability.cpp
new file mode 100644
index 00000000000000..e485ce2036c976
--- /dev/null
+++ b/clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullability.cpp
@@ -0,0 +1,174 @@
+//===-- PointerNullability.cpp - Pointer nullability properties -*- 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/Analysis/FlowSensitive/Models/Nullability/PointerNullability.h"
+#include "clang/AST/Type.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/Formula.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/Specifiers.h"
+#include "llvm/ADT/StringRef.h"
+#include <cassert>
+#include <optional>
+
+namespace clang::dataflow::nullability {
+
+/// The nullness information of a pointer is represented by two properties
+/// which indicate if its source was nullable, and if its value is null.
+constexpr llvm::StringLiteral kFromNullable = "from_nullable";
+constexpr llvm::StringLiteral kNull = "is_null";
+
+bool isSupportedPointerType(QualType T) { return isSupportedRawPointerType(T); }
+
+bool isSupportedRawPointerType(QualType T) {
+  return T.getCanonicalType()->isPointerType();
+}
+
+PointerValue *getRawPointerValue(const Expr *PointerExpr,
+                                 const Environment &Env) {
+  return Env.get<PointerValue>(*PointerExpr);
+}
+
+PointerValue *getPointerValue(const Expr *PointerExpr, const Environment &Env) {
+  return getRawPointerValue(PointerExpr, Env);
+}
+
+bool hasPointerNullState(const PointerValue &PointerVal) {
+  return PointerVal.getProperty(kFromNullable) != nullptr &&
+         PointerVal.getProperty(kNull) != nullptr;
+}
+
+PointerNullState getPointerNullState(const PointerValue &PointerVal) {
+  Value *FromNullableProp = PointerVal.getProperty(kFromNullable);
+  Value *NullProp = PointerVal.getProperty(kNull);
+
+  assert(FromNullableProp != nullptr && NullProp != nullptr &&
+         "PointerVal is missing null state!");
+
+  return {
+      isa<TopBoolValue>(FromNullableProp)
+          ? nullptr
+          : &cast<BoolValue>(FromNullableProp)->formula(),
+      isa<TopBoolValue>(NullProp) ? nullptr
+                                  : &cast<BoolValue>(NullProp)->formula(),
+  };
+}
+
+static bool tryCreatePointerNullState(PointerValue &PointerVal, Arena &A,
+                                      const Formula *FromNullable = nullptr,
+                                      const Formula *IsNull = nullptr) {
+  if (hasPointerNullState(PointerVal))
+    return false;
+  if (!FromNullable)
+    FromNullable = &A.makeAtomRef(A.makeAtom());
+  if (!IsNull)
+    IsNull = &A.makeAtomRef(A.makeAtom());
+  PointerVal.setProperty(kFromNullable, A.makeBoolValue(*FromNullable));
+  PointerVal.setProperty(kNull, A.makeBoolValue(*IsNull));
+  return true;
+}
+
+void initPointerNullState(PointerValue &PointerVal,
+                          DataflowAnalysisContext &Ctx,
+                          std::optional<NullabilityKind> Source) {
+  auto &A = Ctx.arena();
+  tryCreatePointerNullState(
+      PointerVal, A,
+      Source ? &A.makeLiteral(*Source == NullabilityKind::Nullable) : nullptr,
+      Source == NullabilityKind::NonNull ? &A.makeLiteral(false) : nullptr);
+}
+
+void initPointerNullState(PointerValue &PointerVal,
+                          DataflowAnalysisContext &Ctx,
+                          PointerNullState State) {
+  assert(!hasPointerNullState(PointerVal));
+
+  auto &A = Ctx.arena();
+
+  // Internally, we encode "top" as `TopBoolValue`.
+  BoolValue &FromNullable = State.FromNullable != nullptr
+                                ? A.makeBoolValue(*State.FromNullable)
+                                : A.makeTopValue();
+  BoolValue &IsNull = State.IsNull != nullptr ? A.makeBoolValue(*State.IsNull)
+                                              : A.makeTopValue();
+  PointerVal.setProperty(kFromNullable, FromNullable);
+  PointerVal.setProperty(kNull, IsNull);
+}
+
+void initNullPointer(PointerValue &PointerVal, DataflowAnalysisContext &Ctx) {
+  tryCreatePointerNullState(PointerVal, Ctx.arena(),
+                            /*FromNullable=*/&Ctx.arena().makeLiteral(true),
+                            /*IsNull=*/&Ctx.arena().makeLiteral(true));
+}
+
+bool isNullable(PointerNullState PointerNullState, const Environment &Env) {
+  auto &A = Env.getDataflowAnalysisContext().arena();
+  auto [FromNullable, Null] = PointerNullState;
+
+  // A value is nullable if either of two things is true:
+  // - The value is provably null under satisfiable flow conditions
+  //   (a value from an unknown source becomes nullable if provably null)
+  // - We got it from a nullable source and it may be actually null
+  //   (if a value from a nullable source was checked, it's not nullable)
+  //
+  // Notably, a value from an unknown source that may be null, but is not
+  // provably null, is not considered nullable.
+  // Values from non-null sources are never considered nullable because being
+  // able to prove them null can only occur under unsatisfiable flow conditions.
+  if (Null) {
+    if (Null->isLiteral(false))
+      return false;
+
+    if (Env.proves(*Null)) {
+      // If we're in an environment with false flow conditions, we can prove
+      // anything, but don't want to consider this value Nullable and end up
+      // producing diagnostics in unreachable code.
+      if (Env.proves(A.makeLiteral(false)))
+        return false;
+      return true;
+    }
+  }
+
+  const Formula *NullableAndMaybeNull = &A.makeLiteral(true);
+  if (FromNullable)
+    NullableAndMaybeNull = &A.makeAnd(*NullableAndMaybeNull, *FromNullable);
+  if (Null)
+    NullableAndMaybeNull = &A.makeAnd(*NullableAndMaybeNull, *Null);
+
+  return Env.allows(*NullableAndMaybeNull);
+}
+
+bool isNullable(const PointerValue &PointerVal, const Environment &Env) {
+  return isNullable(getPointerNullState(PointerVal), Env);
+}
+
+NullabilityKind getNullability(PointerNullState PointerNullState,
+                               const Environment &Env) {
+  auto &A = Env.getDataflowAnalysisContext().arena();
+  if (auto *Null = PointerNullState.IsNull) {
+    if (Env.proves(A.makeNot(*Null)))
+      return NullabilityKind::NonNull;
+  }
+  return isNullable(PointerNullState, Env) ? NullabilityKind::Nullable
+                                           : NullabilityKind::Unspecified;
+}
+
+NullabilityKind getNullability(const PointerValue &PointerVal,
+                               const Environment &Env) {
+  return getNullability(getPointerNullState(PointerVal), Env);
+}
+
+NullabilityKind getNullability(const Expr *E, const Environment &Env) {
+  if (PointerValue *P = getPointerValue(E, Env))
+    return getNullability(*P, Env);
+  return NullabilityKind::Unspecified;
+}
+
+} // namespace clang::dataflow::nullability
diff --git a/clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityAnalysis.cpp b/clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityAnalysis.cpp
new file mode 100644
index 00000000000000..49987dc087890f
--- /dev/null
+++ b/clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityAnalysis.cpp
@@ -0,0 +1,136 @@
+//===-- PointerNullabilityAnalysis.cpp - Nullability analysis ---*- 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/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityAnalysis.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Type.h"
+#include "clang/Analysis/CFG.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/Formula.h"
+#include "clang/Analysis/FlowSensitive/MatchSwitch.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullability.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityLattice.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/ValueTransferer.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Basic/LLVM.h"
+#include <cassert>
+#include <optional>
+
+namespace clang::dataflow::nullability {
+
+// If `Elt` is an expression of raw pointer type, ensures that it has a
+// `PointerValue` associated with it. Also ensure that it has nullability
+// state.
+static void ensureRawPointerHasValueAndNullability(
+    const CFGElement &Elt, Environment &Env,
+    TransferState<PointerNullabilityLattice> &State) {
+  std::optional<CFGStmt> S = Elt.getAs<CFGStmt>();
+  if (!S)
+    return;
+
+  const Expr *E = dyn_cast<Expr>(S->getStmt());
+  if (!E)
+    return;
+
+  if (PointerValue *PointerVal = ensureRawPointerHasValue(E, Env)) {
+    if (!hasPointerNullState(*PointerVal)) {
+      initPointerFromTypeNullability(*PointerVal, E, State);
+    }
+  }
+}
+
+PointerNullabilityAnalysis::PointerNullabilityAnalysis(ASTContext &Context,
+                                                       Environment &Env)
+    : DataflowAnalysis<PointerNullabilityAnalysis, PointerNullabilityLattice>(
+          Context),
+      ValueTransferer(buildValueTransferer()) {}
+
+void PointerNullabilityAnalysis::transfer(const CFGElement &Elt,
+                                          PointerNullabilityLattice &Lattice,
+                                          Environment &Env) {
+  TransferState<PointerNullabilityLattice> State(Lattice, Env);
+
+  ValueTransferer(Elt, getASTContext(), State);
+  ensureRawPointerHasValueAndNullability(Elt, Env, State);
+}
+
+static const Formula *mergeFormulas(const Formula *Bool1,
+                                    const Environment &Env1,
+                                    const Formula *Bool2,
+                                    const Environment &Env2,
+                                    Environment &MergedEnv) {
+  if (Bool1 == Bool2)
+    return Bool1;
+
+  if (Bool1 == nullptr && Bool2 == nullptr)
+    return nullptr;
+
+  Arena &A = MergedEnv.arena();
+  // If one side is Top (unconstrained), replace it with a fresh atom, which is
+  // still unconstrained. Analogous to unpacking TopBoolValues in the framework.
+  if (Bool1 == nullptr)
+    Bool1 = &A.makeAtomRef(A.makeAtom());
+  if (Bool2 == nullptr)
+    Bool2 = &A.makeAtomRef(A.makeAtom());
+
+  // If `Bool1` and `Bool2` are constrained to the same true / false value,
+  // return that literal directly rather than delegating to `joinBoolValues`.
+  // Otherwise, in the SAT bool model, the framework will allocate a fresh atom
+  // and flow-condition constraint).
+  if (Env1.proves(*Bool1)) {
+    if (Env2.proves(*Bool2))
+      return &A.makeLiteral(true);
+  } else if (Env1.proves(A.makeNot(*Bool1)) && Env2.proves(A.makeNot(*Bool2))) {
+    return &A.makeLiteral(false);
+  }
+
+  // Otherwise, let the boolean model decide how to join the two values (e.g.,
+  // the SAT model uses information about which path was taken to associate the
+  // result with `Bool1` and `Bool2`).
+  return &MergedEnv
+              .joinBoolValues(A.makeBoolValue(*Bool1), Env1,
+                              A.makeBoolValue(*Bool2), Env2)
+              .formula();
+}
+
+void PointerNullabilityAnalysis::join(QualType Type, const Value &Val1,
+                                      const Environment &Env1,
+                                      const Value &Val2,
+                                      const Environment &Env2, Value &MergedVal,
+                                      Environment &MergedEnv) {
+  if (!isSupportedRawPointerType(Type))
+    return;
+
+  if (!hasPointerNullState(cast<PointerValue>(Val1)) ||
+      !hasPointerNullState(cast<PointerValue>(Val2))) {
+    // It can happen that we merge pointers without null state, if either or
+    // both of the pointers has not appeared in an expression (and has not
+    // otherwise been initialized with nullability properties) before the merge.
+    // When the merged value appears in an expression, `transferPointer` will
+    // take care of initializing it with nullability properties.
+    return;
+  }
+
+  PointerNullState Nullability1 = getPointerNullState(cast<PointerValue>(Val1));
+  PointerNullState Nullability2 = getPointerNullState(cast<PointerValue>(Val2));
+
+  const Formula *FromNullable =
+      mergeFormulas(Nullability1.FromNullable, Env1, Nullability2.FromNullable,
+                    Env2, MergedEnv);
+  const Formula *Null = mergeFormulas(Nullability1.IsNull, Env1,
+                                      Nullability2.IsNull, Env2, MergedEnv);
+
+  initPointerNullState(cast<PointerValue>(MergedVal),
+                       MergedEnv.getDataflowAnalysisContext(),
+                       {FromNullable, Null});
+}
+
+} // namespace clang::dataflow::nullability
diff --git a/clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityMatchers.cpp b/clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityMatchers.cpp
new file mode 100644
index 00000000000000..326230f43f2832
--- /dev/null
+++ b/clang/lib/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityMatchers.cpp
@@ -0,0 +1,34 @@
+//===-- PointerNullabilityMatchers.cpp - AST matchers -----------*- 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/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityMatchers.h"
+#include "clang/AST/OperationKinds.h"
+#include "clang/AST/Stmt.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+namespace clang::dataflow::nullability {
+
+using ast_matchers::anyOf;
+using ast_matchers::expr;
+using ast_matchers::hasCastKind;
+using ast_matchers::hasOperatorName;
+using ast_matchers::hasType;
+using ast_matchers::implicitCastExpr;
+using ast_matchers::unaryOperator;
+using ast_matchers::internal::Matcher;
+
+Matcher<Stmt> isPointerExpr() { return expr(hasType(isSupportedRawPointer())); }
+
+Matcher<Stmt> isNullPointerLiteral() {
+  return implicitCastExpr(anyOf(hasCastKind(CK_NullToPointer),
+                                hasCastKind(CK_NullToMemberPointer)));
+}
+
+Matcher<Stmt> isAddrOf() { return unaryOperator(hasOperatorName("&")); }
+
+} // namespace clang::dataflow::nullability
diff --git a/clang/lib/Analysis/FlowSensitive/Models/Nullability/ValueTransferer.cpp b/clang/lib/Analysis/FlowSensitive/Models/Nullability/ValueTransferer.cpp
new file mode 100644
index 00000000000000..63495fe2a87196
--- /dev/null
+++ b/clang/lib/Analysis/FlowSensitive/Models/Nullability/ValueTransferer.cpp
@@ -0,0 +1,176 @@
+//===-- ValueTransferer.cpp - Value nullability transfer --------*- 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/Analysis/FlowSensitive/Models/Nullability/ValueTransferer.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/OperationKinds.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Analysis/FlowSensitive/CFGMatchSwitch.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/MatchSwitch.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullability.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityLattice.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityMatchers.h"
+#include "clang/Analysis/FlowSensitive/StorageLocation.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Basic/LLVM.h"
+#include "clang/Basic/Specifiers.h"
+#include <cassert>
+
+namespace clang::dataflow::nullability {
+
+using ast_matchers::MatchFinder;
+
+PointerValue *ensureRawPointerHasValue(const Expr *E, Environment &Env) {
+  if (!isSupportedRawPointerType(E->getType()))
+    return nullptr;
+
+  if (E->isPRValue()) {
+    if (auto *Val = Env.get<PointerValue>(*E))
+      return Val;
+    auto *Val = cast<PointerValue>(Env.createValue(E->getType()));
+    Env.setValue(*E, *Val);
+    return Val;
+  }
+
+  StorageLocation *Loc = Env.getStorageLocation(*E);
+  if (Loc == nullptr) {
+    Loc = &Env.createStorageLocation(*E);
+    Env.setStorageLocation(*E, *Loc);
+  }
+  if (auto *Val = Env.get<PointerValue>(*Loc))
+    return Val;
+  auto *Val = cast<PointerValue>(Env.createValue(E->getType()));
+  Env.setValue(*Loc, *Val);
+  return Val;
+}
+
+static NullabilityKind getPointerTypeNullability(const Expr *E) {
+  return E->getType()->getNullability().value_or(NullabilityKind::Unspecified);
+}
+
+void initPointerFromTypeNullability(
+    PointerValue &PointerVal, const Expr *E,
+    TransferState<PointerNullabilityLattice> &State) {
+  initPointerNullState(PointerVal, State.Env.getDataflowAnalysisContext(),
+                       getPointerTypeNullability(E));
+}
+
+/// If the pointer value stored at `PointerLoc` has any "top" nullability
+/// properties, creates a new pointer value referencing the same location with
+/// the "top" properties unpacked into fresh atoms. Returns:
+/// -  The unpacked pointer value if unpacking took place.
+/// -  The original pointer value if no unpacking took place.
+/// -  Null if `PointerLoc` is not associated with a value.
+/// This is analogous to the unpacking done on `TopBoolValue`s in the framework.
+static PointerValue *unpackPointerValue(StorageLocation &PointerLoc,
+                                        Environment &Env) {
+  auto *PointerVal = Env.get<PointerValue>(PointerLoc);
+  if (!PointerVal)
+    return nullptr;
+
+  PointerNullState NullState = getPointerNullState(*PointerVal);
+  if (NullState.FromNullable && NullState.IsNull)
+    return PointerVal;
+
+  auto &A = Env.getDataflowAnalysisContext().arena();
+
+  if (NullState.FromNullable == nullptr)
+    NullState.FromNullable = &A.makeAtomRef(A.makeAtom());
+  if (NullState.IsNull == nullptr)
+    NullState.IsNull = &A.makeAtomRef(A.makeAtom());
+
+  auto &NewPointerVal = Env.create<PointerValue>(PointerVal->getPointeeLoc());
+  initPointerNullState(NewPointerVal, Env.getDataflowAnalysisContext(),
+                       NullState);
+  Env.setValue(PointerLoc, NewPointerVal);
+
+  return &NewPointerVal;
+}
+
+static void
+transferNullPointer(const Expr *NullPointer, const MatchFinder::MatchResult &,
+                    TransferState<PointerNullabilityLattice> &State) {
+  if (auto *PointerVal = ensureRawPointerHasValue(NullPointer, State.Env)) {
+    initNullPointer(*PointerVal, State.Env.getDataflowAnalysisContext());
+  }
+}
+
+static void
+transferNotNullPointer(const Expr *NotNullPointer,
+                       const MatchFinder::MatchResult &,
+                       TransferState<PointerNullabilityLattice> &State) {
+  if (auto *PointerVal = ensureRawPointerHasValue(NotNullPointer, State.Env)) {
+    initPointerNullState(*PointerVal, State.Env.getDataflowAnalysisContext(),
+                         NullabilityKind::NonNull);
+  }
+}
+
+static void transferPointer(const Expr *PointerExpr,
+                            const MatchFinder::MatchResult &Result,
+                            TransferState<PointerNullabilityLattice> &State) {
+  auto *PointerVal = ensureRawPointerHasValue(PointerExpr, State.Env);
+  if (!PointerVal)
+    return;
+
+  // A pointer bitcast is null iff its operand is null, so seed the result
+  // pointer's null-state from the operand *before* falling back to type-based
+  // initialization below. This preserves the operand's flow-sensitive
+  // null-state across the cast.
+  //
+  // We copy only the null-state and keep the result pointer's own pointee
+  // storage location, since the operand and result pointee types can differ
+  // across a bitcast (e.g. `void*` -> `T*`, or base -> derived).
+  if (const auto *Cast = dyn_cast<CastExpr>(PointerExpr);
+      Cast &&
+      (Cast->getCastKind() == CK_BitCast ||
+       Cast->getCastKind() == CK_LValueBitCast) &&
+      isSupportedRawPointerType(Cast->getSubExpr()->getType()) &&
+      isSupportedRawPointerType(Cast->getType()) &&
+      !hasPointerNullState(*PointerVal)) {
+    if (const PointerValue *SrcVal =
+            getRawPointerValue(Cast->getSubExpr(), State.Env);
+        SrcVal != nullptr && hasPointerNullState(*SrcVal)) {
+      initPointerNullState(*PointerVal, State.Env.getDataflowAnalysisContext(),
+                           getPointerNullState(*SrcVal));
+    }
+  }
+
+  initPointerFromTypeNullability(*PointerVal, PointerExpr, State);
+
+  if (const auto *Cast = dyn_cast<CastExpr>(PointerExpr);
+      Cast && Cast->getCastKind() == CK_LValueToRValue) {
+    // Forward the modeled `PointerValue` from the glvalue sub-expression's
+    // storage location. The operand and result share the same pointee type
+    // here, so forwarding the whole value is safe.
+    if (StorageLocation *Loc =
+            State.Env.getStorageLocation(*Cast->getSubExpr())) {
+      if (PointerValue *Val = unpackPointerValue(*Loc, State.Env)) {
+        State.Env.setValue(*PointerExpr, *Val);
+      }
+    }
+  }
+}
+
+CFGMatchSwitch<TransferState<PointerNullabilityLattice>>
+buildValueTransferer() {
+  // The value transfer functions must establish:
+  // - if we're transferring over an Expr
+  // - and the Expr has a supported pointer type
+  // - and the Expr's value is modeled by the framework (or this analysis)
+  // - then the PointerValue has nullability properties (is_null/from_nullable)
+  return CFGMatchSwitchBuilder<TransferState<PointerNullabilityLattice>>()
+      // Handles initialization of the null states of pointers.
+      .CaseOfCFGStmt<Expr>(isAddrOf(), transferNotNullPointer)
+      .CaseOfCFGStmt<Expr>(isNullPointerLiteral(), transferNullPointer)
+      .CaseOfCFGStmt<Expr>(isPointerExpr(), transferPointer)
+      .Build();
+}
+
+} // namespace clang::dataflow::nullability
diff --git a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
index 8dae4d0c3282b2..bfee373993606c 100644
--- a/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
+++ b/clang/unittests/Analysis/FlowSensitive/CMakeLists.txt
@@ -49,3 +49,5 @@ add_clang_unittest(ClangAnalysisFlowSensitiveTests
   FrontendOpenMP
   Support
   )
+
+add_subdirectory(Models/Nullability)
diff --git a/clang/unittests/Analysis/FlowSensitive/Models/Nullability/AssignmentTest.cpp b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/AssignmentTest.cpp
new file mode 100644
index 00000000000000..6f42e787380e97
--- /dev/null
+++ b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/AssignmentTest.cpp
@@ -0,0 +1,184 @@
+//===-- AssignmentTest.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
+//
+//===----------------------------------------------------------------------===//
+//
+// Tests that pointers have the expected nullability (Nullable, Nonnull,
+// Unspecified) after initialization and assignment. The tests check the
+// analysis state directly (vs tests for emitted diagnostics).
+//
+//===----------------------------------------------------------------------===//
+
+#include "CheckNullabilityState.h"
+#include "clang/Basic/Specifiers.h"
+#include "gtest/gtest.h"
+
+namespace clang::dataflow::nullability {
+namespace {
+
+TEST(NullabilityAssignmentTest, AddrOf) {
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target() {
+      int local = 0;
+      int *target_p = &local;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::NonNull);
+}
+
+TEST(NullabilityAssignmentTest, NullPointer) {
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target() {
+      int *target_p = nullptr;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target() {
+      int *target_p = 0;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+  namespace std {
+    using nullptr_t = decltype(nullptr);
+}
+    void target(std::nullptr_t null_val) {
+      int *target_p = null_val;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+}
+
+TEST(NullabilityAssignmentTest, AssignFromAnnotatedPointer) {
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * _Nonnull nonnull_p) {
+      int *target_p = nonnull_p;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::NonNull);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * _Nullable nullable_p) {
+      int *target_p = nullable_p;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int *unknown_p) {
+      int *target_p = unknown_p;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Unspecified);
+}
+
+TEST(NullabilityAssignmentTest, AssignmentOverwrite) {
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * _Nonnull nonnull_p) {
+      int *target_p = nullptr;
+      target_p = nonnull_p;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::NonNull);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * _Nonnull nonnull_p) {
+      int *target_p = nonnull_p;
+      target_p = nullptr;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * unspecified_p) {
+      int *target_p = nullptr;
+      target_p = unspecified_p;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Unspecified);
+}
+
+TEST(NullabilityAssignmentTest, AssignFromAnnotatedTypeAlias) {
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    using NonnullPtr = int *_Nonnull;
+    void target(NonnullPtr nonnull_p) {
+      int *target_p = nonnull_p;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::NonNull);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    typedef int* _Nonnull NonnullPtr;
+    void target(NonnullPtr nonnull_p) {
+      int *target_p = nonnull_p;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::NonNull);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    using IntPtr = int *;
+    void target(_Nullable IntPtr nullable_p) {
+      int *target_p = nullable_p;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+}
+
+TEST(NullabilityAssignmentTest, AssignFromInnerPointerType) {
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * _Nonnull * _Nonnull pp) {
+      int *target_p = *pp;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::NonNull);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * _Nullable * _Nonnull pp) {
+      int *target_p = *pp;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int** _Nonnull pp) {
+      int *target_p = *pp;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Unspecified);
+}
+
+TEST(NullabilityAssignmentTest, BitCast) {
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int local) {
+      void *v = &local;
+      int *target_p = static_cast<int *>(v);
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::NonNull);
+}
+
+} // namespace
+} // namespace clang::dataflow::nullability
diff --git a/clang/unittests/Analysis/FlowSensitive/Models/Nullability/CMakeLists.txt b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/CMakeLists.txt
new file mode 100644
index 00000000000000..b3779b0a2bf139
--- /dev/null
+++ b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/CMakeLists.txt
@@ -0,0 +1,24 @@
+add_clang_unittest(ClangAnalysisFlowSensitiveNullabilityTests
+  AssignmentTest.cpp
+  CheckNullabilityState.cpp
+  JoinTest.cpp
+  PointerNullabilityTest.cpp
+  CLANG_LIBS
+  clangAST
+  clangASTMatchers
+  clangAnalysis
+  clangAnalysisFlowSensitive
+  clangAnalysisFlowSensitiveNullability
+  clangBasic
+  clangFrontend
+  clangLex
+  clangSerialization
+  clangTooling
+  LINK_LIBS
+  clangTesting
+  LLVMTestingAnnotations
+  LLVMTestingSupport
+  LLVM_COMPONENTS
+  FrontendOpenMP
+  Support
+  )
diff --git a/clang/unittests/Analysis/FlowSensitive/Models/Nullability/CheckNullabilityState.cpp b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/CheckNullabilityState.cpp
new file mode 100644
index 00000000000000..2bd376aa0f5269
--- /dev/null
+++ b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/CheckNullabilityState.cpp
@@ -0,0 +1,51 @@
+//===-- CheckNullabilityState.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 "CheckNullabilityState.h"
+#include "../../TestingSupport.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
+#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullability.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityAnalysis.h"
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityLattice.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Basic/Specifiers.h"
+#include "llvm/ADT/StringMap.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Error.h"
+#include "llvm/Testing/Support/Error.h"
+#include "gtest/gtest.h"
+#include <utility>
+
+namespace clang::dataflow::nullability {
+
+NullabilityKind evaluateNullabilityAtCheck(llvm::StringRef Code) {
+  NullabilityKind Result = NullabilityKind::Unspecified;
+  llvm::Error Err = dataflow::test::checkDataflow<PointerNullabilityAnalysis>(
+      dataflow::test::AnalysisInputs<PointerNullabilityAnalysis>(
+          Code, ast_matchers::hasName("target"),
+          [](ASTContext &Ctx, Environment &Env) {
+            return PointerNullabilityAnalysis(Ctx, Env);
+          })
+          .withASTBuildArgs({"-std=c++17"}),
+      [&Result](const llvm::StringMap<
+                    DataflowAnalysisState<PointerNullabilityLattice>> &Results,
+                const dataflow::test::AnalysisOutputs &AO) {
+        const Environment &Env =
+            dataflow::test::getEnvironmentAtAnnotation(Results, "check");
+        Result = getNullability(dataflow::test::getValueForDecl<PointerValue>(
+                                    AO.ASTCtx, Env, "target_p"),
+                                Env);
+      });
+  EXPECT_THAT_ERROR(std::move(Err), llvm::Succeeded());
+  return Result;
+}
+
+} // namespace clang::dataflow::nullability
diff --git a/clang/unittests/Analysis/FlowSensitive/Models/Nullability/CheckNullabilityState.h b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/CheckNullabilityState.h
new file mode 100644
index 00000000000000..abd0b22f4524b2
--- /dev/null
+++ b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/CheckNullabilityState.h
@@ -0,0 +1,24 @@
+//===-- CheckNullabilityState.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 CLANG_UNITTESTS_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_CHECKNULLABILITYSTATE_H
+#define CLANG_UNITTESTS_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_CHECKNULLABILITYSTATE_H
+
+#include "clang/Basic/Specifiers.h"
+#include "llvm/ADT/StringRef.h"
+
+namespace clang::dataflow::nullability {
+
+/// Runs `PointerNullabilityAnalysis` on the function `target` in `Code` and
+/// returns the nullability of the pointer variable `target_p` at the program
+/// point marked `// [[check]]`.
+NullabilityKind evaluateNullabilityAtCheck(llvm::StringRef Code);
+
+} // namespace clang::dataflow::nullability
+
+#endif // CLANG_UNITTESTS_ANALYSIS_FLOWSENSITIVE_MODELS_NULLABILITY_CHECKNULLABILITYSTATE_H
diff --git a/clang/unittests/Analysis/FlowSensitive/Models/Nullability/JoinTest.cpp b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/JoinTest.cpp
new file mode 100644
index 00000000000000..d3051dc01f1132
--- /dev/null
+++ b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/JoinTest.cpp
@@ -0,0 +1,155 @@
+//===-- JoinTest.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
+//
+//===----------------------------------------------------------------------===//
+//
+// Tests that pointers have the expected nullability (Nullable, Nonnull,
+// Unspecified) where control flow joins (e.g. after an `if`).  The tests check
+// the analysis state directly (vs tests for emitted diagnostics).
+//
+//===----------------------------------------------------------------------===//
+
+#include "CheckNullabilityState.h"
+#include "clang/Basic/Specifiers.h"
+#include "gtest/gtest.h"
+
+namespace clang::dataflow::nullability {
+namespace {
+
+TEST(NullabilityJoinTest, JoinSameNullabilityFromAssignments) {
+  // Joining when two branches have the same nullability.
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * _Nonnull p1, int * _Nonnull p2, bool b) {
+      int *target_p = p1;
+      if (b) {
+        target_p = p2;
+      }
+      (void)0;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::NonNull);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * _Nullable p1, int * _Nullable p2, bool b) {
+      int *target_p = p1;
+      if (b) {
+        target_p = p2;
+      }
+      (void)0;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(bool b) {
+      int *target_p = nullptr;
+      if (b) {
+        target_p = 0;
+      }
+      (void)0;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * p1, int *  p2, bool b) {
+      int *target_p = p1;
+      if (b) {
+        target_p = p2;
+      }
+      (void)0;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Unspecified);
+}
+
+TEST(NullabilityJoinTest, JoinDifferentNullabilityFromAssignments) {
+  // Joining when two branches have the different nullability.
+  // Nonnull and nullable => nullable.
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * _Nonnull nonnull_p, int * _Nullable nullable_p, bool b) {
+      int *target_p = nonnull_p;
+      if (b) {
+        target_p = nullable_p;
+      }
+      (void)0;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  // Nonnull and nullptr
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * _Nonnull nonnull_p, bool b) {
+      int *target_p = nonnull_p;
+      if (b) {
+        target_p = nullptr;
+      }
+      (void)0;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  // Nullable and nullptr
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int * _Nullable nullable_p, bool b) {
+      int *target_p = nullable_p;
+      if (b) {
+        target_p = nullptr;
+      }
+      (void)0;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  // Unspecified and nullable
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int *unknown_p, int * _Nullable nullable_p, bool b) {
+      int *target_p = unknown_p;
+      if (b) {
+        target_p = nullable_p;
+      }
+      (void)0;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  // Unspecified and nullptr
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int *unknown_p, bool b) {
+      int *target_p = unknown_p;
+      if (b) {
+        target_p = nullptr;
+      }
+      (void)0;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Nullable);
+
+  // Unspecified and nonnull => unspecified.
+  EXPECT_EQ(evaluateNullabilityAtCheck(R"cc(
+    void target(int *unknown_p, int * _Nonnull nonnull_p, bool b) {
+      int *target_p = unknown_p;
+      if (b) {
+        target_p = nonnull_p;
+      }
+      (void)0;
+      // [[check]]
+    }
+  )cc"),
+            NullabilityKind::Unspecified);
+}
+
+} // namespace
+} // namespace clang::dataflow::nullability
diff --git a/clang/unittests/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityTest.cpp b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityTest.cpp
new file mode 100644
index 00000000000000..f0eeeb2b18d4c8
--- /dev/null
+++ b/clang/unittests/Analysis/FlowSensitive/Models/Nullability/PointerNullabilityTest.cpp
@@ -0,0 +1,134 @@
+//===-- PointerNullabilityTest.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
+//
+// Low-level unit tests for the pointer value null state (IsNull, FromNullable).
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/Analysis/FlowSensitive/Models/Nullability/PointerNullability.h"
+#include "clang/AST/Type.h"
+#include "clang/Analysis/FlowSensitive/Arena.h"
+#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
+#include "clang/Analysis/FlowSensitive/Formula.h"
+#include "clang/Analysis/FlowSensitive/Value.h"
+#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
+#include "clang/Basic/Specifiers.h"
+#include "gtest/gtest.h"
+#include <memory>
+
+namespace clang::dataflow::nullability {
+namespace {
+
+class NullabilityPropertiesTest : public ::testing::Test {
+protected:
+  PointerValue &makePointer(NullabilityKind N) {
+    auto &P = Env.create<PointerValue>(DACtx.createStorageLocation(QualType()));
+    initPointerNullState(P, DACtx, N);
+    return P;
+  }
+
+  PointerValue &makeNullPointer() {
+    auto &P = Env.create<PointerValue>(DACtx.createStorageLocation(QualType()));
+    initNullPointer(P, DACtx);
+    return P;
+  }
+
+  DataflowAnalysisContext DACtx =
+      DataflowAnalysisContext(std::make_unique<WatchedLiteralsSolver>());
+  Environment Env = Environment(DACtx);
+  Arena &A = DACtx.arena();
+};
+
+using IsNullableTest = NullabilityPropertiesTest;
+
+TEST_F(IsNullableTest, NullPtr) {
+  EXPECT_TRUE(isNullable(makeNullPointer(), Env));
+}
+
+TEST_F(IsNullableTest, Nullable) {
+  auto &Nullable = makePointer(NullabilityKind::Nullable);
+  EXPECT_TRUE(isNullable(Nullable, Env));
+}
+
+TEST_F(IsNullableTest, NullableButNotNull) {
+  auto &NullableButNotNull = makePointer(NullabilityKind::Nullable);
+  auto *IsNull = getPointerNullState(NullableButNotNull).IsNull;
+  ASSERT_NE(IsNull, nullptr);
+  Env.assume(A.makeNot(*IsNull));
+
+  EXPECT_FALSE(isNullable(NullableButNotNull, Env));
+}
+
+TEST_F(IsNullableTest, NullableAndNull) {
+  auto &NullableAndNull = makePointer(NullabilityKind::Nullable);
+  auto *IsNull = getPointerNullState(NullableAndNull).IsNull;
+  ASSERT_NE(IsNull, nullptr);
+  Env.assume(*IsNull);
+
+  EXPECT_TRUE(isNullable(NullableAndNull, Env));
+}
+
+TEST_F(IsNullableTest, NonnullAndNotNull) {
+  auto &NonnullAndNotNull = makePointer(NullabilityKind::NonNull);
+  EXPECT_FALSE(isNullable(NonnullAndNotNull, Env));
+
+  auto *IsNull = getPointerNullState(NonnullAndNotNull).IsNull;
+  ASSERT_NE(IsNull, nullptr);
+
+  // `IsNull` should not just be provably false but an actual false literal.
+  ASSERT_EQ(IsNull, &A.makeLiteral(false));
+
+  // Assuming the pointer is non-null is a no-op, but make sure it doesn't
+  // change the result of `isNullable()`.
+  Env.assume(A.makeNot(*IsNull));
+  EXPECT_FALSE(isNullable(NonnullAndNotNull, Env));
+}
+
+TEST_F(IsNullableTest, NonnullAndNull) {
+  // If a pointer comes from a non-null source but is dynamically discovered to
+  // be definitely null, we don't consider it nullable, because we're in an
+  // environment with false flow conditions.
+  auto &NonnullAndNull = makePointer(NullabilityKind::NonNull);
+  auto *IsNull = getPointerNullState(NonnullAndNull).IsNull;
+  ASSERT_NE(IsNull, nullptr);
+  Env.assume(*IsNull);
+
+  EXPECT_FALSE(isNullable(NonnullAndNull, Env));
+}
+
+TEST_F(IsNullableTest, UnknownAndNull) {
+  // If a pointer comes from an unknown source but is dynamically discovered to
+  // be definitely null, we consider it nullable.
+  auto &UnknownAndNull = makePointer(NullabilityKind::Unspecified);
+  auto *IsNull = getPointerNullState(UnknownAndNull).IsNull;
+  ASSERT_NE(IsNull, nullptr);
+  Env.assume(*IsNull);
+
+  EXPECT_TRUE(isNullable(UnknownAndNull, Env));
+}
+
+TEST_F(NullabilityPropertiesTest, InitNullabilityPropertiesWithFormulas) {
+  auto &P = Env.create<PointerValue>(DACtx.createStorageLocation(QualType()));
+
+  Arena &A = DACtx.arena();
+  const Formula &FromNullable = A.makeAtomRef(A.makeAtom());
+  const Formula &IsNull = A.makeAtomRef(A.makeAtom());
+
+  initPointerNullState(P, DACtx, PointerNullState{&FromNullable, &IsNull});
+  ASSERT_EQ(getPointerNullState(P).FromNullable, &FromNullable);
+  ASSERT_EQ(getPointerNullState(P).IsNull, &IsNull);
+}
+
+TEST_F(NullabilityPropertiesTest, InitNullabilityPropertiesWithTop) {
+  auto &P = Env.create<PointerValue>(DACtx.createStorageLocation(QualType()));
+
+  initPointerNullState(P, DACtx, PointerNullState{nullptr, nullptr});
+  ASSERT_EQ(getPointerNullState(P).FromNullable, nullptr);
+  ASSERT_EQ(getPointerNullState(P).IsNull, nullptr);
+}
+
+} // namespace
+} // namespace clang::dataflow::nullability



More information about the cfe-commits mailing list