[Mlir-commits] [mlir] [MLIR][LLVMIR] Add support for intrinsics with metadata arguments (PR #200308)

Andy Kaylor llvmlistbot at llvm.org
Wed Jun 3 11:53:02 PDT 2026


================
@@ -149,6 +150,72 @@ static LogicalResult convertInstructionImpl(OpBuilder &odsBuilder,
   return failure();
 }
 
+/// Depth-first conversion of the metadata node `md` to the matching LLVM
+/// dialect metadata attribute. Returns a null attribute for shapes that the
+/// dialect's metadata-attribute hierarchy does not currently model. `path`
+/// holds the metadata nodes on the current depth-first search path. Cyclic
+/// metadata graphs are valid in LLVM IR, but they cannot be expressed by the
+/// immutable, structurally-uniqued metadata attributes built here. The `path`
+/// set lets the traversal recognize such a back-edge and bail out. `attrMap`
+/// caches the attributes of fully converted nodes so that shared subgraphs
+/// are visited only once.
+static Attribute
+convertMetadataToAttrImpl(MLIRContext *ctx, const llvm::Metadata *md,
+                          SmallPtrSetImpl<const llvm::Metadata *> &path,
+                          DenseMap<const llvm::Metadata *, Attribute> &attrMap) {
+  if (!md)
+    return {};
+  if (auto *mdStr = dyn_cast<llvm::MDString>(md))
+    return MDStringAttr::get(ctx, StringAttr::get(ctx, mdStr->getString()));
+  if (auto *cam = dyn_cast<llvm::ConstantAsMetadata>(md)) {
+    auto *ci = dyn_cast<llvm::ConstantInt>(cam->getValue());
+    if (!ci)
+      return {};
+    auto intType = IntegerType::get(ctx, ci->getBitWidth());
+    return MDConstantAttr::get(ctx, IntegerAttr::get(intType, ci->getValue()));
+  }
+  if (auto *vam = dyn_cast<llvm::ValueAsMetadata>(md)) {
+    auto *fn = dyn_cast<llvm::Function>(vam->getValue());
+    if (!fn)
+      return {};
+    return MDFuncAttr::get(ctx, FlatSymbolRefAttr::get(ctx, fn->getName()));
+  }
+  if (auto *node = dyn_cast<llvm::MDNode>(md)) {
+    if (Attribute cached = attrMap.lookup(node))
+      return cached;
+    // If `node` is already on the current search path, this is a back-edge into
+    // a cyclic graph. While that's valid it isn't implemented yet, so bail out.
+    if (!path.insert(node).second)
+      return {};
+    SmallVector<Attribute> operands;
+    operands.reserve(node->getNumOperands());
+    for (const llvm::MDOperand &op : node->operands()) {
+      Attribute opAttr = convertMetadataToAttrImpl(ctx, op.get(), path, attrMap);
+      if (!opAttr) {
+        path.erase(node);
+        return {};
+      }
----------------
andykaylor wrote:

Good point

https://github.com/llvm/llvm-project/pull/200308


More information about the Mlir-commits mailing list