[llvm] [ADT] Add make_isa_range to filter and downcast a range by type (NFC) (PR #223414)

Florian Hahn via llvm-commits llvm-commits at lists.llvm.org
Wed Sep 16 01:23:12 PDT 2026


https://github.com/fhahn updated https://github.com/llvm/llvm-project/pull/223414

>From 79e7eca09524b9e11d64455e2a61b26d7a483fea Mon Sep 17 00:00:00 2001
From: Florian Hahn <flo at fhahn.com>
Date: Mon, 14 Sep 2026 10:48:33 +0100
Subject: [PATCH 1/3] [ADT] Add make_isa_range to filter and downcast a range
 by type (NFC)

Add a range adaptor that keeps only the elements of a range that isa<T>
holds for, casting each of them to T.

This replaces the common idiom of filtering by type in the loop body

  for (Instruction &I : *BB) {
    auto *PN = dyn_cast<PHINode>(&I);
    if (!PN)
      continue;
    ... use PN ...
  }

with

  for (PHINode &PN : make_isa_range<PHINode>(*BB))
    ... use PN ...

This pattern is quite widespread in the LLVM codebase, and follow-up
commits will migrate use-sites step-by-step.
---
 llvm/include/llvm/ADT/STLExtras.h    | 16 ++++++
 llvm/unittests/ADT/STLExtrasTest.cpp | 76 ++++++++++++++++++++++++++++
 2 files changed, 92 insertions(+)

diff --git a/llvm/include/llvm/ADT/STLExtras.h b/llvm/include/llvm/ADT/STLExtras.h
index 0081ce2da106b..f4532a30aaab7 100644
--- a/llvm/include/llvm/ADT/STLExtras.h
+++ b/llvm/include/llvm/ADT/STLExtras.h
@@ -23,6 +23,7 @@
 #include "llvm/ADT/iterator.h"
 #include "llvm/ADT/iterator_range.h"
 #include "llvm/Config/abi-breaking.h"
+#include "llvm/Support/Casting.h"
 #include "llvm/Support/ErrorHandling.h"
 #include <algorithm>
 #include <cassert>
@@ -556,6 +557,21 @@ make_filter_range(RangeT &&Range, PredicateT Pred) {
   return make_range(FilterIteratorT(B, E, Pred), FilterIteratorT(E, E, Pred));
 }
 
+/// Return a range over \p Range containing only elements for which isa<T>
+/// holds, casting each of them to T. Ranges of pointers yield T *.
+///
+/// Note: as for make_filter_range, the returned range only borrows the
+/// iterators of \p Range. Passing a temporary container is not supported, as
+/// its lifetime is not extended by the returned range; passing a temporary
+/// view, e.g. the result of drop_begin, is fine.
+template <typename T, typename RangeT> auto make_isa_range(RangeT &&Range) {
+  static_assert(std::is_reference_v<decltype(*adl_begin(Range))> ||
+                    std::is_pointer_v<detail::ValueOfRange<RangeT>>,
+                "make_isa_range requires a range of pointers or references");
+  return map_range(make_filter_range(std::forward<RangeT>(Range), IsaPred<T>),
+                   CastTo<T>);
+}
+
 /// A pseudo-iterator adaptor that is designed to implement "early increment"
 /// style loops.
 ///
diff --git a/llvm/unittests/ADT/STLExtrasTest.cpp b/llvm/unittests/ADT/STLExtrasTest.cpp
index 00c062ae1ca29..2e12f818b5049 100644
--- a/llvm/unittests/ADT/STLExtrasTest.cpp
+++ b/llvm/unittests/ADT/STLExtrasTest.cpp
@@ -592,6 +592,82 @@ TEST(STLExtrasTest, MakeFirstSecondRangeADL) {
   EXPECT_THAT(make_second_range(Pairs), ElementsAre(1, 2));
 }
 
+/// Utility classes to setup casting functionality.
+struct Shape {
+  enum ShapeKind { SK_Circle, SK_Square };
+  const ShapeKind Kind;
+  Shape(ShapeKind Kind) : Kind(Kind) {}
+};
+template <Shape::ShapeKind K> struct ShapeImpl : Shape {
+  ShapeImpl() : Shape(K) {}
+  static bool classof(const Shape *S) { return S->Kind == K; }
+};
+struct Circle : ShapeImpl<Shape::SK_Circle> {};
+struct Square : ShapeImpl<Shape::SK_Square> {};
+
+TEST(STLExtrasTest, MakeIsaRangePointers) {
+  Circle C0, C1;
+  Square S;
+  std::vector<Shape *> Shapes = {&C0, &S, &C1};
+
+  auto Circles = make_isa_range<Circle>(Shapes);
+  static_assert(std::is_same_v<decltype(*Circles.begin()), Circle *>);
+  EXPECT_THAT(Circles, ElementsAre(&C0, &C1));
+  EXPECT_THAT(make_isa_range<Square>(Shapes), ElementsAre(&S));
+
+  // Ranges without any element of the requested type are empty.
+  std::vector<Shape *> OnlyCircles = {&C0, &C1};
+  EXPECT_TRUE(make_isa_range<Square>(OnlyCircles).empty());
+
+  // Ranges dereferencing to `Shape *const &`, like ArrayRef, work as well.
+  ArrayRef<Shape *> ShapesRef = Shapes;
+  auto RefCircles = make_isa_range<Circle>(ShapesRef);
+  static_assert(std::is_same_v<decltype(*RefCircles.begin()), Circle *>);
+  EXPECT_THAT(RefCircles, ElementsAre(&C0, &C1));
+
+  // The same holds for ranges returning their elements by value.
+  auto ByValue = map_range(Shapes, [](Shape *S) { return S; });
+  auto ValueCircles = make_isa_range<Circle>(ByValue);
+  static_assert(std::is_same_v<decltype(*ValueCircles.begin()), Circle *>);
+  EXPECT_THAT(ValueCircles, ElementsAre(&C0, &C1));
+
+  // Constness of the elements is preserved.
+  std::vector<const Shape *> ConstShapes = {&C0, &S, &C1};
+  auto ConstCircles = make_isa_range<Circle>(ConstShapes);
+  static_assert(
+      std::is_same_v<decltype(*ConstCircles.begin()), const Circle *>);
+  EXPECT_THAT(ConstCircles, ElementsAre(&C0, &C1));
+}
+
+TEST(STLExtrasTest, MakeIsaRangeReferences) {
+  Circle C0, C1;
+  Square S;
+  std::vector<Shape *> Shapes = {&C0, &S, &C1};
+
+  auto Circles = make_isa_range<Circle>(make_pointee_range(Shapes));
+  static_assert(std::is_same_v<decltype(*Circles.begin()), Circle &>);
+  EXPECT_THAT(map_range(Circles, [](Circle &C) { return &C; }),
+              ElementsAre(&C0, &C1));
+
+  // Constness of the elements is preserved.
+  std::vector<const Shape *> ConstShapes = {&C0, &S, &C1};
+  auto ConstCircles = make_isa_range<Circle>(make_pointee_range(ConstShapes));
+  static_assert(
+      std::is_same_v<decltype(*ConstCircles.begin()), const Circle &>);
+  EXPECT_THAT(map_range(ConstCircles, [](const Circle &C) { return &C; }),
+              ElementsAre(&C0, &C1));
+}
+
+TEST(STLExtrasTest, MakeIsaRangeEarlyIncrement) {
+  Circle C0, C1;
+  Square S;
+  std::list<Shape *> Shapes = {&C0, &S, &C1};
+
+  for (Circle *C : make_early_inc_range(make_isa_range<Circle>(Shapes)))
+    Shapes.remove(C);
+  EXPECT_THAT(Shapes, ElementsAre(&S));
+}
+
 template <typename T> struct Iterator {
   int i = 0;
   T operator*() const { return i; }

>From 0817f42f7be1d07a53a707b60f237628febd5a41 Mon Sep 17 00:00:00 2001
From: Florian Hahn <flo at fhahn.com>
Date: Mon, 14 Sep 2026 16:18:05 +0100
Subject: [PATCH 2/3] !fixup remove unneeded std::forward;

---
 llvm/include/llvm/ADT/STLExtras.h | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/llvm/include/llvm/ADT/STLExtras.h b/llvm/include/llvm/ADT/STLExtras.h
index f4532a30aaab7..017046e4736ba 100644
--- a/llvm/include/llvm/ADT/STLExtras.h
+++ b/llvm/include/llvm/ADT/STLExtras.h
@@ -568,8 +568,7 @@ template <typename T, typename RangeT> auto make_isa_range(RangeT &&Range) {
   static_assert(std::is_reference_v<decltype(*adl_begin(Range))> ||
                     std::is_pointer_v<detail::ValueOfRange<RangeT>>,
                 "make_isa_range requires a range of pointers or references");
-  return map_range(make_filter_range(std::forward<RangeT>(Range), IsaPred<T>),
-                   CastTo<T>);
+  return map_range(make_filter_range(Range, IsaPred<T>), CastTo<T>);
 }
 
 /// A pseudo-iterator adaptor that is designed to implement "early increment"

>From ecc6f55d8e24033800f896d2be3d87240ab2a8d2 Mon Sep 17 00:00:00 2001
From: Florian Hahn <flo at fhahn.com>
Date: Tue, 15 Sep 2026 22:02:14 +0100
Subject: [PATCH 3/3] !fixup support value cast

---
 llvm/include/llvm/ADT/STLExtras.h    |  9 +++--
 llvm/unittests/ADT/STLExtrasTest.cpp | 60 ++++++++++++++++++++++++++++
 2 files changed, 65 insertions(+), 4 deletions(-)

diff --git a/llvm/include/llvm/ADT/STLExtras.h b/llvm/include/llvm/ADT/STLExtras.h
index 017046e4736ba..2d9dc40f7d66f 100644
--- a/llvm/include/llvm/ADT/STLExtras.h
+++ b/llvm/include/llvm/ADT/STLExtras.h
@@ -558,16 +558,17 @@ make_filter_range(RangeT &&Range, PredicateT Pred) {
 }
 
 /// Return a range over \p Range containing only elements for which isa<T>
-/// holds, casting each of them to T. Ranges of pointers yield T *.
+/// holds, casting each of them to T.
 ///
 /// Note: as for make_filter_range, the returned range only borrows the
 /// iterators of \p Range. Passing a temporary container is not supported, as
 /// its lifetime is not extended by the returned range; passing a temporary
 /// view, e.g. the result of drop_begin, is fine.
 template <typename T, typename RangeT> auto make_isa_range(RangeT &&Range) {
-  static_assert(std::is_reference_v<decltype(*adl_begin(Range))> ||
-                    std::is_pointer_v<detail::ValueOfRange<RangeT>>,
-                "make_isa_range requires a range of pointers or references");
+  static_assert(
+      std::is_reference_v<decltype(*adl_begin(Range))> ||
+          !std::is_reference_v<decltype(CastTo<T>(*adl_begin(Range)))>,
+      "make_isa_range would return references into temporary elements");
   return map_range(make_filter_range(Range, IsaPred<T>), CastTo<T>);
 }
 
diff --git a/llvm/unittests/ADT/STLExtrasTest.cpp b/llvm/unittests/ADT/STLExtrasTest.cpp
index 2e12f818b5049..0893e4c92424e 100644
--- a/llvm/unittests/ADT/STLExtrasTest.cpp
+++ b/llvm/unittests/ADT/STLExtrasTest.cpp
@@ -668,6 +668,66 @@ TEST(STLExtrasTest, MakeIsaRangeEarlyIncrement) {
   EXPECT_THAT(Shapes, ElementsAre(&S));
 }
 
+/// A value-typed handle hierarchy that casts by value.
+struct HandleImpl {
+  unsigned Kind;
+};
+
+struct Handle {
+public:
+  Handle(const HandleImpl *Impl = nullptr) : Impl(Impl) {}
+  const HandleImpl *getImpl() const { return Impl; }
+  bool operator==(const Handle &Other) const { return Impl == Other.Impl; }
+
+protected:
+  const HandleImpl *Impl;
+};
+
+struct FooHandle : public Handle {
+  using Handle::Handle;
+  static bool classof(Handle H) { return H.getImpl()->Kind == 0; }
+};
+
+struct BarHandle : public Handle {
+  using Handle::Handle;
+  static bool classof(Handle H) { return H.getImpl()->Kind == 1; }
+};
+} // namespace
+
+namespace llvm {
+/// Casts take and return the handle by value.
+template <typename To, typename From>
+struct CastInfo<To, From,
+                std::enable_if_t<std::is_base_of_v<Handle, std::decay_t<From>>>>
+    : NullableValueCastFailed<To>,
+      DefaultDoCastIfPossible<To, From, CastInfo<To, From>> {
+  static bool isPossible(Handle H) { return To::classof(H); }
+  static To doCast(Handle H) { return To(H.getImpl()); }
+};
+} // namespace llvm
+
+namespace {
+TEST(STLExtrasTest, MakeIsaRangeValueTypes) {
+  HandleImpl FooImpl0 = {0}, BarImpl = {1}, FooImpl1 = {0};
+  std::vector<Handle> Handles = {Handle(&FooImpl0), Handle(&BarImpl),
+                                 Handle(&FooImpl1)};
+
+  // Casting a handle yields a handle by value, not a reference.
+  auto Foos = make_isa_range<FooHandle>(Handles);
+  static_assert(std::is_same_v<decltype(*Foos.begin()), FooHandle>);
+  EXPECT_THAT(Foos, ElementsAre(FooHandle(&FooImpl0), FooHandle(&FooImpl1)));
+  EXPECT_THAT(make_isa_range<BarHandle>(Handles),
+              ElementsAre(BarHandle(&BarImpl)));
+
+  // Ranges that only materialize the handles as temporaries work as well,
+  // because the cast does not refer back to the element.
+  auto ByValue = map_range(Handles, [](Handle H) { return H; });
+  auto ByValueFoos = make_isa_range<FooHandle>(ByValue);
+  static_assert(std::is_same_v<decltype(*ByValueFoos.begin()), FooHandle>);
+  EXPECT_THAT(ByValueFoos,
+              ElementsAre(FooHandle(&FooImpl0), FooHandle(&FooImpl1)));
+}
+
 template <typename T> struct Iterator {
   int i = 0;
   T operator*() const { return i; }



More information about the llvm-commits mailing list