[mlir][drr] Simple heuristic to reduce chance of accidental nullptr dereference

When an attribute is optional & is given an additional constraint in
rewrite pattern that could lead to dereferencing null Attribute. Avoid
cases where the constraints checks attribute but has no check if null.

This should be improved to be more uniformly guarded.

GitOrigin-RevId: 86eb57b728c85bd1658f542d6ce8340efa63b4df
diff --git a/tools/mlir-tblgen/RewriterGen.cpp b/tools/mlir-tblgen/RewriterGen.cpp
index 76f9250..2a98497 100644
--- a/tools/mlir-tblgen/RewriterGen.cpp
+++ b/tools/mlir-tblgen/RewriterGen.cpp
@@ -793,6 +793,18 @@
     // If a constraint is specified, we need to generate function call to its
     // static verifier.
     StringRef verifier = staticMatcherHelper.getVerifierName(matcher);
+    if (attr.isOptional()) {
+      // Avoid dereferencing null attribute. This is using a simple heuristic to
+      // avoid common cases of attempting to dereference null attribute. This
+      // will return where there is no check if attribute is null unless the
+      // attribute's value is not used.
+      // FIXME: This could be improved as some null dereferences could slip
+      // through.
+      if (!StringRef(matcher.getConditionTemplate()).contains("!$_self") &&
+          StringRef(matcher.getConditionTemplate()).contains("$_self")) {
+        os << "if (!tblgen_attr) return failure();\n";
+      }
+    }
     emitStaticVerifierCall(
         verifier, opName, "tblgen_attr",
         formatv("\"op '{0}' attribute '{1}' failed to satisfy constraint: "