[Mlir-commits] [mlir] [mlir][ODS] Add `ConstantEnumCase` (PR #78992)

Markus Böck llvmlistbot at llvm.org
Tue Jan 23 00:32:10 PST 2024


================
@@ -417,4 +417,54 @@ class EnumAttr<Dialect dialect, EnumAttrInfo enumInfo, string name = "",
   let assemblyFormat = "$value";
 }
 
+class _symbolToValue<EnumAttrInfo enumAttrInfo, string case> {
+  defvar cases =
+    !filter(iter, enumAttrInfo.enumerants, !eq(iter.str, case));
+
+  assert !not(!empty(cases)), "failed to find enum-case '" # case # "'";
+
+  // `!empty` check to not cause an error if the cases are empty.
+  // The assertion catches the issue later and emits a proper error message.
+  string value = enumAttrInfo.cppType # "::"
+    # !if(!empty(cases), "", !head(cases).symbol);
+}
+
+class _bitSymbolsToValue<BitEnumAttr bitEnumAttr, string case> {
+  defvar pos = !find(case, "|");
+
+  // Recursive instantiation looking up the symbol before the `|` in
+  // enum cases.
+  string value = !if(
+    !eq(pos, -1), /*baseCase=*/_symbolToValue<bitEnumAttr, case>.value,
+    /*rec=*/_symbolToValue<bitEnumAttr, !substr(case, 0, pos)>.value # "|"
+    # _bitSymbolsToValue<bitEnumAttr, !substr(case, !add(pos, 1))>.value
+  );
+}
+
+class ConstantEnumCaseBase<Attr attribute,
+    EnumAttrInfo enumAttrInfo, string case>
+  : ConstantAttr<attribute,
+  !if(!isa<BitEnumAttr>(enumAttrInfo),
+    _bitSymbolsToValue<!cast<BitEnumAttr>(enumAttrInfo), case>.value,
+    _symbolToValue<enumAttrInfo, case>.value
+  )
+>;
+
+/// Constant attribute for defining enum values. `attribute` should be one of
+/// `EnumAttrInfo` or `EnumAttr` and `symbol` the string representation of an
+/// enum case. Multiple enum values of a bit-enum can be combined using `|` as
+/// a separator. Note that there mustn't be any whitespace around the
+/// separator.
+///
+/// Examples:
+/// * ConstantEnumCase<Arith_IntegerOverflowAttr, "nsw|nuw">
----------------
zero9178 wrote:

The `|` syntax to combine enum values is only enabled if the enum passed in is a `BitEnumAttr`, so there isn't any opportunity for misuse if using a normal enum attribute (so it'd just error saying `failed to find enum case'first|second'`).
`BitEnumAttr` (modulo bugs) guarantees that enum values have only a single bit set.

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


More information about the Mlir-commits mailing list