Confusion in 'build' methods in MLIR

In “toy” tutorial chapter 2, I wasn’t able to understand the section ‘Attaching build methods’. What is the purpose of ‘build’ methods and how to use ‘builder’ field and ‘OpBuilder’ class to define ‘build’ methods using ODS format?
In the tutorial it is stated that:
" ODS can generate some simple build methods automatically, and in this case it will generate our first build method for us. For the rest, we define the builders field."

How would I know what builder method has already been generated by ODS and for what builder methods do I have to define the ‘builder field’?

In the tutorial the builder field is defined as follows:

let builders = [
    // Build a constant with a given constant tensor value.
    OpBuilder<(ins "DenseElementsAttr":$value), [{
      // Call into an autogenerated `build` method.
      build(builder, result, value.getType(), value);
    }]>,

    // Build a constant with a given constant floating-point value. This builder
    // creates a declaration for `ConstantOp::build` with the given parameters.
    OpBuilder<(ins "double":$value)>
  ];

Why the type of value attribute is not specified as F64ElementsAttr as it was done here before?

kindly help :melting_face:

Thanks

In general you don’t need to write builders until you need to :wink:
These are mostly exclusively “convenience” anyway to make it so that call-site are easier to create an operation if the default builders aren’t good enough.

The best way to figure is likely to look at the generated code (find files ending with .inc.h in the build directory). The builders generated by default are fairly straightforward and take as arguments all the ODS arguments defined for an operation.

Here for example OpBuilder<(ins "double":$value)> will allow to create the constant op from a simple float: builder.create<ConstantOp>(loc, 42.0f);.
The first one is just using the attribute type to infer the result type of the operation, that is:

DenseElementsAttr value = ...;
builder.create<ConstantOp>(loc, value.getType(), value); // ODS generated builder
builder.create<ConstantOp>(loc, value); // Manually defined "convenience" builder
1 Like