[llvm] Add isa_or_null<> to Casting.h (PR #104682)

via llvm-commits llvm-commits at lists.llvm.org
Sat Aug 17 11:55:49 PDT 2024


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-support

Author: Braden Helmer (bradenhelmer)

<details>
<summary>Changes</summary>

Implements isa_or_null<> as suggested in #<!-- -->50305.

---
Full diff: https://github.com/llvm/llvm-project/pull/104682.diff


3 Files Affected:

- (modified) llvm/docs/ReleaseNotes.rst (+2) 
- (modified) llvm/include/llvm/Support/Casting.h (+7) 
- (modified) llvm/unittests/Support/Casting.cpp (+8) 


``````````diff
diff --git a/llvm/docs/ReleaseNotes.rst b/llvm/docs/ReleaseNotes.rst
index 42c0ad976089f7..f71b145d128b71 100644
--- a/llvm/docs/ReleaseNotes.rst
+++ b/llvm/docs/ReleaseNotes.rst
@@ -180,6 +180,8 @@ Changes to Sanitizers
 Other Changes
 -------------
 
+* A template for 'isa_or_null<>' has been added to the casting operations in support.
+
 External Open Source Projects Using LLVM 19
 ===========================================
 
diff --git a/llvm/include/llvm/Support/Casting.h b/llvm/include/llvm/Support/Casting.h
index 14a32ccd0e0dc9..cb39381285cd7a 100644
--- a/llvm/include/llvm/Support/Casting.h
+++ b/llvm/include/llvm/Support/Casting.h
@@ -683,6 +683,13 @@ template <typename... X, class Y>
   return isa_and_present<X...>(Val);
 }
 
+// isa_or_null<X> - Returns true if the value is null or matches the list of
+// types provided.
+template <typename... To, typename From>
+[[nodiscard]] inline bool isa_or_null(const From &Val) {
+  return !detail::isPresent(Val) || isa<To...>(Val);
+}
+
 /// cast_if_present<X> - Functionally identical to cast, except that a null
 /// value is accepted.
 template <class X, class Y>
diff --git a/llvm/unittests/Support/Casting.cpp b/llvm/unittests/Support/Casting.cpp
index a128cedaf3988d..8fee7d037e3c5b 100644
--- a/llvm/unittests/Support/Casting.cpp
+++ b/llvm/unittests/Support/Casting.cpp
@@ -162,6 +162,14 @@ TEST(CastingTest, isa_and_nonnull) {
   EXPECT_FALSE(isa_and_nonnull<foo>(fub()));
 }
 
+TEST(CastingTest, isa_or_null) {
+  EXPECT_TRUE(isa_or_null<foo>(B1));
+  EXPECT_TRUE(isa_or_null<foo>(B2));
+  EXPECT_TRUE(isa_or_null<foo>(B3));
+  EXPECT_TRUE(isa_or_null<foo>(B4));
+  EXPECT_TRUE(isa_or_null<foo>(fub()));
+}
+
 TEST(CastingTest, cast) {
   foo &F1 = cast<foo>(B1);
   EXPECT_NE(&F1, null_foo);

``````````

</details>


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


More information about the llvm-commits mailing list