Skip to content

Commit aac21b1

Browse files
[mlir][docs] Guide on generating alias for type/attribute
1 parent 2adcec7 commit aac21b1

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

mlir/docs/AsmPrinter.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# Customizing AsmPrinter Behavior
2+
3+
[TOC]
4+
5+
## Generating Aliases
6+
7+
To reduce verbosity in the resulting assembly, `AsmPrinter` can generate aliases for frequently used types and attributes.
8+
9+
For example, `!my_dialect.type<a=3,b=4,c=5,d=tuple,e=another_type>` and `#my_dialect.attr<a=3>` can be aliased to `!my_dialect_type` and `#my_dialect_attr`, simplifying further references.
10+
11+
To enable this, the owning dialect of these types/attributes can define an interface to hook into the `AsmPrinter`. This is effective only when the assembly is not printed in generic form.
12+
13+
```cpp
14+
struct MyDialectOpAsmDialectInterface : public OpAsmDialectInterface {
15+
public:
16+
using OpAsmDialectInterface::OpAsmDialectInterface;
17+
18+
AliasResult getAlias(Type type, raw_ostream& os) const override {
19+
if (mlir::isa<MyType>(type)) {
20+
os << "my_dialect_type";
21+
// Could return OverridableAlias when
22+
// allowing other dialect to override the alias.
23+
//
24+
// Other dialects are allowed to provide alias for
25+
// type/attribute not owned by them
26+
// but the final result would depend on the registration order
27+
// of these dialects in the MLIRContext
28+
return AliasResult::FinalAlias;
29+
}
30+
return AliasResult::NoAlias;
31+
}
32+
33+
AliasResult getAlias(Attribute attr, raw_ostream& os) const override {
34+
if (mlir::isa<MyAttribute>(attr)) {
35+
os << "my_dialect_attr";
36+
return AliasResult::FinalAlias;
37+
}
38+
return AliasResult::NoAlias;
39+
}
40+
};
41+
42+
void MyDialect::initialize() {
43+
// register the interface to the dialect
44+
addInterface<MyDialectOpAsmDialectInterface>();
45+
}
46+
```
47+
48+
* If `getAlias` provides an alias with a trailing digit, `AsmPrinter` appends an underscore to avoid conflicts with autogenerated IDs.
49+
* If multiple types/attributes have the same alias from `getAlias`, a number is appended to the alias to avoid conflicts.

0 commit comments

Comments
 (0)