[mlir][ods] Add query for derived attribute
authorJacques Pienaar <jpienaar@google.com>
Tue, 3 Mar 2020 20:01:54 +0000 (12:01 -0800)
committerJacques Pienaar <jpienaar@google.com>
Tue, 3 Mar 2020 20:04:16 +0000 (12:04 -0800)
For ODS generated operations enable querying whether there is a derived
attribute with a given name.

Rollforward of commit 5aa57c2 without using llvm::is_contained.

mlir/test/mlir-tblgen/op-attribute.td
mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp

index 44c9a72..cb85149 100644 (file)
@@ -201,6 +201,18 @@ def DOp : NS_Op<"d_op", []> {
 // DEF: odsState.addAttribute("str_attr", (*odsBuilder).getStringAttr(str_attr));
 // DEF: odsState.addAttribute("dv_str_attr", (*odsBuilder).getStringAttr(dv_str_attr));
 
+// Test derived type attr.
+// ---
+def DerivedTypeAttrOp : NS_Op<"derived_type_attr_op", []> {
+  let results = (outs AnyTensor:$output);
+  DerivedTypeAttr element_dtype = DerivedTypeAttr<"return output().getType();">;
+}
+
+// DECL: bool isDerivedAttribute
+// DEF: bool DerivedTypeAttrOp::isDerivedAttribute(StringRef name) {
+// DEF:   if (name == "element_dtype") return true;
+// DEF:   return false;
+// DEF: }
 
 // Test that only default valued attributes at the end of the arguments
 // list get default values in the builder signature
index f4d114a..8c6ba60 100644 (file)
@@ -391,6 +391,20 @@ void OpEmitter::genAttrGetters() {
       emitAttrWithReturnType(name, attr);
     }
   }
+
+  // Generate helper method to query whether a named attribute is a derived
+  // attribute. This enables, for example, avoiding adding an attribute that
+  // overlaps with a derived attribute.
+  auto &method =
+      opClass.newMethod("bool", "isDerivedAttribute", "StringRef name");
+  auto &body = method.body();
+  auto derivedAttr = make_filter_range(op.getAttributes(),
+                                       [](const NamedAttribute &namedAttr) {
+                                         return namedAttr.attr.isDerivedAttr();
+                                       });
+  for (auto namedAttr : derivedAttr)
+    body << "    if (name == \"" << namedAttr.name << "\") return true;\n";
+  body << " return false;";
 }
 
 void OpEmitter::genAttrSetters() {