From d3b93a11139b3f3b4196f2e24ef731ed41f9b7aa Mon Sep 17 00:00:00 2001
From: Wilson Snyder <wsnyder@wsnyder.org>
Date: Sat, 16 Mar 2024 08:56:12 -0400
Subject: [PATCH] Fix object reference to conditional null : null

---
 src/V3Width.cpp                      |  4 +++-
 test_regress/t/t_class_assign_cond.v | 20 ++++++++++++++++++++
 2 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/src/V3Width.cpp b/src/V3Width.cpp
index b1dfcd85d..4327785ed 100644
--- a/src/V3Width.cpp
+++ b/src/V3Width.cpp
@@ -490,7 +490,9 @@ class WidthVisitor final : public VNVisitor {
             //  the expression includes the size of the output too.
             const AstNodeDType* const thenDTypep = nodep->thenp()->dtypep();
             const AstNodeDType* const elseDTypep = nodep->elsep()->dtypep();
-            if (thenDTypep->skipRefp() == elseDTypep->skipRefp()) {
+            if (nodep->thenp()->isNull() && nodep->elsep()->isNull()) {
+                nodep->dtypep(m_vup->dtypeNullp());
+            } else if (thenDTypep->skipRefp() == elseDTypep->skipRefp()) {
                 // TODO might need a broader equation, use the Castable function?
                 nodep->dtypeFrom(thenDTypep);
             } else if (nodep->thenp()->isClassHandleValue()
diff --git a/test_regress/t/t_class_assign_cond.v b/test_regress/t/t_class_assign_cond.v
index 4d78e3a68..321ff7d28 100644
--- a/test_regress/t/t_class_assign_cond.v
+++ b/test_regress/t/t_class_assign_cond.v
@@ -35,6 +35,7 @@ module t (/*AUTOARG*/);
       ExtendCls ext_cls = null;
       AnotherExtendCls an_ext_cls = null;
       ExtendExtendCls ext_ext_cls = null;
+      int r;
 
       cls1 = (cls1 == null) ? cls2 : cls1;
       if (cls1 != null) $stop;
@@ -64,6 +65,25 @@ module t (/*AUTOARG*/);
       cls1 = (ext_ext_cls.f != 4) ? ext_ext_cls : an_ext_cls;
       if (cls1.f != 5) $stop;
 
+      ext_cls = new(3);
+      r = $random;
+      cls1 = r[0] ? ext_cls : null;
+      if (cls1 != null && cls1.f != 3) $stop;
+
+      ext_cls = new(3);
+      r = $random;
+      cls1 = r[0] ? null : ext_cls;
+      if (cls1 != null && cls1.f != 3) $stop;
+
+      ext_cls = new(3);
+      r = $random;
+      cls1 = r[0] ? null : null;
+      if (cls1 != null) $stop;
+
+      ext_cls = new(3);
+      cls1 = (ext_cls == null) ? null : null;
+      if (cls1 != null) $stop;
+
       $write("*-* All Finished *-*\n");
       $finish;
    end