MLIR Tutorial Chapter 3 - To make work a new transformation hook

I would like to report an interesting detail related to the MLIR tutorial “Chapter 3: High-level Language-Specific Analysis and Transformation”, found at Chapter 3: High-level Language-Specific Analysis and Transformation - MLIR .

I was unable to execute a new transformation hook matchAndRewrite() when I extended this chapter 3 tutorial. I got inspired from the tutorial which defined SimplifyRedundantTranspose and I created in Ch3/mlir/ToyCombine.cpp the class:
struct SimplifyRedundantMinus : public mlir::OpRewritePattern { mlir::LogicalResult matchAndRewrite(MinusOp op,
mlir::PatternRewriter &rewriter) const override {
Also, I defined the method:
void MinusOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) {
I also created in Ch3/include/toy/ the following Op, getting inspired from AddOp:
def MinusOp : Toy_Op<“minus”> { …
// I also defined this field
// Enable registering canonicalization patterns with this operation.
let hasCanonicalizer = 1;


So, as I said, this tutorial, as it is now, it’s not executing SimplifyRedundantMinus::matchAndRewrite(). The reason turned out to be the fact that the minus operation was considered as a simple function - if looking at the generated MLIR code we had:
%0 = toy.generic_call @minus(%arg0, %arg0) : (tensor<*xf64>, tensor<*xf64>) → tensor<*xf64> loc(“codegen3.toy”:9:10)
but the transpose call had the toy namespace directly:
%0 = toy.transpose(%arg0 : tensor<*xf64>) to tensor<*xf64> loc(“codegen3.toy”:14:10)
So, I had to transform minus from a generic call to function toy.minus belonging to the Toy dialect.
To do this I had to add in Ch3/mlir/MLIRGen.cpp, in method mlirGen(CallExprAST &call) a similar code to the one for the transpose operation, which looks like this:
// Builtin calls have their custom operation, meaning this is a
// straightforward emission.
if (callee == “minus”) {
if (call.getArgs().size() != 2) {
emitError(location, "MLIR codegen encountered an error: toy.minus "
“accepts only 2 arguments”);
return nullptr;
return builder.create(location, operands[0], operands[1]);
After this, the tutorial creates instead of toy.generic_call @minus the following function call belonging to the Toy dialect:
%0 = toy.minus %arg0, %arg0 : tensor<*xf64> loc(“codegen3.toy”:9:10)

This information with the change in Ch3/mlir/MLIRGen.cpp is not described in the tutorial Chapter 3 at Chapter 3: High-level Language-Specific Analysis and Transformation - MLIR . And this is why I write this post.

Best regards,