LLVM Discussion Forums

Is there a tree representation for MLIR code?

During the lowering process, does MLIR create some graph-like structure (such as an AST) which is then used to transform and generate the MLIR output code? I’m looking for some abstraction for generic MLIR code and was wondering if there’s something of the sort already implemented that can be used in out-of-tree programs.

Alternatively, It would help to have some form of interface to iterate through MLIR code. I know that LLVM has the llvm::Module, llvm::Function, and llvm::BasicBlocks classes which are used to traverse the data structure keeping the code. Does MLIR have some similar classes that allow traversing through MLIR code? And if so, can it be used on out of tree programs?

1 Like

MLIR has a similar structure, LangRef is likely the documentation you’re looking for, and the Toy tutorial is walking through the manipulation of the IR.

Can you clarify what you mean by “out of tree programs”? (Multiple projects are using MLIR “out-of-tree”).

Hey @joker-eph,

Completely overlooked this documentation. That’s exactly what I was looking for. Thanks.

I might have forgotten some part but, although the tutorial explains several procedures, I didn’t notice a way to iterate through the code. Even so, with the LangRef I believe it becomes understandable how to do so.

In the Toy tutorial (chapter 2), whenever an MLIR file is given as input, it’s parsed In the following line:

mlir::OwningModuleRef module = mlir::parseSourceFile(sourceMgr, &context);

So module holds the reference to a ModuleOp with the input code. Then we can retrieve MouduleOp with module.get() which holds a single Region that can be retrieved with getBody(). With the region, we can use getBlocks(), and so on. This way, iterating through the code seems to be possible.

I imagine the set of classes used to represent the code in C++ is the “in-memory” representation that is mentioned in the LangRef. Is this correct?

Good point, I just wrote some doc dedicated to this: https://reviews.llvm.org/D87221 (if you want to review, feel free to comment there).

Yes, let me know if the added doc and example code in the revision above is answering all these questions!

This is on the website now: https://mlir.llvm.org/docs/Tutorials/UnderstandingTheIRStructure/

1 Like

This example is perfect! Thanks for the help!