[llvm] [IR2Vec] Introducing python bindings for IR2Vec (PR #173194)
via llvm-commits
llvm-commits at lists.llvm.org
Tue Dec 23 02:41:06 PST 2025
llvmbot wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-mlgo
Author: Nishant Sachdeva (nishant-sachdeva)
<details>
<summary>Changes</summary>
# Introducing Python Bindings for llvm-ir2vec
- Addresses https://github.com/llvm/llvm-project/issues/141839
## Summary
This patch refactors the llvm-ir2vec tool to support Python bindings. This done by the following changes
## Changes
### 1. Library Extraction (`lib/`)
- **Created `lib/EmbTool`**: Extracted embedding tool functionality from `llvm-ir2vec.cpp` into a separate library
- `lib/emb-tool.cpp`: Core embedding generation logic
- `lib/emb-tool.h`: Public interface for the embedding tool
- `lib/CMakeLists.txt`: Library build configuration
### 2. Tool Refactoring
- **Simplified `llvm-ir2vec.cpp`**: Refactored to use the `EmbTool` library, removing code duplication
- Command-line tool now acts as a thin wrapper around the library functionality
### 3. Python Bindings (`bindings/`)
- **Added `bindings/ir2vec_bindings.cpp`**: pybind11-based Python bindings
- Provides Pythonic interface for embedding generation
- **Added `bindings/CMakeLists.txt`**: Build configuration for Python module
- Gracefully handles missing pybind11 dependency
- Creates `py_ir2vec` Python module
### 4. Build System
- **Updated root `CMakeLists.txt`**:
- Builds library before tool and bindings
- Links tool and bindings against `EmbTool` library
- All LLVM component dependencies properly propagated through the library
## Directory Structure
```
llvm-ir2vec/
├── lib/ # Core library
│ ├── CMakeLists.txt
│ ├── emb-tool.cpp
│ └── emb-tool.h
├── bindings/ # Python bindings
│ ├── CMakeLists.txt
│ └── ir2vec_bindings.cpp
├── CMakeLists.txt # Root build config
└── llvm-ir2vec.cpp # Command-line tool
```
## Benefits
1. **Code Reusability**: Core functionality now available as a library
2. **Python Integration**: Enables programmatic usage from Python scripts and notebooks
3. **Maintainability**: Single source of truth for embedding logic
4. **Backward Compatibility**: Existing command-line tool behavior unchanged
5. **Optional Dependencies**: Python bindings gracefully skipped if pybind11 unavailable
## Usage
```python
import py_ir2vec
tool = py_ir2vec.IR2VecTool("input.ll")
entities = tool.getEntityMappings()
triplets = tool.generateTriplets()
```
## Next Steps
- Python API method for embedding generation
- Extending an equivalent API structure to MIR2Vec
- Wheel file builds
---
Patch is 33.42 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/173194.diff
7 Files Affected:
- (modified) llvm/tools/llvm-ir2vec/CMakeLists.txt (+9-19)
- (added) llvm/tools/llvm-ir2vec/bindings/CMakeLists.txt (+14)
- (added) llvm/tools/llvm-ir2vec/bindings/ir2vec_bindings.cpp (+107)
- (added) llvm/tools/llvm-ir2vec/lib/CMakeLists.txt (+28)
- (added) llvm/tools/llvm-ir2vec/lib/emb-tool.cpp (+421)
- (renamed) llvm/tools/llvm-ir2vec/lib/emb-tool.h (+3-3)
- (modified) llvm/tools/llvm-ir2vec/llvm-ir2vec.cpp (+1-371)
``````````diff
diff --git a/llvm/tools/llvm-ir2vec/CMakeLists.txt b/llvm/tools/llvm-ir2vec/CMakeLists.txt
index 2bb6686392907..d5956cde6892d 100644
--- a/llvm/tools/llvm-ir2vec/CMakeLists.txt
+++ b/llvm/tools/llvm-ir2vec/CMakeLists.txt
@@ -1,25 +1,15 @@
-set(LLVM_LINK_COMPONENTS
- # Core LLVM components for IR processing
- Analysis
- Core
- IRReader
- Support
-
- # Machine IR components (for -mode=mir)
- CodeGen
- MIRParser
-
- # Target initialization (required for MIR parsing)
- AllTargetsAsmParsers
- AllTargetsCodeGens
- AllTargetsDescs
- AllTargetsInfos
- TargetParser
- )
+# Build the library first
+add_subdirectory(lib)
+# Build the llvm-ir2vec executable
add_llvm_tool(llvm-ir2vec
llvm-ir2vec.cpp
DEPENDS
intrinsics_gen
- )
+)
+
+# Link the executable against the library
+target_link_libraries(llvm-ir2vec PRIVATE EmbTool)
+
+add_subdirectory(bindings)
diff --git a/llvm/tools/llvm-ir2vec/bindings/CMakeLists.txt b/llvm/tools/llvm-ir2vec/bindings/CMakeLists.txt
new file mode 100644
index 0000000000000..a820960b9ea07
--- /dev/null
+++ b/llvm/tools/llvm-ir2vec/bindings/CMakeLists.txt
@@ -0,0 +1,14 @@
+find_package(Python3 REQUIRED COMPONENTS Interpreter Development.Module)
+find_package(pybind11 CONFIG QUIET)
+
+if(NOT pybind11_FOUND)
+ message(WARNING "pybind11 not found - skipping py_ir2vec")
+ return()
+endif()
+
+pybind11_add_module(py_ir2vec
+ ir2vec_bindings.cpp
+)
+
+# Link against the EmbTool library
+target_link_libraries(py_ir2vec PRIVATE EmbTool)
\ No newline at end of file
diff --git a/llvm/tools/llvm-ir2vec/bindings/ir2vec_bindings.cpp b/llvm/tools/llvm-ir2vec/bindings/ir2vec_bindings.cpp
new file mode 100644
index 0000000000000..d9d4b9f07e637
--- /dev/null
+++ b/llvm/tools/llvm-ir2vec/bindings/ir2vec_bindings.cpp
@@ -0,0 +1,107 @@
+//===- ir2vec_bindings.cpp - Python Bindings for IR2Vec ------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "../lib/emb-tool.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IRReader/IRReader.h"
+#include "llvm/Support/SourceMgr.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include <pybind11/pybind11.h>
+#include <pybind11/stl.h>
+
+#include <fstream>
+#include <memory>
+#include <string>
+
+namespace py = pybind11;
+using namespace llvm;
+using namespace llvm::ir2vec;
+
+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) {
+ Err.print(Filename.c_str(), outs());
+ 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) {
+ if (fileNotValid(Filename))
+ throw std::runtime_error("Invalid file path");
+
+ Ctx = std::make_unique<LLVMContext>();
+ M = getLLVMIR(Filename, *Ctx);
+ Tool = std::make_unique<IR2VecTool>(*M);
+ }
+
+ // Get entity mappings (vocabulary)
+ std::vector<std::string> getEntityMappings() {
+ return IR2VecTool::collectEntityMappings();
+ }
+
+ // Generate triplets for vocabulary training
+ py::dict generateTriplets() {
+ auto result = Tool->generateTriplets();
+ py::list triplets_list;
+
+ for (const auto &t : result.Triplets) {
+ triplets_list.append(py::make_tuple(t.Head, t.Tail, t.Relation));
+ }
+
+ py::dict output;
+ output["max_relation"] = result.MaxRelation;
+ output["triplets"] = triplets_list;
+ return output;
+ }
+};
+
+} // anonymous namespace
+
+PYBIND11_MODULE(py_ir2vec, m) {
+ m.doc() = std::string("Python bindings for ") + ToolName + "\n\n" + ToolName +
+ " provides distributed representations for LLVM IR.\n\n"
+ "Example:\n"
+ " >>> import py_ir2vec\n"
+ " >>> tool = py_ir2vec." +
+ ToolName +
+ "Tool(\"test.ll\")\n"
+ " >>> entities = tool.getEntityMappings()\n"
+ " >>> triplets = tool.generateTriplets()";
+
+ // Main tool class
+ py::class_<PyIR2VecTool>(m, "IR2VecTool")
+ .def(py::init<const std::string &>(), py::arg("filename"),
+ "Initialize IR2Vec on an LLVM IR file\n"
+ "Args:\n"
+ " filename: Path to LLVM IR file (.bc or .ll)")
+ .def("getEntityMappings", &PyIR2VecTool::getEntityMappings,
+ "Get entity mappings (vocabulary)\n"
+ "Returns: list[str] - list of entity names where index is entity_id")
+ .def("generateTriplets", &PyIR2VecTool::generateTriplets,
+ "Generate triplets for vocabulary training\n"
+ "Returns: dict with 'max_relation' and 'triplets' keys");
+}
\ No newline at end of file
diff --git a/llvm/tools/llvm-ir2vec/lib/CMakeLists.txt b/llvm/tools/llvm-ir2vec/lib/CMakeLists.txt
new file mode 100644
index 0000000000000..f15761beb97df
--- /dev/null
+++ b/llvm/tools/llvm-ir2vec/lib/CMakeLists.txt
@@ -0,0 +1,28 @@
+set(LLVM_LINK_COMPONENTS
+ # Core LLVM components for IR processing
+ Analysis
+ Core
+ IRReader
+ Support
+
+ # Machine IR components (for -mode=mir)
+ CodeGen
+ MIRParser
+
+ # Target initialization (required for MIR parsing)
+ AllTargetsAsmParsers
+ AllTargetsCodeGens
+ AllTargetsDescs
+ AllTargetsInfos
+ TargetParser
+)
+
+add_llvm_library(EmbTool
+ emb-tool.cpp
+
+ LINK_COMPONENTS
+ ${LLVM_LINK_COMPONENTS}
+
+ DEPENDS
+ intrinsics_gen
+)
\ No newline at end of file
diff --git a/llvm/tools/llvm-ir2vec/lib/emb-tool.cpp b/llvm/tools/llvm-ir2vec/lib/emb-tool.cpp
new file mode 100644
index 0000000000000..891b26f8ef763
--- /dev/null
+++ b/llvm/tools/llvm-ir2vec/lib/emb-tool.cpp
@@ -0,0 +1,421 @@
+//===- emb-tool.cpp - IR2Vec/MIR2Vec Embedding Generation Tool -----------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// This file implements the IR2VecTool and MIR2VecTool classes for
+/// IR2Vec/MIR2Vec embedding generation.
+///
+//===----------------------------------------------------------------------===//
+
+#include "emb-tool.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/Analysis/IR2Vec.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Function.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Instructions.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/PassInstrumentation.h"
+#include "llvm/IR/PassManager.h"
+#include "llvm/IR/Type.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include "llvm/CodeGen/MIR2Vec.h"
+#include "llvm/CodeGen/MIRParser/MIRParser.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/MachineModuleInfo.h"
+#include "llvm/CodeGen/TargetInstrInfo.h"
+#include "llvm/CodeGen/TargetRegisterInfo.h"
+#include "llvm/Support/WithColor.h"
+#include "llvm/Target/TargetMachine.h"
+
+#define DEBUG_TYPE "ir2vec"
+
+namespace llvm {
+
+namespace ir2vec {
+
+bool IR2VecTool::initializeVocabulary() {
+ // Register and run the IR2Vec vocabulary analysis
+ // The vocabulary file path is specified via --ir2vec-vocab-path global
+ // option
+ MAM.registerPass([&] { return PassInstrumentationAnalysis(); });
+ MAM.registerPass([&] { return IR2VecVocabAnalysis(); });
+ // This will throw an error if vocab is not found or invalid
+ Vocab = &MAM.getResult<IR2VecVocabAnalysis>(M);
+ return Vocab->isValid();
+}
+
+TripletResult IR2VecTool::generateTriplets(const Function &F) const {
+ if (F.isDeclaration())
+ return {};
+
+ TripletResult Result;
+ Result.MaxRelation = 0;
+
+ unsigned MaxRelation = NextRelation;
+ unsigned PrevOpcode = 0;
+ bool HasPrevOpcode = false;
+
+ for (const BasicBlock &BB : F) {
+ for (const auto &I : BB.instructionsWithoutDebug()) {
+ unsigned Opcode = Vocabulary::getIndex(I.getOpcode());
+ unsigned TypeID = Vocabulary::getIndex(I.getType()->getTypeID());
+
+ // Add "Next" relationship with previous instruction
+ if (HasPrevOpcode) {
+ Result.Triplets.push_back({PrevOpcode, Opcode, NextRelation});
+ LLVM_DEBUG(dbgs() << Vocabulary::getVocabKeyForOpcode(PrevOpcode + 1)
+ << '\t'
+ << Vocabulary::getVocabKeyForOpcode(Opcode + 1)
+ << '\t' << "Next\n");
+ }
+
+ // Add "Type" relationship
+ Result.Triplets.push_back({Opcode, TypeID, TypeRelation});
+ LLVM_DEBUG(
+ dbgs() << Vocabulary::getVocabKeyForOpcode(Opcode + 1) << '\t'
+ << Vocabulary::getVocabKeyForTypeID(I.getType()->getTypeID())
+ << '\t' << "Type\n");
+
+ // Add "Arg" relationships
+ unsigned ArgIndex = 0;
+ for (const Use &U : I.operands()) {
+ unsigned OperandID = Vocabulary::getIndex(*U.get());
+ unsigned RelationID = ArgRelation + ArgIndex;
+ Result.Triplets.push_back({Opcode, OperandID, RelationID});
+
+ LLVM_DEBUG({
+ StringRef OperandStr = Vocabulary::getVocabKeyForOperandKind(
+ Vocabulary::getOperandKind(U.get()));
+ dbgs() << Vocabulary::getVocabKeyForOpcode(Opcode + 1) << '\t'
+ << OperandStr << '\t' << "Arg" << ArgIndex << '\n';
+ });
+
+ ++ArgIndex;
+ }
+ // Only update MaxRelation if there were operands
+ if (ArgIndex > 0)
+ MaxRelation = std::max(MaxRelation, ArgRelation + ArgIndex - 1);
+ PrevOpcode = Opcode;
+ HasPrevOpcode = true;
+ }
+ }
+
+ Result.MaxRelation = MaxRelation;
+ return Result;
+}
+
+TripletResult IR2VecTool::generateTriplets() const {
+ TripletResult Result;
+ Result.MaxRelation = NextRelation;
+
+ for (const Function &F : M.getFunctionDefs()) {
+ TripletResult FuncResult = generateTriplets(F);
+ Result.MaxRelation = std::max(Result.MaxRelation, FuncResult.MaxRelation);
+ Result.Triplets.insert(Result.Triplets.end(), FuncResult.Triplets.begin(),
+ FuncResult.Triplets.end());
+ }
+
+ return Result;
+}
+
+void IR2VecTool::writeTripletsToStream(raw_ostream &OS) const {
+ auto Result = generateTriplets();
+ OS << "MAX_RELATION=" << Result.MaxRelation << '\n';
+ for (const auto &T : Result.Triplets)
+ OS << T.Head << '\t' << T.Tail << '\t' << T.Relation << '\n';
+}
+
+EntityList IR2VecTool::collectEntityMappings() {
+ auto EntityLen = Vocabulary::getCanonicalSize();
+ EntityList Result;
+ for (unsigned EntityID = 0; EntityID < EntityLen; ++EntityID)
+ Result.push_back(Vocabulary::getStringKey(EntityID).str());
+ return Result;
+}
+
+void IR2VecTool::writeEntitiesToStream(raw_ostream &OS) {
+ auto Entities = collectEntityMappings();
+ OS << Entities.size() << "\n";
+ for (unsigned EntityID = 0; EntityID < Entities.size(); ++EntityID)
+ OS << Entities[EntityID] << '\t' << EntityID << '\n';
+}
+
+void IR2VecTool::writeEmbeddingsToStream(raw_ostream &OS,
+ EmbeddingLevel Level) const {
+ if (!Vocab->isValid()) {
+ WithColor::error(errs(), ToolName)
+ << "Vocabulary is not valid. IR2VecTool not initialized.\n";
+ return;
+ }
+
+ for (const Function &F : M.getFunctionDefs())
+ writeEmbeddingsToStream(F, OS, Level);
+}
+
+void IR2VecTool::writeEmbeddingsToStream(const Function &F, raw_ostream &OS,
+ EmbeddingLevel Level) const {
+ if (!Vocab || !Vocab->isValid()) {
+ WithColor::error(errs(), ToolName)
+ << "Vocabulary is not valid. IR2VecTool not initialized.\n";
+ return;
+ }
+ if (F.isDeclaration()) {
+ OS << "Function " << F.getName() << " is a declaration, skipping.\n";
+ return;
+ }
+
+ // Create embedder for this function
+ auto Emb = Embedder::create(IR2VecEmbeddingKind, F, *Vocab);
+ if (!Emb) {
+ WithColor::error(errs(), ToolName)
+ << "Failed to create embedder for function " << F.getName() << "\n";
+ return;
+ }
+
+ OS << "Function: " << F.getName() << "\n";
+
+ // Generate embeddings based on the specified level
+ switch (Level) {
+ case FunctionLevel:
+ Emb->getFunctionVector().print(OS);
+ break;
+ case BasicBlockLevel:
+ for (const BasicBlock &BB : F) {
+ OS << BB.getName() << ":";
+ Emb->getBBVector(BB).print(OS);
+ }
+ break;
+ case InstructionLevel:
+ for (const Instruction &I : instructions(F)) {
+ OS << I;
+ Emb->getInstVector(I).print(OS);
+ }
+ break;
+ }
+}
+
+} // namespace ir2vec
+
+namespace mir2vec {
+
+bool MIR2VecTool::initializeVocabulary(const Module &M) {
+ MIR2VecVocabProvider Provider(MMI);
+ auto VocabOrErr = Provider.getVocabulary(M);
+ if (!VocabOrErr) {
+ WithColor::error(errs(), ToolName)
+ << "Failed to load MIR2Vec vocabulary - "
+ << toString(VocabOrErr.takeError()) << "\n";
+ return false;
+ }
+ Vocab = std::make_unique<MIRVocabulary>(std::move(*VocabOrErr));
+ return true;
+}
+
+bool MIR2VecTool::initializeVocabularyForLayout(const Module &M) {
+ for (const Function &F : M.getFunctionDefs()) {
+ MachineFunction *MF = MMI.getMachineFunction(F);
+ if (!MF)
+ continue;
+
+ const TargetInstrInfo &TII = *MF->getSubtarget().getInstrInfo();
+ const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
+ const MachineRegisterInfo &MRI = MF->getRegInfo();
+
+ auto VocabOrErr = MIRVocabulary::createDummyVocabForTest(TII, TRI, MRI, 1);
+ if (!VocabOrErr) {
+ WithColor::error(errs(), ToolName)
+ << "Failed to create dummy vocabulary - "
+ << toString(VocabOrErr.takeError()) << "\n";
+ return false;
+ }
+ Vocab = std::make_unique<MIRVocabulary>(std::move(*VocabOrErr));
+ return true;
+ }
+
+ WithColor::error(errs(), ToolName)
+ << "No machine functions found to initialize vocabulary\n";
+ return false;
+}
+
+TripletResult MIR2VecTool::generateTriplets(const MachineFunction &MF) const {
+ TripletResult Result;
+ Result.MaxRelation = MIRNextRelation;
+
+ if (!Vocab) {
+ WithColor::error(errs(), ToolName)
+ << "MIR Vocabulary must be initialized for triplet generation.\n";
+ return Result;
+ }
+
+ unsigned PrevOpcode = 0;
+ bool HasPrevOpcode = false;
+ for (const MachineBasicBlock &MBB : MF) {
+ for (const MachineInstr &MI : MBB) {
+ // Skip debug instructions
+ if (MI.isDebugInstr())
+ continue;
+
+ // Get opcode entity ID
+ unsigned OpcodeID = Vocab->getEntityIDForOpcode(MI.getOpcode());
+
+ // Add "Next" relationship with previous instruction
+ if (HasPrevOpcode) {
+ Result.Triplets.push_back({PrevOpcode, OpcodeID, MIRNextRelation});
+ LLVM_DEBUG(dbgs() << Vocab->getStringKey(PrevOpcode) << '\t'
+ << Vocab->getStringKey(OpcodeID) << '\t' << "Next\n");
+ }
+
+ // Add "Arg" relationships for operands
+ unsigned ArgIndex = 0;
+ for (const MachineOperand &MO : MI.operands()) {
+ auto OperandID = Vocab->getEntityIDForMachineOperand(MO);
+ unsigned RelationID = MIRArgRelation + ArgIndex;
+ Result.Triplets.push_back({OpcodeID, OperandID, RelationID});
+ LLVM_DEBUG({
+ std::string OperandStr = Vocab->getStringKey(OperandID);
+ dbgs() << Vocab->getStringKey(OpcodeID) << '\t' << OperandStr << '\t'
+ << "Arg" << ArgIndex << '\n';
+ });
+
+ ++ArgIndex;
+ }
+
+ // Update MaxRelation if there were operands
+ if (ArgIndex > 0)
+ Result.MaxRelation =
+ std::max(Result.MaxRelation, MIRArgRelation + ArgIndex - 1);
+
+ PrevOpcode = OpcodeID;
+ HasPrevOpcode = true;
+ }
+ }
+
+ return Result;
+}
+
+TripletResult MIR2VecTool::generateTriplets(const Module &M) const {
+ TripletResult Result;
+ Result.MaxRelation = MIRNextRelation;
+
+ for (const Function &F : M.getFunctionDefs()) {
+ MachineFunction *MF = MMI.getMachineFunction(F);
+ if (!MF) {
+ WithColor::warning(errs(), ToolName)
+ << "No MachineFunction for " << F.getName() << "\n";
+ continue;
+ }
+
+ TripletResult FuncResult = generateTriplets(*MF);
+ Result.MaxRelation = std::max(Result.MaxRelation, FuncResult.MaxRelation);
+ Result.Triplets.insert(Result.Triplets.end(), FuncResult.Triplets.begin(),
+ FuncResult.Triplets.end());
+ }
+
+ return Result;
+}
+
+void MIR2VecTool::writeTripletsToStream(const Module &M,
+ raw_ostream &OS) const {
+ auto Result = generateTriplets(M);
+ OS << "MAX_RELATION=" << Result.MaxRelation << '\n';
+ for (const auto &T : Result.Triplets)
+ OS << T.Head << '\t' << T.Tail << '\t' << T.Relation << '\n';
+}
+
+EntityList MIR2VecTool::collectEntityMappings() const {
+ if (!Vocab) {
+ WithColor::error(errs(), ToolName)
+ << "Vocabulary must be initialized for entity mappings.\n";
+ return {};
+ }
+
+ const unsigned EntityCount = Vocab->getCanonicalSize();
+ EntityList Result;
+ for (unsigned EntityID = 0; EntityID < EntityCount; ++EntityID)
+ Result.push_back(Vocab->getStringKey(EntityID));
+
+ return Result;
+}
+
+void MIR2VecTool::writeEntitiesToStream(raw_ostream &OS) const {
+ auto Entities = collectEntityMappings();
+ if (Entities.empty())
+ return;
+
+ OS << Entities.size() << "\n";
+ for (unsigned EntityID = 0; EntityID < Entities.size(); ++EntityID)
+ OS << Entities[EntityID] << '\t' << EntityID << '\n';
+}
+
+void MIR2VecTool::writeEmbeddingsToStream(const Module &M, raw_ostream &OS,
+ EmbeddingLevel Level) const {
+ if (!Vocab) {
+ WithColor::error(errs(), ToolName) << "Vocabulary not initialized.\n";
+ return;
+ }
+
+ for (const Function &F : M.getFunctionDefs()) {
+ MachineFunction *MF = MMI.getMachineFunction(F);
+ if (!MF) {
+ WithColor::warning(errs(), ToolName)
+ << "No MachineFunction for " << F.getName() << "\n";
+ continue;
+ }
+
+ writeEmbeddingsToStream(*MF, OS, Level);
+ }
+}
+
+void MIR2VecTool::writeEmbeddingsToStream(MachineFunction &MF, raw_ostream &OS,
+ EmbeddingLevel Level) const {
+ if (!Vocab) {
+ WithColor::error(errs(), ToolName) << "Vocabulary not initialized.\n";
+ return;
+ }
+
+ auto Emb = MIREmbedder::create(MIR2VecKind::Symbolic, MF, *Vocab);
+ if (!Emb) {
+ WithColor::error(errs(), ToolName)
+ << "Failed to create embedder for " << MF.getName() << "\n";
+ return;
+ }
+
+ OS << "MIR2Vec embeddings for machine function " << MF.getName() << ":\n";
+
+ // Generate embeddings based on the specified level
+ switch (Level) {
+ case FunctionLevel:
+ OS << "Function vector: ";
+ Emb->getMFunctionVector().print(OS);
+ break;
+ case BasicBlockLevel:
+ OS << "Basic block vectors:\n";
+ for (const MachineBasicBlock &MBB : MF) {
+ OS << "MBB " << MBB.getName() << ": ";
+ Emb->getMBBVector(MBB).print(OS);
+ }
+ break;
+ case InstructionLevel:
+ OS << "Instruction vectors:\n";
+ for (const MachineBasicBlock &MBB : MF) {
+ for (const MachineInstr &MI : MBB) {
+ OS << MI << " -> ";
+ Emb->getMInstVector(MI).print(OS);
+ }
+ }
+ break;
+ }
+}
+
+} // namespace mir2vec
+
+} // namespace llvm
\ No newline at end of file
diff --git a/llvm/tools/llvm-ir2vec/llvm-ir2vec.h b/llvm/tools/llvm-ir2vec/lib/emb-tool.h
similarity index 98%
rename from llvm/tools/llvm-ir2vec/llvm-ir2vec.h
rename to llvm/tools/llvm-ir2vec/lib/emb-tool.h
index 566c362edbd22..24b8022ed7482 100644
--- a/llvm/tools/llvm-ir2vec/llvm-ir2vec.h
+++ b/llvm/tools/llvm-ir2vec/lib/emb-tool.h
@@ -12,8 +12,8 @@
///
...
[truncated]
``````````
</details>
https://github.com/llvm/llvm-project/pull/173194
More information about the llvm-commits
mailing list