diff --git a/llvm/docs/ProgrammersManual.rst b/llvm/docs/ProgrammersManual.rst --- a/llvm/docs/ProgrammersManual.rst +++ b/llvm/docs/ProgrammersManual.rst @@ -164,6 +164,12 @@ efficient to use the ``InstVisitor`` class to dispatch over the instruction type directly. +``isa_and_nonnull<>``: + The ``isa_and_nonnull<>`` operator works just like the ``isa<>`` operator, + except that it allows for a null pointer as an argument (which it then + returns false). This can sometimes be useful, allowing you to combine several + null checks into one. + ``cast_or_null<>``: The ``cast_or_null<>`` operator works just like the ``cast<>`` operator, except that it allows for a null pointer as an argument (which it then diff --git a/llvm/include/llvm/Support/Casting.h b/llvm/include/llvm/Support/Casting.h --- a/llvm/include/llvm/Support/Casting.h +++ b/llvm/include/llvm/Support/Casting.h @@ -143,6 +143,16 @@ typename simplify_type::SimpleType>::doit(Val); } +// isa_and_nonnull - Functionally identical to isa, except that a null value +// is accepted. +// +template +LLVM_NODISCARD inline bool isa_and_nonnull(const Y &Val) { + if (!Val) + return false; + return isa(Val); +} + //===----------------------------------------------------------------------===// // cast Support Templates //===----------------------------------------------------------------------===// diff --git a/llvm/unittests/Support/Casting.cpp b/llvm/unittests/Support/Casting.cpp --- a/llvm/unittests/Support/Casting.cpp +++ b/llvm/unittests/Support/Casting.cpp @@ -118,6 +118,12 @@ EXPECT_TRUE(isa(B4)); } +TEST(CastingTest, isa_and_nonnull) { + EXPECT_TRUE(isa_and_nonnull(B2)); + EXPECT_TRUE(isa_and_nonnull(B4)); + EXPECT_FALSE(isa_and_nonnull(fub())); +} + TEST(CastingTest, cast) { foo &F1 = cast(B1); EXPECT_NE(&F1, null_foo);