[Mlir-commits] [mlir] [mlir] NamedAttribute utility generator (PR #75118)

Mehdi Amini llvmlistbot at llvm.org
Tue Dec 12 13:32:44 PST 2023


================
@@ -283,6 +283,78 @@ class AttrDef<Dialect dialect, string name, list<Trait> traits = [],
                                  "::" # cppClassName # ">($_self)">;
 }
 
+// Define a StringAttr wrapper for the NamedAttribute `name`
+// - `name` is dialect-scoped when not-inherent.
+// - Utilities to is/has/get/set/lookup/create typed Attr on an Operation
+//   including typed `value` attribute
+class NamedAttrDef<Dialect dialect, string name, string userName,
+    string valueAttrType = "::mlir::Attribute">
+    : AttrDef<dialect, name, [], "::mlir::StringAttr"> {
+  let mnemonic = userName;
+
+  string scopedName = dialect.name # "." # mnemonic;
+  code typedefValueAttr = "typedef " # valueAttrType # " ValueAttrType;\n";
+  code getNameFunc = "static constexpr llvm::StringLiteral getScopedName() { return \""
+      # scopedName # "\"; }\n";
+
+  code namedAttrFuncs = !strconcat(typedefValueAttr, getNameFunc, [{
+    // Get name based on inherentness
+    static llvm::StringLiteral getName(Operation *op = nullptr) {
+      if (op && op->getPropertiesStorageSize()) {
+       auto mnemonic = getMnemonic();
+       if (op->getInherentAttr(mnemonic))
+         return mnemonic;
+      }
+      return getScopedName();
+    }
+    // Is or Has
+    static bool is(::mlir::NamedAttribute attr) {
+      return attr.getName() == getScopedName();
+    }
+    static bool isInherent(::mlir::NamedAttribute attr) {
+      return attr.getName() == getMnemonic();
+    }
+    static bool has(::mlir::Operation *op) {
+      return op->hasAttr(getName(op));
+    }
+    // Get Name
+    static ::mlir::StringAttr get(::mlir::MLIRContext *ctx, ::mlir::Operation *op = nullptr) {
+      return ::mlir::StringAttr::get(ctx, getName(op));
+    }
+    // Get Value
+    static ValueAttrType getValue(::mlir::Operation *op) {
+      return op->getAttrOfType<ValueAttrType>(getName(op));
+    }
+    // Scoped lookup for inheritance
+    static ValueAttrType lookupValue(::mlir::Operation *op) {
+      if (auto attr = getValue(op))
+        return attr;
+      std::optional<RegisteredOperationName> opInfo = op->getRegisteredInfo();
+      if (!opInfo || !opInfo->hasTrait<OpTrait::IsIsolatedFromAbove>()) {
+        if (auto *par = op->getParentOp())
+          return lookupValue(par);
+      }
+      return ValueAttrType();
+    }
+    // Set Value on Op
+    static void setValue(::mlir::Operation *op, ValueAttrType val) {
+      assert(op);
+      op->setAttr(getName(op), val);
+    }
+    // Remove Value from Op
+    static void removeValue(::mlir::Operation *op) {
----------------
joker-eph wrote:

The terminology is confusing: why are you using "Value" for referring to "Attributes"?

https://github.com/llvm/llvm-project/pull/75118


More information about the Mlir-commits mailing list