Compiling a simple example

Hello

I am bit new to this,. so this question might have been answered. However I cannot find a concrete solution. So here it goes. I have the following code.

#include “mlir/IR/MLIRContext.h”
#include “mlir/IR/Builders.h”
#include “mlir/IR/BuiltinOps.h”
#include “mlir/Dialect/Func/IR/FuncOps.h”

using namespace mlir;

int main() {
// Initialize the MLIR context.
MLIRContext context;

// Create an MLIR module.
auto module = ModuleOp::create(UnknownLoc::get(&context));

// Create a function type.
auto funcType = FunctionType::get(&context, {}, {});

// Create an MLIR function inside the module.
func::FuncOp func = func::FuncOp::create(UnknownLoc::get(&context), “my_function”, funcType);

// Add the function to the module.
module.push_back(func);

// Print the MLIR module.
module.print(llvm::outs());

return 0;
}

I have tried compiling it but I always get a Segfault and nothing is being printed. It seems the code segfaults at func::FuncOp::create.

I have tried compiling directly as

g++ test.cpp -o test.x -I/usr/local/Cellar/llvm/17.0.1/include -L/usr/local/Cellar/llvm/17.0.1/lib -lLLVM -lMLIR -std=c++17

and I have also tried compiling the code using cmake. But same error.

I installed llvm 17 using brew. That installed the mlir libraries as well.

Thanks

Hi Thom,

Try something like:

#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"

using namespace mlir;

int main() {

  // Initialize the MLIR context.
  MLIRContext context;
  context.loadDialect<func::FuncDialect>();
  Builder builder(&context);

  // Create an MLIR module.
  OwningOpRef<ModuleOp> module(ModuleOp::create(UnknownLoc::get(&context)));


  // Create a function type.
  auto funcType = builder.getFunctionType(std::nullopt, std::nullopt);

  // Create an MLIR function inside the module.
  func::FuncOp func1 = func::FuncOp::create(builder.getUnknownLoc(), "my_function", funcType);
  func1.setPrivate();

  // Add the function to the module.
  module->push_back(func1);

  // Print the MLIR module.
  module->print(llvm::outs());

  return 0;
}

Specifically, this line is important. You must load a dialect before constructing ops that belong to the dialect. If MLIR is built with assertions (doesn’t seem to be the case for you), an assertion will fire when the dialect has not been loaded before an op is constructed.

1 Like

Thanks a bunch for the help.

It seems to be working now.

Developing without assertions is gonna be tough! It’s highly advisable to keep these enabled.

I have assertions enabled on an Ubuntu machine. On MAC I could not compile the code, and I just used the brew install llvm version. That version installed LLVM and MLIR but I doubt they had the assertions enabled.

Thanks for the fast response.