RFC-028: JIT Compiler — Multi-Tier Execution Engine Within the VM
References:
Abstract
This document proposes introducing the Cranelift JIT compiler into YaoXiang's VM backend, upgrading the VM from a pure interpreter to a multi-tier execution engine: cold code is interpreted, while hot functions are compiled by Cranelift into native code. The JIT path and RFC-018's LLVM AOT path share the IR normalization pass. Cranelift provides fast JIT compilation, while LLVM provides in-depth AOT optimization, allowing each to play to its strengths.
Core positioning: The JIT serves the VM; it does not replace it.
Motivation
Why Is JIT Needed?
The current VM backend is a pure interpreter and executes 10–100 times slower than native code. During development, tests, scripts, and local debugging are run frequently—these scenarios do not require AOT's ultimate optimizations, but they do need execution speeds significantly faster than those of the interpreter.
Why Not Use Only LLVM AOT?
LLVM AOT compilation takes a long time (seconds) and is unsuitable for rapid development iterations. Development requires a "change and run" experience: change one line of code → rerun → see the results almost immediately. Cranelift JIT compilation of a single function takes only 1–5 ms, so users do not perceive the compilation delay.
Why Cranelift Instead of LLVM ORC JIT?
| Dimension | Cranelift JIT | LLVM ORC JIT |
|---|---|---|
| Compilation speed | 1–5 ms/function | 10–100 ms/function |
| Dependency footprint | Small | Large (full LLVM required) |
| Code quality | 70–80% of LLVM -O2 | Extremely high |
| Use cases | Development debugging, rapid iteration | Unsuitable (see the trade-offs discussed here) |
Cranelift compiles quickly and provides sufficient code quality. LLVM is left to AOT for offline, in-depth optimization. Each tool should do one thing well.
Proposal
Core Architecture
VM 执行引擎
├── 解释器层
│ ├── 执行字节码指令
│ ├── 收集热度数据(invocation count + loop backedge count)
│ └── 达到阈值 → 提交编译任务
│
├── JIT 编译层(Cranelift Backend)
│ ├── 编译队列(后台线程,不阻塞解释器)
│ ├── IR → 规范化 → Cranelift IR → 原生代码
│ └── 复用 RFC-018 §4.0 的 IR 规范化 pass(栈→SSA)
│
├── 代码缓存
│ ├── 函数表:函数 ID → {解释器入口, JIT入口(可选)}
│ ├── 编译后函数入口原子替换
│ └── 按模块分组(预留热重载接口)
│
└── 热度分析
├── 每函数调用计数 + 循环回边计数
├── 定时衰减(避免一次性预热触发编译)
└── 三级热度:Cold → Warm → Hot → CompiledIntegration with the Existing Architecture
源码 → 前端(共享)→ IR → ┬→ 字节码 codegen → VM 解释器 → [热函数] → Cranelift JIT
│
└→ LLVM AOT codegen → .o → 链接 → exe(生产)JIT and AOT share the IR normalization pass (middle/passes/ir_normalize.rs); the underlying codegen changes from LLVM to Cranelift.
Execution Flow
函数调用
→ fn_entry.code_ptr.load()
→ ┬─ 解释器 stub(冷状态):逐条解释字节码
└─ JIT 原生代码(热状态):直接执行机器码
→ 返回Detailed Design
1. Directory Structure
src/
├── backends/
│ ├── interpreter/ # Existing — VM interpreter
│ │ └── executor/
│ │ ├── engine.rs # Modified — dispatch calls through FunctionEntry instead of interpreting directly
│ │ └── ...
│ │
│ ├── jit/ # Added — JIT compilation layer
│ │ ├── mod.rs # JIT module entry point; initializes the Cranelift context
│ │ ├── profiler.rs # Hotness counting + decay + threshold decisions
│ │ ├── entry.rs # FunctionEntry + AtomicPtr management
│ │ ├── cache.rs # Code cache (executable page management via mmap)
│ │ ├── compiler.rs # IR → Cranelift IR → native code
│ │ ├── types.rs # YaoXiang type → Cranelift type mapping
│ │ └── abi.rs # Function calling convention (System V / Microsoft x64)
│ │
│ ├── llvm/ # Planned — LLVM AOT (RFC-018)
│ ├── common/ # Existing
│ └── runtime/ # Existing
│
└── middle/
└── passes/
└── ir_normalize.rs # Added — shared IR normalization (stack→SSA)
# Shared by JIT and LLVM AOTKey constraints:
backends/jit/depends only onmiddle/(IR definitions and normalization passes), the standard library, and the Cranelift cratebackends/jit/does not depend onbackends/llvm/; the two are peer backendsbackends/jit/does not depend onbackends/interpreter/; they interact through theFunctionEntryinterface
2. Hotness Analysis and Tiered Triggering
2.1 Hotness State Machine
Cold ──(invocation > 50 或 backedge > 500)──→ Warm
Warm ──(invocation > 200)────────────────────→ Hot
Hot ──(提交编译队列,编译完成)──────────────────→ CompiledThe thresholds are configurable; the values above are the defaults. See the practical threshold ranges of LuaJIT, JVM C1, and V8 Sparkplug (50–1000).
2.2 Counters
Each function maintains two atomic counters in its FunctionEntry (see §4.1):
// Hotness fields of FunctionEntry (full definition in §4.1)
invocation_count: AtomicU32, // Number of times the function is called
backedge_count: AtomicU32, // Number of loop backedge jumps
state: AtomicU8, // Cold | Warm | Hot | Compiled2.3 Decay Mechanism
Every 5 seconds, all counters are shifted right by one bit (multiplied by 0.5). This prevents code that runs frequently but only once at startup, such as an initialization traversal, from triggering pointless JIT compilation.
fn decay(entry: &FunctionEntry) {
entry.invocation_count.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| Some(v >> 1));
entry.backedge_count.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| Some(v >> 1));
}Bit operations avoid division overhead.
2.4 Compilation Queue
解释器线程后台 JIT 线程
│ │
├─ 热度达到 Hot │
├─ 推送编译请求 ─────────────────→ │
│ (不阻塞解释器) ├─ 取出函数 IR
│ ├─ IR 规范化 (栈→SSA)
│ ├─ Cranelift 编译
│ ├─ 写入代码缓存
│ └─ 原子更新函数入口指针
│ 下次调用该函数 ←───────────────── │
│ 直接走原生代码 │While compilation is in progress, the function continues to execute through the interpreter. Once compilation finishes, the next call atomically switches to the JIT code.
3. IR → Cranelift Compilation Pipeline
3.1 Pipeline
YaoXiang IR (栈形式)
→ IR 规范化 pass (栈 → 寄存器/SSA) ← 复用 RFC-018 §4.0
→ Cranelift IR 构建
→ Cranelift 优化 + 机器码生成
→ 写入代码缓存3.2 YaoXiang Type → Cranelift Type
| YaoXiang Type | Cranelift Type | Description |
|---|---|---|
Int | i64 | |
Int32 | i32 | |
Float | f64 | |
Float32 | f32 | |
Bool | i8 | Cranelift has no i1; use i8 |
Char | i32 | Unicode code point |
String | { i64, i64 } | Pointer + length |
Void | Empty tuple | |
&T | — | Zero-sized; eliminated after compilation |
&mut T | — | Zero-sized; eliminated after compilation |
ref T | { i64, i64 } | Reference-counted pointer + data pointer |
*T | i64 | Raw pointer |
List(T) | { i64, i64, i64 } | Data pointer + length + capacity |
| Structure | Cranelift struct | |
| Record enum | { i64, [max_payload] } | Tag + union |
?T | { i8, T } | Presence flag + data |
Compared with the LLVM type table in RFC-018 §3: Cranelift does not distinguish pointer types and has no
i1, making the overall model simpler.
3.3 Key Instruction Translation
| IR Instruction | Cranelift IR |
|---|---|
Add { dst, lhs, rhs } | iadd (integer) / fadd (floating-point) |
Sub { dst, lhs, rhs } | isub / fsub |
Mul { dst, lhs, rhs } | imul / fmul |
Div { dst, lhs, rhs } | sdiv / udiv / fdiv |
Eq { dst, lhs, rhs } | icmp eq / fcmp eq |
Jmp(label) | jump |
JmpIf(cond, label) | brnz |
Ret(Some(v)) | return |
Call { dst, func, args } | call |
Load { dst, src } | load |
Store { dst, src } | store |
Spawn { ... } | Call the runtime's task_spawn + task_wait_all |
See the main RFC text for the complete translation table. The core principle is that the Cranelift instruction set covers every YaoXiang IR operation, with no semantic gaps.
3.4 Two Normalization Schemes Coexist
The VM interpreter requires stack semantics (Push/Pop/Dup/Swap), while the Cranelift JIT and LLVM AOT require registers/SSA. The IR normalization pass performs the conversion once (RFC-018 §4.0), is shared by JIT and AOT, and does not change the IR representation itself. Each backend consumes the same IR according to its own needs.
4. Function Entry Table and Atomic Replacement
4.1 FunctionEntry
struct FunctionEntry {
/// Atomically replaceable execution target
code_ptr: AtomicPtr<u8>,
/// Immutable metadata
bytecode: &'static [u8], // Interpreter fallback
ir: &'static FunctionIR, // Input for JIT compilation
/// Runtime statistics
invocation_count: AtomicU32,
backedge_count: AtomicU32,
state: AtomicU8, // Cold | Warm | Hot | Compiled
}4.2 Entry Dispatch
调用方
→ fn_entry.code_ptr.load(Ordering::Acquire)
→ ┬─ 解释器 stub 地址 → 执行解释器,逐条解释字节码
└─ JIT 代码地址 → 直接跳转原生代码One pointer dereference. Modern CPU branch predictors handle indirect jumps as follows: the first prediction is incorrect, and every subsequent prediction is correct. The overhead is approximately 1 cycle.
4.3 Atomic Switch
After compilation completes, perform one CAS:
fn install_jit_code(entry: &FunctionEntry, jit_code: *mut u8) -> bool {
entry.code_ptr.compare_exchange(
INTERPRETER_STUB, // 期望:仍指向解释器
jit_code, // 替换为:JIT 代码
Ordering::AcqRel,
Ordering::Acquire,
).is_ok()
}The interpreter is not paused, there is no safepoint wait, and call sites are not traversed. A single atomic operation completes the switch.
5. Code Cache
5.1 Structure
CodeCache:
modules:
"main.yao":
functions:
"compute" → FunctionEntry (state: Compiled)
"process" → FunctionEntry (state: Cold)
"init" → FunctionEntry (state: Compiled)
native_pages: [ mmap'd executable memory pages ]
"lib.yao":
functions:
"helper" → FunctionEntry (state: Compiled)
native_pages: [ mmap'd executable memory pages ]5.2 Executable Memory Management
struct NativePage {
ptr: *mut u8,
size: usize,
used: AtomicUsize, // Bytes used
remaining: usize, // Remaining capacity
}
impl CodeCache {
fn allocate(&self, code_size: usize) -> *mut u8;
fn deallocate(&self, ptr: *mut u8, code_size: usize); // 仅在模块失效时调用
}Each module allocates contiguous mmap executable pages, and all JIT functions within a module are allocated from the same page. When a module is invalidated, the entire page is reclaimed, eliminating the need to release each function individually.
6. Hot-Reload Extension Points
The following interfaces compile successfully but are not called until the hot-reload implementation is available. The interface design principle is: the JIT implementation only needs insert and per-function compare_exchange; module-level operations are reserved for hot reload.
/// Code cache extension interface (reserved, not implemented)
trait CodeCacheExt {
/// Invalidate all JIT code for the entire module and fall back to the interpreter
fn invalidate_module(&self, module_path: &str);
/// Invalidate specific functions based on a source location range
fn invalidate_range(&self, file: &str, start: u32, end: u32);
/// Atomically replace the function table for the entire module
fn swap_module(&self, module_path: &str, new_functions: HashMap<String, FunctionEntry>);
}
/// Compilation queue extension interface (reserved, not implemented)
trait CompileQueueExt {
/// Priority enqueueing (hot-reload compilation takes priority over normal JIT compilation)
fn submit_priority(&self, task: CompileTask);
}Why group by module?
JIT itself only needs functions. Organizing them by module is entirely for the benefit of hot reload: after a module is recompiled, its entire function set can be replaced atomically instead of performing a CAS for each function—the latter leads to an inconsistent state when functions have cyclic dependencies.
Trade-offs
Advantages
- No perceptible compilation latency: Cranelift takes 1–5 ms/function, compilation runs on a background thread, and the interpreter does not pause
- Shared infrastructure: JIT and AOT share the IR normalization pass (RFC-018 §4.0), avoiding duplicated implementation
- Non-breaking: This is a purely additive feature. The VM and interpreter remain unchanged; only a faster hot path is added
- No LLVM dependency: The VM does not introduce LLVM, keeping it lightweight
- Natural multi-platform support: Cranelift natively supports x86_64 and ARM64, covering all target platforms
- Hot reload reserved: Grouping the code cache by module and using indirect jumps for function entries lays the structural foundation for future hot reload
Drawbacks
- New Cranelift dependency: Introducing a new external crate requires familiarity with its API
- Debugging complexity: Stack frames in JIT-generated code must be compatible with interpreter stack frames, and debug-information mapping requires additional handling
- Cold-start hotness latency: The program receives no JIT acceleration during its first few seconds while hotness accumulates
- Platform ABI: The mmap and calling conventions of different platforms (Linux/macOS/Windows) require separate adaptations
Consistency with Related RFCs
| RFC | Consistency |
|---|---|
| RFC-018 LLVM AOT | ✅ Shares the IR normalization pass; JIT and AOT are peer backends |
| RFC-024 spawn block concurrency | ✅ spawn blocks are compiled into runtime function calls |
| RFC-008 runtime architecture | ✅ All three runtime tiers (Embedded/Standard/Full) support JIT |
Alternatives
| Approach | Why It Was Not Selected |
|---|---|
| LLVM AOT only, without JIT | Development requires recompiling the entire program, sacrificing the rapid-iteration experience |
| LLVM ORC JIT | High compilation latency (10–100 ms), a large LLVM dependency, and poor suitability for embedding in the VM |
| Custom lightweight JIT (dynasm) | A handwritten backend has high maintenance costs and is less mature than Cranelift |
| Template JIT | No optimization, poor code quality, and wasted JIT compilation time |
| Whole-program JIT (without an interpreter) | Slow cold start; compiling simple scripts is not worthwhile |
Dependencies
- RFC-018 (LLVM AOT) → Shared IR normalization pass
- RFC-024 (spawn block concurrency) → JIT compilation of spawn blocks
- RFC-008 (runtime architecture) → JIT support across all three runtime tiers
- Cranelift crate → JIT backend
References
- Cranelift IR Documentation
- RFC-018: LLVM AOT Compiler Design
- RFC-024: Concurrency Model Based on spawn Blocks
- RFC-008: Design for Decoupling the Runtime Concurrency Model from the Scheduler
- Hölzle, U. (1994). Adaptive Optimization for Self: Reconciling High Performance with Exploratory Programming. Stanford.
Lifecycle and Disposition
| Status | Location | Description |
|---|---|---|
| Draft | docs/src/rfc/draft/ | Author's draft, awaiting submission for review |
| Under Review | docs/src/rfc/review/ | Open for community discussion and feedback |
| Accepted | docs/src/rfc/accepted/ | Becomes an official design document |
