[Mlir-commits] [mlir] [mlir] Support null interface to base conversion (PR #65988)

Markus Böck llvmlistbot at llvm.org
Mon Sep 11 11:10:48 PDT 2023


https://github.com/zero9178 created https://github.com/llvm/llvm-project/pull/65988:

The current implicit conversion operator from an interface to a "base interface" of the interface unconditionally calls `this->getImpl()` which leads to accessing a null pointer if the interface instance is a null instance.

This PR changes the ODS generated interface instance to explicitly check and then return a null interface instance if the `this` instance is a null instance.

>From c0a4dc282c9bb514d0923e0938600eeeb5c53112 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Markus=20B=C3=B6ck?= <markus.boeck02 at gmail.com>
Date: Mon, 11 Sep 2023 20:09:10 +0200
Subject: [PATCH] [mlir] Support null interface to base conversion

The current implicit conversion operator from an interface to a "base interface" of the interface unconditionally calls `this->getImpl()` which leads to accessing a null pointer if the interface instance is a null instance.

This PR changes the ODS generated interface instance to explicitly check and then return a null interface instance if the `this` instance is a null instance.
---
 mlir/tools/mlir-tblgen/OpInterfacesGen.cpp |  1 +
 mlir/unittests/IR/InterfaceTest.cpp        | 13 +++++++++++++
 2 files changed, 14 insertions(+)

diff --git a/mlir/tools/mlir-tblgen/OpInterfacesGen.cpp b/mlir/tools/mlir-tblgen/OpInterfacesGen.cpp
index 65c1e6392b1316e..9672a02cc08f68c 100644
--- a/mlir/tools/mlir-tblgen/OpInterfacesGen.cpp
+++ b/mlir/tools/mlir-tblgen/OpInterfacesGen.cpp
@@ -571,6 +571,7 @@ void InterfaceGenerator::emitInterfaceDecl(const Interface &interface) {
 
     // Allow implicit conversion to the base interface.
     os << "  operator " << baseQualName << " () const {\n"
+       << "    if (!*this) return nullptr;\n"
        << "    return " << baseQualName << "(*this, getImpl()->impl"
        << base.getName() << ");\n"
        << "  }\n\n";
diff --git a/mlir/unittests/IR/InterfaceTest.cpp b/mlir/unittests/IR/InterfaceTest.cpp
index 621a1c5fa18f3f8..5ab4d9a106231a1 100644
--- a/mlir/unittests/IR/InterfaceTest.cpp
+++ b/mlir/unittests/IR/InterfaceTest.cpp
@@ -70,3 +70,16 @@ TEST(InterfaceTest, TestCustomClassOf) {
   EXPECT_FALSE(isa<TestOptionallyImplementedOpInterface>(*op));
   op.erase();
 }
+
+TEST(InterfaceTest, TestImplicitConversion) {
+  MLIRContext context;
+  context.loadDialect<test::TestDialect>();
+
+  TestBaseTypeInterfacePrintTypeB typeB;
+  TestBaseTypeInterfacePrintTypeA typeA = typeB;
+  EXPECT_EQ(typeA, nullptr);
+
+  typeB = TestType::get(&context);
+  typeA = typeB;
+  EXPECT_EQ(typeA, typeB);
+}



More information about the Mlir-commits mailing list