Emit MLIR from c++/c

Hi there, I am pretty new to MLIR. I noticed that the toy dialect example can emit mlir using Toy DSL and a codegen tool. Otherwise, we can also use MLIR python-binding to build MLIR module and op flow and emit MLIR by running the python code.

I wonder how to Emit MLIR from C/C++, is there any example? I try my best to find the examples but found none.

Thanks in advance!


The largest range of examples there would be the passes. What most of the passes do is use C++ builders (along wit matching section and defining passes, but the most is constructing MLIR operations in C++ which is how you’ll build the module before emitting it). The unittest group is another.



1 Like

Toy is written in C++ as well: it generates MLIR in C++ from the parsed-tree for the small DSL it is using.

1 Like

Thanks, Jacques , I think you save my life

Yes, thanks mehdi, you are right, but it is hard for me to write a DSL. I think the python binding is a good way. But I wonder if there is C++ binding, may be it is the way that Jacques describe that constructing MLIR op in C++ passes.

I don’t quite get your question actually, you don’t have to write a DSL: the DSL in Toy is just to support the tutorial. The parser of the DSL produces a parse tree, which is a C++ data structure, you could have this from JSON or any other source. The fact is that the “C++ bindings” as you call it what is used in Toy to emit MLIR: this is the exact same API you will find in c++ passes as Jacques describe. The difference is that Toy will emit MLIR “from scratch” (that is you have as input a C++ data structure that you turn into MLIR) whereas the C++ passes are transforming an existing MLIR construct in place.

@mehdi_amini Thanks mehdi, I got your point. Do I have to write the operation building codes in passes? Is there a way for me to write MLIR op building codes in a standalone c++ file just like I do using python bindings or that in Toy DSL?

I may miss something, but isn’t the answer in the question? Yes you can do just like the Toy example, that’s why it’s there: to show how you can do it.

Thanks for your patience, after read more code in Toy chapter2, I know how to do now.

I,m also interested it, would you like show the link of above Toy example ?

Sure, you can refer to this Link. It is not that intuitive like python binding does to build a module.