MCPcopy Index your code
hub / github.com/TheDan64/inkwell

github.com/TheDan64/inkwell @0.9.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release 0.9.0 ↗ · + Follow
1,713 symbols 7,209 edges 78 files 616 documented · 36%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Inkwell(s)

Crates.io Build Status codecov lines of code Join the chat at https://gitter.im/inkwell-rs/Lobby Minimum rustc 1.85

It's a New Kind of Wrapper for Exposing LLVM (Safely)

Inkwell aims to help you pen your own programming languages by safely wrapping llvm-sys. It provides a more strongly typed interface than the underlying LLVM C API so that certain types of errors can be caught at compile time instead of at LLVM's runtime. This means we are trying to replicate LLVM IR's strong typing as closely as possible. The ultimate goal is to make LLVM safer from the rust end and a bit easier to learn (via documentation) and use.

Requirements

  • Rust 1.85+
  • One of LLVM 11-22

Usage

You'll need to point your Cargo.toml to use a single LLVM version feature flag corresponding to your LLVM version as such:

[dependencies]
inkwell = { version = "0.8.0", features = ["llvm22-1"] }

Supported versions: LLVM 11-22 mapping to a cargo feature flag llvmM-0 where M corresponds to the LLVM major version.

Please be aware that we may make breaking changes on master from time to time since we are pre-v1.0.0, in compliance with semver. Please prefer a crates.io release whenever possible!

Documentation

Documentation is automatically deployed here based on master. These docs are not yet 100% complete and only show the latest supported LLVM version due to a rustdoc issue. See #2 for more info.

Examples

Tari's llvm-sys example written in safe code1 with Inkwell:

use inkwell::builder::Builder;
use inkwell::context::Context;
use inkwell::execution_engine::{ExecutionEngine, JitFunction};
use inkwell::module::Module;
use inkwell::OptimizationLevel;

use std::error::Error;

/// Convenience type alias for the `sum` function.
///
/// Calling this is innately `unsafe` because there's no guarantee it doesn't
/// do `unsafe` operations internally.
type SumFunc = unsafe extern "C" fn(u64, u64, u64) -> u64;

struct CodeGen<'ctx> {
    context: &'ctx Context,
    module: Module<'ctx>,
    builder: Builder<'ctx>,
    execution_engine: ExecutionEngine<'ctx>,
}

impl<'ctx> CodeGen<'ctx> {
    fn jit_compile_sum(&self) -> Option<JitFunction<'_, SumFunc>> {
        let i64_type = self.context.i64_type();
        let fn_type = i64_type.fn_type(&[i64_type.into(), i64_type.into(), i64_type.into()], false);
        let function = self.module.add_function("sum", fn_type, None);
        let basic_block = self.context.append_basic_block(function, "entry");

        self.builder.position_at_end(basic_block);

        let x = function.get_nth_param(0)?.into_int_value();
        let y = function.get_nth_param(1)?.into_int_value();
        let z = function.get_nth_param(2)?.into_int_value();

        let sum = self.builder.build_int_add(x, y, "sum").unwrap();
        let sum = self.builder.build_int_add(sum, z, "sum").unwrap();

        self.builder.build_return(Some(&sum)).unwrap();

        unsafe { self.execution_engine.get_function("sum").ok() }
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    let context = Context::create();
    let module = context.create_module("sum");
    let execution_engine = module.create_jit_execution_engine(OptimizationLevel::None)?;
    let codegen = CodeGen {
        context: &context,
        module,
        builder: context.create_builder(),
        execution_engine,
    };

    let sum = codegen.jit_compile_sum().ok_or("Unable to JIT compile `sum`")?;

    let x = 1u64;
    let y = 2u64;
    let z = 3u64;

    unsafe {
        println!("{} + {} + {} = {}", x, y, z, sum.call(x, y, z));
        assert_eq!(sum.call(x, y, z), x + y + z);
    }

    Ok(())
}

1 There are two uses of unsafe in this example because the actual act of compiling and executing code on the fly is innately unsafe. For one, there is no way of verifying we are calling get_function() with the right function signature. It is also unsafe to call the function we get because there's no guarantee the code itself doesn't do unsafe things internally (the same reason you need unsafe when calling into C).

LLVM's Kaleidoscope Tutorial

Can be found in the examples directory.

Alternative Crate(s)

Contributing

Check out our Contributing Guide

Extension points exported contracts — how you extend this code

AsDIScope (Interface)
Specific scopes (i.e. `DILexicalBlock`) can be turned into a `DIScope` with the `AsDIScope::as_debug_info_scope` trait m [9 …
src/debug_info.rs
AsTypeRef (Interface)
Accessor to the inner LLVM type reference [11 implementers]
src/types/traits.rs
AsValueRef (Interface)
This is an ugly privacy hack so that Type can stay private to this module and so that super traits using this trait will [14 …
src/values/traits.rs
PassManagerSubType (Interface)
This is an ugly privacy hack so that PassManagerSubType can stay private to this module and so that super traits using t [2 …
src/passes.rs
AsContextRef (Interface)
This trait abstracts an LLVM `Context` type and should be implemented with caution. [2 implementers]
src/context.rs
UnsafeFunctionPointer (Interface)
Marker trait representing an unsafe function pointer (`unsafe extern "C" fn(A, B, ...) -> Output`). [1 implementers]
src/execution_engine.rs
McjitMemoryManager (Interface)
A trait for user-defined memory management in MCJIT. Implementors can override how LLVM's MCJIT engine allocates memory [1 …
src/memory_manager.rs
DIFlagsConstants (Interface)
(no doc) [1 implementers]
src/debug_info.rs

Core symbols most depended-on inside this repo

as_value_ref
called by 245
src/values/fn_value.rs
as_ptr
called by 207
src/targets.rs
append_basic_block
called by 150
src/context.rs
create_module
called by 141
src/context.rs
position_at_end
called by 133
src/builder.rs
to_c_str
called by 131
src/support/mod.rs
add_function
called by 130
src/module.rs
fn_type
called by 130
src/types/int_type.rs

Shape

Method 1,321
Function 221
Class 112
Enum 38
Interface 21

Languages

Rust100%

Modules by API surface

src/builder.rs119 symbols
src/passes.rs111 symbols
src/targets.rs86 symbols
src/values/instruction_value.rs71 symbols
src/debug_info.rs63 symbols
src/module.rs59 symbols
src/values/int_value.rs55 symbols
src/values/fn_value.rs55 symbols
src/context.rs48 symbols
src/execution_engine.rs43 symbols
src/values/global_value.rs40 symbols
examples/kaleidoscope/implementation_typed_pointers.rs40 symbols

For agents

$ claude mcp add inkwell \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact