[llvm] [llvm-ir2vec] Adding initEmbedding API to ir2vec python bindings (PR #177092)

Nishant Sachdeva via llvm-commits llvm-commits at lists.llvm.org
Wed Jan 21 02:11:10 PST 2026


https://github.com/nishant-sachdeva updated https://github.com/llvm/llvm-project/pull/177092

>From 13030fdb297fae811e064c87d28ee6e6b5032aef Mon Sep 17 00:00:00 2001
From: nishant-sachdeva <nishant.sachdeva at research.iiit.ac.in>
Date: Wed, 21 Jan 2026 10:47:10 +0530
Subject: [PATCH 1/3] Adding an initEmbedding API to ir2vec python bindings

---
 llvm/include/llvm/Analysis/IR2Vec.h           |  4 +-
 llvm/lib/Analysis/IR2Vec.cpp                  | 29 +++++--
 .../llvm-ir2vec/bindings/ir2vec-bindings.py   | 21 ++++-
 .../tools/llvm-ir2vec/Bindings/CMakeLists.txt |  3 +-
 llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp  | 85 ++++++++++++++++++-
 5 files changed, 130 insertions(+), 12 deletions(-)

diff --git a/llvm/include/llvm/Analysis/IR2Vec.h b/llvm/include/llvm/Analysis/IR2Vec.h
index 5957a3743f22e..dcb9783bfa91c 100644
--- a/llvm/include/llvm/Analysis/IR2Vec.h
+++ b/llvm/include/llvm/Analysis/IR2Vec.h
@@ -615,8 +615,8 @@ class IR2VecVocabAnalysis : public AnalysisInfoMixin<IR2VecVocabAnalysis> {
   using VocabMap = std::map<std::string, ir2vec::Embedding>;
   std::optional<ir2vec::VocabStorage> Vocab;
 
-  Error readVocabulary(VocabMap &OpcVocab, VocabMap &TypeVocab,
-                       VocabMap &ArgVocab);
+  Error readVocabulary(StringRef EffectivePath, VocabMap &OpcVocab,
+                       VocabMap &TypeVocab, VocabMap &ArgVocab);
   void generateVocabStorage(VocabMap &OpcVocab, VocabMap &TypeVocab,
                             VocabMap &ArgVocab);
   void emitError(Error Err, LLVMContext &Ctx);
diff --git a/llvm/lib/Analysis/IR2Vec.cpp b/llvm/lib/Analysis/IR2Vec.cpp
index 85b5372c961c1..ef0259e32b271 100644
--- a/llvm/lib/Analysis/IR2Vec.cpp
+++ b/llvm/lib/Analysis/IR2Vec.cpp
@@ -62,6 +62,20 @@ cl::opt<IR2VecKind> IR2VecEmbeddingKind(
     cl::init(IR2VecKind::Symbolic), cl::desc("IR2Vec embedding kind"),
     cl::cat(IR2VecCategory));
 
+static std::optional<std::string> VocabOverride;
+
+void setIR2VecVocabPath(StringRef Path) {
+  if (Path.empty())
+    VocabOverride = std::nullopt;
+  else
+    VocabOverride = Path.str();
+}
+
+StringRef getIR2VecVocabPath() {
+  return VocabOverride ? StringRef(*VocabOverride)
+                       : StringRef(VocabFile.getValue());
+}
+
 } // namespace ir2vec
 } // namespace llvm
 
@@ -482,12 +496,14 @@ VocabStorage Vocabulary::createDummyVocabForTest(unsigned Dim) {
 
 // FIXME: Make this optional. We can avoid file reads
 // by auto-generating a default vocabulary during the build time.
-Error IR2VecVocabAnalysis::readVocabulary(VocabMap &OpcVocab,
+Error IR2VecVocabAnalysis::readVocabulary(StringRef EffectivePath,
+                                          VocabMap &OpcVocab,
                                           VocabMap &TypeVocab,
                                           VocabMap &ArgVocab) {
-  auto BufOrError = MemoryBuffer::getFileOrSTDIN(VocabFile, /*IsText=*/true);
+  auto BufOrError =
+      MemoryBuffer::getFileOrSTDIN(EffectivePath, /*IsText=*/true);
   if (!BufOrError)
-    return createFileError(VocabFile, BufOrError.getError());
+    return createFileError(EffectivePath.str(), BufOrError.getError());
 
   auto Content = BufOrError.get()->getBuffer();
 
@@ -615,8 +631,11 @@ IR2VecVocabAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
   if (Vocab.has_value())
     return Vocabulary(std::move(Vocab.value()));
 
+  StringRef EffectivePath =
+      VocabOverride ? StringRef(*VocabOverride) : VocabFile.getValue();
+
   // Otherwise, try to read from the vocabulary file.
-  if (VocabFile.empty()) {
+  if (EffectivePath.empty()) {
     // FIXME: Use default vocabulary
     Ctx->emitError("IR2Vec vocabulary file path not specified; You may need to "
                    "set it using --ir2vec-vocab-path");
@@ -624,7 +643,7 @@ IR2VecVocabAnalysis::run(Module &M, ModuleAnalysisManager &AM) {
   }
 
   VocabMap OpcVocab, TypeVocab, ArgVocab;
-  if (auto Err = readVocabulary(OpcVocab, TypeVocab, ArgVocab)) {
+  if (auto Err = readVocabulary(EffectivePath, OpcVocab, TypeVocab, ArgVocab)) {
     emitError(std::move(Err), *Ctx);
     return Vocabulary();
   }
diff --git a/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py b/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
index 459f353a478cb..e6734d2055cd8 100644
--- a/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
+++ b/llvm/test/tools/llvm-ir2vec/bindings/ir2vec-bindings.py
@@ -1,7 +1,22 @@
-# RUN: env PYTHONPATH=%llvm_lib_dir %python %s
+# RUN: rm -rf %t.ll
+# RUN: echo "define i32 @add(i32 %%a, i32 %%b) {" > %t.ll
+# RUN: echo "entry:" >> %t.ll
+# RUN: echo "  %%sum = add i32 %%a, %%b" >> %t.ll
+# RUN: echo "  ret i32 %%sum" >> %t.ll
+# RUN: echo "}" >> %t.ll
+# RUN: env PYTHONPATH=%llvm_lib_dir %python %s %t.ll %ir2vec_test_vocab_dir/dummy_3D_nonzero_opc_vocab.json | FileCheck %s
 
+import sys
 import ir2vec
 
-print("SUCCESS: Module imported")
+ll_file = sys.argv[1]
+vocab_path = sys.argv[2]
 
-# CHECK: SUCCESS: Module imported
+tool = ir2vec.initEmbedding(filename=ll_file, mode="sym", vocab_path=vocab_path)
+
+if tool is not None:
+    print("SUCCESS: Tool initialized")
+    print(f"Tool type: {type(tool).__name__}")
+
+# CHECK: SUCCESS: Tool initialized
+# CHECK: Tool type: IR2VecTool
diff --git a/llvm/tools/llvm-ir2vec/Bindings/CMakeLists.txt b/llvm/tools/llvm-ir2vec/Bindings/CMakeLists.txt
index 5df3720a24777..677208774f5a1 100644
--- a/llvm/tools/llvm-ir2vec/Bindings/CMakeLists.txt
+++ b/llvm/tools/llvm-ir2vec/Bindings/CMakeLists.txt
@@ -1,4 +1,4 @@
-find_package(Python COMPONENTS Interpreter Development.Module REQUIRED)
+find_package(Python ${Python3_VERSION} EXACT COMPONENTS Interpreter Development.Module REQUIRED)
 
 execute_process(
     COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir
@@ -10,5 +10,6 @@ set_target_properties(LLVMEmbUtils PROPERTIES POSITION_INDEPENDENT_CODE ON)
 
 nanobind_add_module(ir2vec MODULE PyIR2Vec.cpp)
 target_link_libraries(ir2vec PRIVATE LLVMEmbUtils)
+target_include_directories(ir2vec PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/..)
 
 message(STATUS "Python bindings for llvm-ir2vec will be built with nanobind")
diff --git a/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp b/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
index b3a46d429b6d4..aff85c091fbef 100644
--- a/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
+++ b/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
@@ -7,7 +7,90 @@
 //===----------------------------------------------------------------------===//
 
 #include <nanobind/nanobind.h>
+#include <nanobind/stl/string.h>
+#include <nanobind/stl/unique_ptr.h>
+
+#include "lib/Utils.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IRReader/IRReader.h"
+#include "llvm/Support/SourceMgr.h"
+
+#include <fstream>
+#include <memory>
+#include <string>
 
 namespace nb = nanobind;
 
-NB_MODULE(ir2vec, m) { m.doc() = "Python bindings for IR2Vec"; }
+namespace llvm {
+namespace ir2vec {
+void setIR2VecVocabPath(StringRef Path);
+StringRef getIR2VecVocabPath();
+} // namespace ir2vec
+} // namespace llvm
+
+namespace {
+
+bool fileNotValid(const std::string &Filename) {
+  std::ifstream F(Filename, std::ios_base::in | std::ios_base::binary);
+  return !F.good();
+}
+
+std::unique_ptr<Module> getLLVMIR(const std::string &Filename,
+                                  LLVMContext &Context) {
+  SMDiagnostic Err;
+  auto M = parseIRFile(Filename, Err, Context);
+  if (!M)
+    throw std::runtime_error("Failed to parse IR file.");
+  return M;
+}
+
+class PyIR2VecTool {
+private:
+  std::unique_ptr<LLVMContext> Ctx;
+  std::unique_ptr<Module> M;
+  std::unique_ptr<IR2VecTool> Tool;
+
+public:
+  PyIR2VecTool(const std::string &Filename, const std::string &Mode,
+               const std::string &VocabPath) {
+    if (fileNotValid(Filename))
+      throw std::runtime_error("Invalid file path");
+
+    if (Mode != "sym" && Mode != "fa")
+      throw std::runtime_error("Invalid mode. Use 'sym' or 'fa'");
+
+    if (VocabPath.empty())
+      throw std::runtime_error("Error - Empty Vocab Path not allowed");
+
+    setIR2VecVocabPath(VocabPath);
+
+    Ctx = std::make_unique<LLVMContext>();
+    M = getLLVMIR(Filename, *Ctx);
+    Tool = std::make_unique<IR2VecTool>(*M);
+
+    bool Ok = Tool->initializeVocabulary();
+    if (!Ok)
+      throw std::runtime_error("Failed to initialize IR2Vec vocabulary");
+  }
+};
+
+} // namespace
+
+NB_MODULE(ir2vec, m) {
+  m.doc() = std::string("Python bindings for ") + ToolName;
+
+  nb::class_<PyIR2VecTool>(m, "IR2VecTool")
+      .def(nb::init<const std::string &, const std::string &,
+                    const std::string &>(),
+           nb::arg("filename"), nb::arg("mode"), nb::arg("vocab_path"));
+
+  m.def(
+      "initEmbedding",
+      [](const std::string &filename, const std::string &mode,
+         const std::string &vocab_path) {
+        return std::make_unique<PyIR2VecTool>(filename, mode, vocab_path);
+      },
+      nb::arg("filename"), nb::arg("mode") = "sym", nb::arg("vocab_path"),
+      nb::rv_policy::take_ownership);
+}

>From b975025aabc5f1a5413f8202f75f3ff7d8fc0873 Mon Sep 17 00:00:00 2001
From: nishant-sachdeva <nishant.sachdeva at research.iiit.ac.in>
Date: Wed, 21 Jan 2026 14:47:00 +0530
Subject: [PATCH 2/3] Correct namespace usage marking for PyIR2Vec.cpp

---
 llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp b/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
index aff85c091fbef..24297d15caaf1 100644
--- a/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
+++ b/llvm/tools/llvm-ir2vec/Bindings/PyIR2Vec.cpp
@@ -21,6 +21,8 @@
 #include <string>
 
 namespace nb = nanobind;
+using namespace llvm;
+using namespace llvm::ir2vec;
 
 namespace llvm {
 namespace ir2vec {

>From e3b176d96e452d64dd4baa14cc0f21f3c058131f Mon Sep 17 00:00:00 2001
From: nishant-sachdeva <nishant.sachdeva at research.iiit.ac.in>
Date: Wed, 21 Jan 2026 15:05:12 +0530
Subject: [PATCH 3/3] Making VocabOverride non-static

---
 llvm/lib/Analysis/IR2Vec.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/llvm/lib/Analysis/IR2Vec.cpp b/llvm/lib/Analysis/IR2Vec.cpp
index ef0259e32b271..5562415eb9e28 100644
--- a/llvm/lib/Analysis/IR2Vec.cpp
+++ b/llvm/lib/Analysis/IR2Vec.cpp
@@ -62,7 +62,7 @@ cl::opt<IR2VecKind> IR2VecEmbeddingKind(
     cl::init(IR2VecKind::Symbolic), cl::desc("IR2Vec embedding kind"),
     cl::cat(IR2VecCategory));
 
-static std::optional<std::string> VocabOverride;
+std::optional<std::string> VocabOverride;
 
 void setIR2VecVocabPath(StringRef Path) {
   if (Path.empty())



More information about the llvm-commits mailing list