#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/Pass/Pass.h"
using namespace mlir;
namespace {
struct MyLocation {
MyLocation() = default;
MyLocation(int id) : id(id) {}
int getId() { return id; }
int id{42};
};
}
MLIR_DECLARE_EXPLICIT_TYPE_ID(MyLocation *)
MLIR_DEFINE_EXPLICIT_TYPE_ID(MyLocation *)
namespace {
struct TestOpaqueLoc
: public PassWrapper<TestOpaqueLoc, OperationPass<ModuleOp>> {
MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestOpaqueLoc)
StringRef getArgument() const final { return "test-opaque-loc"; }
StringRef getDescription() const final {
return "Changes all leaf locations to opaque locations";
}
void runOnOperation() override {
std::vector<std::unique_ptr<MyLocation>> myLocs;
int lastIt = 0;
getOperation().getBody()->walk([&](Operation *op) {
myLocs.push_back(std::make_unique<MyLocation>(lastIt++));
Location loc = op->getLoc();
op->setLoc(
OpaqueLoc::get<MyLocation *>(myLocs.back().get(), &getContext()));
if (isa<ModuleOp>(op->getParentOp()) ||
op->hasTrait<OpTrait::IsTerminator>())
return;
OpBuilder builder(op);
Operation *opCloned1 = builder.clone(*op);
opCloned1->setLoc(OpaqueLoc::get<MyLocation *>(myLocs.back().get(), loc));
Operation *opCloned2 = builder.clone(*op);
opCloned2->setLoc(OpaqueLoc::get<void *>(nullptr, loc));
});
ScopedDiagnosticHandler diagHandler(&getContext(), [](Diagnostic &diag) {
auto &os = llvm::outs();
if (isa<OpaqueLoc>(diag.getLocation())) {
MyLocation *loc = OpaqueLoc::getUnderlyingLocationOrNull<MyLocation *>(
diag.getLocation());
if (loc)
os << "MyLocation: " << loc->id;
else
os << "nullptr";
}
os << ": " << diag << '\n';
os.flush();
});
getOperation().walk([&](Operation *op) { op->emitOpError(); });
}
};
}
namespace mlir {
namespace test {
void registerTestOpaqueLoc() { PassRegistration<TestOpaqueLoc>(); }
}
}