jit

package
v0.4.24 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 21, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

pkg/jit/cache.go Function compilation cache for JIT

pkg/jit/call.go Call trampoline for JIT <-> Go transitions

pkg/jit/codegen.go x86-64 Code Generator for JIT compilation

pkg/jit/codegen_ext.go Extended x86-64 Code Generator with function call support

pkg/jit/codegen_optimized.go Optimized x86-64 code generator that uses hardware registers for VM registers

pkg/jit/jit.go JIT Compiler for Xxlang VM - Pure Go Implementation Generates x86-64 machine code at runtime

pkg/jit/jit_bridge.go JIT code execution bridge that avoids Go stack management issues

pkg/jit/jit_fib.go JIT compilation support for recursive Fibonacci functions Supports both tail-recursive and non-tail-recursive implementations

pkg/jit/jit_full.go Full JIT implementation with function call support via interpreter callback

pkg/jit/jit_recursive.go JIT compilation for recursive functions with call inlining

pkg/jit/jit_simple.go Simplified JIT implementation with correct code generation

pkg/jit/jit_true_recursive.go JIT compilation that supports TRUE recursive execution (not transformation to iteration) This generates native code that actually performs recursive calls via the call instruction

pkg/jit/jit_vm.go JIT-enabled VM that combines interpreter with JIT compilation

pkg/jit/native_codegen.go Pure native x86-64 code generator for JIT Generates self-contained native code without VM callbacks

pkg/jit/native_executor.go Native JIT executor that runs compiled x86-64 code directly

Index

Constants

View Source
const (
	// Value tag constants
	TagInt  = 0x7FFC
	TagBool = 0x7FFD
	TagNull = 0x7FFE
)

Register allocation for x86-64

View Source
const FibSavedRegsSize = 48

SavedRegsSize is the bytes used for saved callee-saved registers on stack Layout: rbp(8) + rbx(8) + r12(8) + r13(8) + r14(8) + r15(8) = 48 bytes Local variables start at [rbp - SavedRegsSize - localOffset]

View Source
const SavedRegsSize = 48

SavedRegsSize is the bytes used for saved callee-saved registers on stack Layout: rbp(8) + rbx(8) + r12(8) + r13(8) + r14(8) + r15(8) = 48 bytes Local variables start at [rbp - SavedRegsSize - localOffset]

Variables

View Source
var TrampolineEntry uintptr

TrampolineEntry is the assembly stub that bridges JIT to Go This is implemented in assembly for each platform

Functions

func CallBuiltinFromNative

func CallBuiltinFromNative(builtinIdx, numArgs int, argsPtr *int64) int64

CallBuiltinFromNative is called from native code to execute a builtin function This is exported for use by the JIT callback mechanism

func CallCollectionFromNative

func CallCollectionFromNative(opKind, numArgs int, argsPtr *int64) int64

CallCollectionFromNative is called from native code to perform collection operations opKind: the operation kind (CollectionOpKind, defined in native_codegen.go) argsPtr: pointer to args array (operation-specific) Returns the result (for get operations) or 0

func CallFromJIT

func CallFromJIT(fnPtr uintptr, args *vm.Value, numArgs int) int64

CallFromJIT is called from JIT code to execute a function This is the Go-side handler for JIT function calls

func CallFunctionFromNative

func CallFunctionFromNative(funcReg, numArgs int, argsPtr *int64) int64

CallFunctionFromNative is called from native code to dispatch a function call funcReg: the register number containing the function value numArgs: number of arguments argsPtr: pointer to args array (int64 values) Returns the result of the function call

func CallJITFunction

func CallJITFunction(entry uintptr, args []vm.Value) vm.Value

CallJITFunction calls a JIT-compiled function from Go

func CallMethodFromNative

func CallMethodFromNative(methodHandle, numArgs int, argsPtr *int64) int64

CallMethodFromNative is called from native code to invoke a method methodHandle: handle to the MethodWrapper argsPtr: pointer to additional arguments (excluding receiver) Returns the method result

func CallNativeCode

func CallNativeCode(codePtr uintptr, arg int64) int64

CallNativeCode calls JIT-compiled native code This is a wrapper that avoids Go's stack management issues

func CallObjectFromNative

func CallObjectFromNative(opKind, numArgs int, argsPtr *int64, nameIdx int) int64

CallObjectFromNative is called from native code to perform object field operations opKind: the operation kind (ObjectOpKind, defined in native_codegen.go) argsPtr: pointer to args array nameIdx: index in string constants for field/method name Returns the result (for get operations) or 0

func CanExecuteNatively

func CanExecuteNatively(fn *compiler.CompiledFunction) bool

CanExecuteNatively checks if a function can be executed natively Functions must meet these criteria:

  • No function calls (OpRegCall or OpRegTailCall)
  • No builtin calls
  • No array/map operations
  • Only: LoadConst, Move, Add, Sub, Mul, Div, Mod, Neg Less, Greater, Equal, NotEqual, LessEqual, GreaterEqual Jump, JumpIfTrue, JumpIfFalse, Return, Null, True, False LoadGlobal, StoreGlobal (with globals pointer passed as argument) LoadLocal, StoreLocal (local variables)

func CanExecuteNativelyWithArrays

func CanExecuteNativelyWithArrays(fn *compiler.CompiledFunction) bool

CanExecuteNativelyWithArrays checks if a function can be executed natively with array/map support

func CanExecuteNativelyWithBuiltins

func CanExecuteNativelyWithBuiltins(fn *compiler.CompiledFunction) bool

CanExecuteNativelyWithBuiltins checks if a function can be executed natively with builtin callback support

func CanExecuteNativelyWithCalls

func CanExecuteNativelyWithCalls(fn *compiler.CompiledFunction) bool

CanExecuteNativelyWithCalls checks if a function can be executed natively with function call support

func CanExecuteNativelyWithObjects

func CanExecuteNativelyWithObjects(fn *compiler.CompiledFunction) bool

CanExecuteNativelyWithObjects checks if a function can be executed natively with object support

func GetBuiltinCallbackPtr

func GetBuiltinCallbackPtr() uintptr

GetBuiltinCallbackPtr returns the function pointer for builtin callbacks This returns the address of the assembly wrapper that can be called from native code

func GetCollectionCallbackPtr

func GetCollectionCallbackPtr() uintptr

GetCollectionCallbackPtr returns the function pointer for collection operations

func GetFunctionCallbackPtr

func GetFunctionCallbackPtr() uintptr

GetFunctionCallbackPtr returns the function pointer for function call dispatch

func GetObjectCallbackPtr

func GetObjectCallbackPtr() uintptr

GetObjectCallbackPtr returns the function pointer for object operations

func InitJITCallbackContext

func InitJITCallbackContext(globals, constants []vm.Value)

InitJITCallbackContext initializes the global JIT callback context

func JITCallFunc

func JITCallFunc(fnPtr uintptr, argsPtr *vm.Value, numArgs int, constantsPtr *vm.Value, numConstants int) int64

JITCallFunc executes a function call from JIT code This is the main entry point for JIT -> Interpreter transitions

func ResetJITCallbackContext

func ResetJITCallbackContext()

ResetJITCallbackContext clears all cached data in the JIT context This should be called between different program executions to prevent memory leaks

func SetCurrentRegisters

func SetCurrentRegisters(regs []vm.Value)

SetCurrentRegisters sets the current frame registers for callbacks

func SetNativeFunctionRegistry

func SetNativeFunctionRegistry(funcs map[int]*NativeCompiledFunc)

SetNativeFunctionRegistry sets the native function registry for callbacks

func SimpleNativeCall

func SimpleNativeCall(code []byte, arg int64) int64

SimpleNativeCall provides a simple way to call JIT code It uses a minimal wrapper to avoid stack issues

func UsesClosures

func UsesClosures(fn *compiler.CompiledFunction) bool

UsesClosures checks if a function contains closure-related opcodes Functions with closures cannot be executed natively and fall back to interpreter

func WarmupFunction

func WarmupFunction(fn *compiler.CompiledFunction, count int)

WarmupFunction pre-warms the cache by recording executions

Types

type CacheConfig

type CacheConfig struct {
	// HotThreshold is the execution count before JIT compilation
	HotThreshold int64

	// MaxEntries limits the cache size
	MaxEntries int

	// MaxCodeSize limits bytecode size for compilation
	MaxCodeSize int
}

CacheConfig holds cache configuration

func DefaultCacheConfig

func DefaultCacheConfig() CacheConfig

DefaultCacheConfig returns default cache configuration

type CacheEntry

type CacheEntry struct {
	// Bytecode hash
	Hash uint64

	// Compiled function
	Compiled *CompiledFunc

	// Original bytecode (for verification)
	Bytecode []byte

	// Function info
	NumParams int
	NumLocals int

	// Compilation state
	State CompilationState

	// Execution count at compilation time
	CompileCount int64
}

CacheEntry represents a cached compiled function

type CacheStats

type CacheStats struct {
	Hits      int64
	Misses    int64
	Compiles  int64
	Evictions int64
}

CacheStats holds cache statistics

type CallContext

type CallContext struct {
	// Registers for current frame
	Registers [256]vm.Value

	// Constants and globals
	Constants []vm.Value
	Globals   []vm.Value

	// Function being executed
	Function *compiler.CompiledFunction

	// Call depth for recursion limit
	Depth int
}

CallContext holds the execution context for JIT function calls

type CallFrame

type CallFrame struct {
	// Registers
	Registers [256]vm.Value

	// Return address (for JIT calls)
	ReturnAddr uintptr

	// Return value
	ReturnVal vm.Value

	// Function being executed
	Fn *FuncInfo
}

CallFrame represents a call frame for JIT <-> Go transitions

type CallTrampoline

type CallTrampoline struct {
	// contains filtered or unexported fields
}

CallTrampoline manages transitions between JIT code and Go interpreter

func GetTrampoline

func GetTrampoline() *CallTrampoline

GetTrampoline returns the global trampoline instance

func (*CallTrampoline) CompileFunction

func (t *CallTrampoline) CompileFunction(fn *compiler.CompiledFunction, constants, globals []vm.Value) (*CompiledFunc, error)

CompileFunction attempts to JIT compile a function

func (*CallTrampoline) GetFunction

func (t *CallTrampoline) GetFunction(fn *compiler.CompiledFunction) *FuncInfo

GetFunction retrieves a registered function

func (*CallTrampoline) RegisterFunction

func (t *CallTrampoline) RegisterFunction(fn *compiler.CompiledFunction, constants []vm.Value) *FuncInfo

RegisterFunction registers a function for JIT calls

func (*CallTrampoline) SetContext

func (t *CallTrampoline) SetContext(constants, globals []vm.Value)

SetContext sets the constants and globals for the current execution

func (*CallTrampoline) SetJIT

func (t *CallTrampoline) SetJIT(jit *JITCompiler)

SetJIT sets the JIT compiler instance

type CodeGenerator

type CodeGenerator struct {
	// contains filtered or unexported fields
}

CodeGenerator generates x86-64 machine code

func NewCodeGenerator

func NewCodeGenerator(config JITConfig) *CodeGenerator

NewCodeGenerator creates a new code generator

func (*CodeGenerator) Generate

func (cg *CodeGenerator) Generate(fn *compiler.CompiledFunction, constants []vm.Value, globals []vm.Value) ([]byte, error)

Generate generates x86-64 code from VM bytecode

type CodePage

type CodePage struct {
	Data []byte
	Used int
}

CodePage represents a page of executable memory

type CollectionOpKind

type CollectionOpKind int

CollectionOpKind indicates what collection operation to perform (must match native_executor.go)

const (
	OpArrayCreate CollectionOpKind = iota
	OpArrayEmpty
	OpArrayAppend
	OpArrayGet
	OpArraySet
	OpMapCreate
	OpMapEmpty
	OpMapSet
	OpMapGet
)

type CompilationState

type CompilationState int32

CompilationState represents the state of compilation

const (
	StateNotCompiled CompilationState = iota
	StateCompiling
	StateCompiled
	StateFailed
)

type CompiledFunc

type CompiledFunc struct {
	// Entry point to the compiled code
	Entry uintptr
	// Code page containing the compiled code
	Page *CodePage
	// Size of compiled code
	Size int
	// Bytecode hash for cache invalidation
	Hash uint64
	// Number of locals/registers needed
	NumRegs int
	// Number of parameters
	NumParams int
}

CompiledFunc represents a JIT-compiled function

func CompileAndCache

func CompileAndCache(jit *JITCompiler, fn *compiler.CompiledFunction, constants, globals []vm.Value) (*CompiledFunc, error)

CompileAndCache compiles a function and caches the result

func (*CompiledFunc) Execute

func (cf *CompiledFunc) Execute() int64

Execute runs a compiled function

func (*CompiledFunc) GetFunctionPointer

func (cf *CompiledFunc) GetFunctionPointer() uintptr

GetFunctionPointer returns a callable pointer for the compiled function

type ExtendedCodeGenerator

type ExtendedCodeGenerator struct {
	// contains filtered or unexported fields
}

ExtendedCodeGenerator generates x86-64 machine code with function support

func NewExtendedCodeGenerator

func NewExtendedCodeGenerator(config JITConfig) *ExtendedCodeGenerator

NewExtendedCodeGenerator creates a new extended code generator

func (*ExtendedCodeGenerator) Generate

func (cg *ExtendedCodeGenerator) Generate(fn *compiler.CompiledFunction, constants []vm.Value, globals []vm.Value) ([]byte, error)

Generate generates x86-64 code from VM bytecode with extended support

func (*ExtendedCodeGenerator) SetInterpreterCallback

func (cg *ExtendedCodeGenerator) SetInterpreterCallback(ptr uintptr)

SetInterpreterCallback sets the interpreter callback function pointer

type FibJITCompiler

type FibJITCompiler struct {
	// contains filtered or unexported fields
}

FibJITCompiler is a specialized JIT compiler for recursive Fibonacci It transforms recursive calls into iterative code with explicit stack

func NewFibJITCompiler

func NewFibJITCompiler(config JITConfig) *FibJITCompiler

NewFibJITCompiler creates a new Fibonacci JIT compiler

func (*FibJITCompiler) Compile

func (c *FibJITCompiler) Compile(fn *compiler.CompiledFunction, constants []vm.Value, globals []vm.Value) ([]byte, error)

Compile compiles a recursive Fibonacci function to native code Returns the compiled code or an error if the function is not suitable

type FullCodeGenerator

type FullCodeGenerator struct {
	// contains filtered or unexported fields
}

FullCodeGenerator generates x86-64 code with interpreter callback support

func NewFullCodeGenerator

func NewFullCodeGenerator(config FullJITConfig) *FullCodeGenerator

NewFullCodeGenerator creates a new code generator

func (*FullCodeGenerator) Generate

func (cg *FullCodeGenerator) Generate(fn *compiler.CompiledFunction, constants []vm.Value, globals []vm.Value) ([]byte, error)

Generate generates machine code for a function

func (*FullCodeGenerator) HasCalls

func (cg *FullCodeGenerator) HasCalls() bool

HasCalls returns true if the function has calls

type FullJITCompiler

type FullJITCompiler struct {
	// contains filtered or unexported fields
}

FullJITCompiler handles JIT compilation with interpreter fallback

func NewFullJITCompiler

func NewFullJITCompiler(config FullJITConfig) *FullJITCompiler

NewFullJITCompiler creates a new full JIT compiler

func (*FullJITCompiler) Cleanup

func (j *FullJITCompiler) Cleanup()

Cleanup releases all resources

func (*FullJITCompiler) RecordExecution

func (j *FullJITCompiler) RecordExecution(fn *compiler.CompiledFunction) bool

RecordExecution records an execution for hot path detection

func (*FullJITCompiler) ShouldCompile

func (j *FullJITCompiler) ShouldCompile(fn *compiler.CompiledFunction) bool

ShouldCompile returns true if the function should be JIT compiled

type FullJITConfig

type FullJITConfig struct {
	HotThreshold int
	MaxCodeSize  int
	Debug        bool
}

FullJITConfig holds configuration for the full JIT compiler

func DefaultFullJITConfig

func DefaultFullJITConfig() FullJITConfig

DefaultFullJITConfig returns default configuration

type FullJITVM

type FullJITVM struct {
	*vm.RegVM
	// contains filtered or unexported fields
}

FullJITVM wraps a register VM with full JIT support

func NewFullJITVM

func NewFullJITVM(bytecode *compiler.Bytecode, config FullJITConfig) *FullJITVM

NewFullJITVM creates a new JIT-enabled VM

func NewFullJITVMWithGlobals

func NewFullJITVMWithGlobals(bytecode *compiler.Bytecode, globals []vm.Value, config FullJITConfig) *FullJITVM

NewFullJITVMWithGlobals creates a JIT VM with custom globals

func (*FullJITVM) Cleanup

func (j *FullJITVM) Cleanup()

Cleanup releases JIT resources

func (*FullJITVM) GetJITStats

func (j *FullJITVM) GetJITStats() JITStats

GetJITStats returns JIT statistics

func (*FullJITVM) Run

func (j *FullJITVM) Run() error

Run executes bytecode with JIT optimization for hot paths

func (*FullJITVM) SetJITEnabled

func (j *FullJITVM) SetJITEnabled(enabled bool)

SetJITEnabled enables or disables JIT

type FuncInfo

type FuncInfo struct {
	Fn        *compiler.CompiledFunction
	IsJITed   bool
	Entry     uintptr // JIT entry point if compiled
	NumParams int
	NumLocals int
	Constants []vm.Value
	FreeVars  []vm.Value
}

FuncInfo contains information about a callable function

type FunctionCache

type FunctionCache struct {
	// contains filtered or unexported fields
}

FunctionCache manages JIT-compiled function caching

func GetGlobalCache

func GetGlobalCache() *FunctionCache

GetGlobalCache returns the global function cache

func NewFunctionCache

func NewFunctionCache(config CacheConfig) *FunctionCache

NewFunctionCache creates a new function cache

func (*FunctionCache) Clear

func (c *FunctionCache) Clear()

Clear clears the cache

func (*FunctionCache) Get

func (c *FunctionCache) Get(hash uint64) *CacheEntry

Get retrieves a cached entry

func (*FunctionCache) GetByBytecode

func (c *FunctionCache) GetByBytecode(bytecode []byte) *CacheEntry

GetByBytecode retrieves a cached entry by bytecode

func (*FunctionCache) GetCompiledFunction

func (c *FunctionCache) GetCompiledFunction(fn *compiler.CompiledFunction) *CompiledFunc

GetCompiledFunction returns the compiled function if available

func (*FunctionCache) GetExecutionCount

func (c *FunctionCache) GetExecutionCount(fn *compiler.CompiledFunction) int64

GetExecutionCount returns the execution count for a function

func (*FunctionCache) GetStats

func (c *FunctionCache) GetStats() CacheStats

GetStats returns cache statistics

func (*FunctionCache) IsCompiled

func (c *FunctionCache) IsCompiled(fn *compiler.CompiledFunction) bool

IsCompiled returns true if the function is JIT compiled

func (*FunctionCache) MarkFailed

func (c *FunctionCache) MarkFailed(fn *compiler.CompiledFunction)

MarkFailed marks a function compilation as failed

func (*FunctionCache) Put

Put stores a compiled function in the cache

func (*FunctionCache) RecordExecution

func (c *FunctionCache) RecordExecution(fn *compiler.CompiledFunction) bool

RecordExecution records a function execution for hot path detection Returns true if the function should be JIT compiled

func (*FunctionCache) ShouldCompile

func (c *FunctionCache) ShouldCompile(fn *compiler.CompiledFunction) bool

ShouldCompile returns true if the function should be compiled

func (*FunctionCache) StartCompiling

func (c *FunctionCache) StartCompiling(fn *compiler.CompiledFunction) *CacheEntry

StartCompiling marks a function as being compiled

type FunctionDispatchInfo

type FunctionDispatchInfo struct {
	Kind      FunctionDispatchKind
	Entry     uintptr // For native functions
	ConstIdx  int     // Index in constants table
	NumParams int     // Number of parameters
	NumFree   int     // Number of free variables (for closures)
}

FunctionDispatchInfo contains information about a function to dispatch to

type FunctionDispatchKind

type FunctionDispatchKind int

FunctionDispatchKind indicates what kind of function was found

const (
	DispatchInvalid FunctionDispatchKind = iota
	DispatchNative                       // Has native compiled code
	DispatchClosure                      // Closure (requires interpreter)
	DispatchFunc                         // Regular compiled function (no native version)
	DispatchBuiltin                      // Builtin function
)

type JITCallFrame

type JITCallFrame struct {
	Registers   [256]vm.Value
	ReturnIP    int
	ReturnValue vm.Value
}

JITCallFrame represents a saved frame for recursive JIT calls

type JITCallbackContext

type JITCallbackContext struct {
	// contains filtered or unexported fields
}

JITCallbackContext holds context for JIT callbacks to Go

type JITCompiler

type JITCompiler struct {
	// contains filtered or unexported fields
}

JITCompiler handles JIT compilation of VM bytecode

func NewJITCompiler

func NewJITCompiler(config JITConfig) *JITCompiler

NewJITCompiler creates a new JIT compiler

func (*JITCompiler) AllocCode

func (j *JITCompiler) AllocCode(size int) ([]byte, *CodePage, error)

allocCode allocates code in an executable page

func (*JITCompiler) Cleanup

func (j *JITCompiler) Cleanup()

Cleanup releases all JIT resources

func (*JITCompiler) Compile

func (j *JITCompiler) Compile(fn *compiler.CompiledFunction, constants []vm.Value, globals []vm.Value) (*CompiledFunc, error)

Compile compiles a function to native code

func (*JITCompiler) GetCompiled

func (j *JITCompiler) GetCompiled(fn *compiler.CompiledFunction) *CompiledFunc

GetCompiled returns a cached compiled function

func (*JITCompiler) GetStats

func (j *JITCompiler) GetStats() JITStats

GetStats returns current JIT statistics

func (*JITCompiler) RecordExecution

func (j *JITCompiler) RecordExecution(fn *compiler.CompiledFunction) bool

RecordExecution records an execution for hot path detection

func (*JITCompiler) ShouldCompile

func (j *JITCompiler) ShouldCompile(fn *compiler.CompiledFunction) bool

ShouldCompile returns true if the function should be JIT compiled

type JITConfig

type JITConfig struct {
	// Minimum execution count before JIT compilation
	HotThreshold int
	// Maximum code size to JIT compile (in bytes)
	MaxCodeSize int
	// Enable debug output
	Debug bool
}

JITConfig holds configuration for the JIT compiler

func DefaultJITConfig

func DefaultJITConfig() JITConfig

DefaultJITConfig returns default JIT configuration

type JITStats

type JITStats struct {
	CompiledFunctions int64
	CacheHits         int64
	CacheMisses       int64
	TotalCodeSize     int64
}

JITStats tracks JIT compilation statistics

type JITVM

type JITVM struct {
	*vm.RegVM
	// contains filtered or unexported fields
}

JITVM wraps a register VM with JIT compilation capability

func NewJITVM

func NewJITVM(bytecode *compiler.Bytecode, config JITConfig) *JITVM

NewJITVM creates a new JIT-enabled VM

func NewJITVMWithGlobals

func NewJITVMWithGlobals(bytecode *compiler.Bytecode, globals []vm.Value, config JITConfig) *JITVM

NewJITVMWithGlobals creates a JIT VM with custom globals

func NewJITVMWithObjectGlobals

func NewJITVMWithObjectGlobals(bytecode *compiler.Bytecode, globals []objects.Object, config JITConfig) *JITVM

NewJITVMWithObjectGlobals creates a JIT VM with globals as objects.Object

func (*JITVM) Cleanup

func (j *JITVM) Cleanup()

Cleanup releases JIT resources

func (*JITVM) CompileFunction

func (j *JITVM) CompileFunction(fn *compiler.CompiledFunction) (*CompiledFunc, error)

CompileFunction compiles a specific function for JIT execution

func (*JITVM) ExecuteCompiled

func (j *JITVM) ExecuteCompiled(cf *CompiledFunc) int64

ExecuteCompiled executes a previously compiled function

func (*JITVM) ExecuteNativeFunction

func (j *JITVM) ExecuteNativeFunction(constIdx int, args ...int64) (int64, bool)

ExecuteNativeFunction executes a natively-compiled function with arguments

func (*JITVM) GetConstants

func (j *JITVM) GetConstants() []vm.Value

GetConstants returns the VM's constants

func (*JITVM) GetGlobals

func (j *JITVM) GetGlobals() []vm.Value

GetGlobals returns the VM's globals

func (*JITVM) GetJITStats

func (j *JITVM) GetJITStats() JITStats

GetJITStats returns JIT compilation statistics

func (*JITVM) GetNativeStats

func (j *JITVM) GetNativeStats() (nativeExecs, interpExecs int64)

GetNativeStats returns native execution statistics

func (*JITVM) LastPoppedObject

func (j *JITVM) LastPoppedObject() objects.Object

LastPoppedObject returns the last popped object

func (*JITVM) Run

func (j *JITVM) Run() error

Run executes the bytecode with JIT compilation for hot paths

func (*JITVM) RunJIT

func (j *JITVM) RunJIT(fn *compiler.CompiledFunction) (int64, error)

RunJIT attempts to run a function with JIT compilation

func (*JITVM) SetCurrentModule

func (j *JITVM) SetCurrentModule(module *objects.Module)

SetCurrentModule sets the current module context

func (*JITVM) SetJITEnabled

func (j *JITVM) SetJITEnabled(enabled bool)

SetJITEnabled enables or disables JIT compilation

func (*JITVM) SetSourcePath

func (j *JITVM) SetSourcePath(path string)

SetSourcePath sets the source path for error messages

type MethodWrapper

type MethodWrapper struct {
	Receiver objects.Object
	Method   *objects.Builtin
}

MethodWrapper wraps a method with its receiver for JIT callbacks

func (*MethodWrapper) HashKey

func (m *MethodWrapper) HashKey() objects.HashKey

HashKey implements objects.Object

func (*MethodWrapper) Inspect

func (m *MethodWrapper) Inspect() string

Inspect implements objects.Object

func (*MethodWrapper) ToBool

func (m *MethodWrapper) ToBool() *objects.Bool

ToBool implements objects.Object

func (*MethodWrapper) Type

func (m *MethodWrapper) Type() objects.ObjectType

Type implements objects.Object

func (*MethodWrapper) TypeTag

func (m *MethodWrapper) TypeTag() objects.TypeTag

TypeTag implements objects.Object

type NativeCodeGenerator

type NativeCodeGenerator struct {
	// contains filtered or unexported fields
}

NativeCodeGenerator generates pure native x86-64 code No VM context needed - all values are in registers or stack Globals are passed as first argument (in rdi per x86-64 calling convention)

func NewNativeCodeGenerator

func NewNativeCodeGenerator() *NativeCodeGenerator

NewNativeCodeGenerator creates a new native code generator

func NewNativeCodeGeneratorWithCallbacks

func NewNativeCodeGeneratorWithCallbacks() *NativeCodeGenerator

NewNativeCodeGeneratorWithCallbacks creates a code generator with callback pointers set up

func (*NativeCodeGenerator) Generate

func (cg *NativeCodeGenerator) Generate(fn *compiler.CompiledFunction, constants []int64) ([]byte, error)

Generate generates native x86-64 code

func (*NativeCodeGenerator) SetBuiltinCallback

func (cg *NativeCodeGenerator) SetBuiltinCallback(ptr uintptr)

SetBuiltinCallback sets the callback pointer for builtin calls

func (*NativeCodeGenerator) SetCollectionCallback

func (cg *NativeCodeGenerator) SetCollectionCallback(ptr uintptr)

SetCollectionCallback sets the callback pointer for collection operations

func (*NativeCodeGenerator) SetFunctionCallback

func (cg *NativeCodeGenerator) SetFunctionCallback(ptr uintptr)

SetFunctionCallback sets the callback pointer for function calls

func (*NativeCodeGenerator) SetObjectCallback

func (cg *NativeCodeGenerator) SetObjectCallback(ptr uintptr)

SetObjectCallback sets the callback pointer for object operations

type NativeCompiledFunc

type NativeCompiledFunc struct {
	Entry        uintptr   // Native code entry point
	Code         []byte    // Native code bytes
	Page         *CodePage // Memory page (for cleanup)
	NumParams    int       // Number of parameters
	NumLocals    int       // Number of local variables
	Constants    []int64   // Integer constants
	IsRecursive  bool      // True if function is self-recursive
	UseBridgeABI bool      // True if function uses System V ABI (bridge.Call1/2/3)
}

NativeCompiledFunc represents a natively-compiled function

func (*NativeCompiledFunc) Execute

func (f *NativeCompiledFunc) Execute(globals []int64, args ...int64) int64

Execute calls a native function with arguments

type NativeExecutor

type NativeExecutor struct {
	// contains filtered or unexported fields
}

NativeExecutor executes JIT-compiled native code directly

func NewNativeExecutor

func NewNativeExecutor(config JITConfig) *NativeExecutor

NewNativeExecutor creates a new native JIT executor

func (*NativeExecutor) Cleanup

func (ne *NativeExecutor) Cleanup()

Cleanup releases JIT resources

func (*NativeExecutor) CompileProgram

func (ne *NativeExecutor) CompileProgram(bytecode *compiler.Bytecode) (*NativeProgram, error)

CompileProgram compiles a bytecode program to native code

func (*NativeExecutor) ExecuteBytecode

func (ne *NativeExecutor) ExecuteBytecode(bytecode *compiler.Bytecode, globals []int64) (int64, error)

ExecuteBytecode executes a bytecode program natively Returns the result as an int64 (for numeric results)

func (*NativeExecutor) ExecuteFunction

func (ne *NativeExecutor) ExecuteFunction(fn *compiler.CompiledFunction, constants []vm.Value, globals []int64) (int64, error)

ExecuteFunction compiles and executes a function natively with globals

type NativeFunctionRegistry

type NativeFunctionRegistry struct {
	// contains filtered or unexported fields
}

NativeFunctionRegistry manages compiled native functions

func NewNativeFunctionRegistry

func NewNativeFunctionRegistry(config JITConfig) *NativeFunctionRegistry

NewNativeFunctionRegistry creates a new function registry

func (*NativeFunctionRegistry) Cleanup

func (r *NativeFunctionRegistry) Cleanup()

Cleanup releases all compiled functions

func (*NativeFunctionRegistry) CompileFunction

func (r *NativeFunctionRegistry) CompileFunction(fn *compiler.CompiledFunction, constIdx int, constants []int64) error

CompileFunction compiles a function and stores it in the registry

func (*NativeFunctionRegistry) CompileRecursiveFunction

func (r *NativeFunctionRegistry) CompileRecursiveFunction(fn *compiler.CompiledFunction, constIdx int, constants []vm.Value) error

CompileRecursiveFunction compiles a recursive function using the FibJIT compiler. This handles functions that contain OpRegCall (self-recursive) by transforming recursion into iteration. The generated code uses System V AMD64 ABI (args in rdi, rsi, rdx) and is called via bridge.Call1/2/3.

func (*NativeFunctionRegistry) Get

func (r *NativeFunctionRegistry) Get(constIdx int) *NativeCompiledFunc

Get returns a compiled function by its constant index

func (*NativeFunctionRegistry) Has

func (r *NativeFunctionRegistry) Has(constIdx int) bool

Has returns true if a function is compiled at the given index

type NativeProgram

type NativeProgram struct {
	// contains filtered or unexported fields
}

NativeProgram represents a program compiled for native execution

func (*NativeProgram) Run

func (p *NativeProgram) Run(globals []int64) int64

Run executes the native program with globals

type NativeSupportLevel

type NativeSupportLevel int

NativeSupportLevel indicates what level of native support a function has

const (
	// SupportNone indicates the function cannot be executed natively
	SupportNone NativeSupportLevel = iota
	// SupportPureArithmetic indicates pure arithmetic/control flow (no callbacks)
	SupportPureArithmetic
	// SupportWithBuiltins indicates arithmetic + builtin calls (requires callback)
	SupportWithBuiltins
	// SupportWithCalls indicates arithmetic + builtin + function calls
	SupportWithCalls
	// SupportWithArrays indicates arithmetic + builtin + calls + array operations
	SupportWithArrays
	// SupportWithObjects indicates full support including object field access
	SupportWithObjects
	// SupportWithClosures indicates full support including closures (future)
	// Closures are complex because they require capturing free variables and
	// managing the closure context. Functions with closures fall back to the
	// interpreter for correctness.
	SupportWithClosures
)

func AnalyzeNativeSupport

func AnalyzeNativeSupport(fn *compiler.CompiledFunction) NativeSupportLevel

AnalyzeNativeSupport analyzes the bytecode to determine native support level

type ObjectOpKind

type ObjectOpKind int

ObjectOpKind indicates what object operation to perform

const (
	OpGetField ObjectOpKind = iota
	OpSetField
	OpGetMethod
)

type OptimizedCodeGenerator

type OptimizedCodeGenerator struct {
	// contains filtered or unexported fields
}

OptimizedCodeGenerator generates more efficient x86-64 code by using hardware registers (rax, rbx, rcx, rdx, r8-r15) to cache VM registers

func NewOptimizedCodeGenerator

func NewOptimizedCodeGenerator() *OptimizedCodeGenerator

NewOptimizedCodeGenerator creates a new optimized code generator

func (*OptimizedCodeGenerator) Generate

func (cg *OptimizedCodeGenerator) Generate(fn *compiler.CompiledFunction, constants []vm.Value, globals []vm.Value) ([]byte, error)

Generate generates optimized machine code

type RecursionAnalysis

type RecursionAnalysis struct {
	// contains filtered or unexported fields
}

RecursionAnalysis contains analysis results for a function

type RecursiveCodeGenerator

type RecursiveCodeGenerator struct {
	// contains filtered or unexported fields
}

RecursiveCodeGenerator generates optimized code for recursive functions by converting tail recursion to loops

func NewRecursiveCodeGenerator

func NewRecursiveCodeGenerator(config JITConfig) *RecursiveCodeGenerator

NewRecursiveCodeGenerator creates a new recursive code generator

func (*RecursiveCodeGenerator) Generate

func (cg *RecursiveCodeGenerator) Generate(fn *compiler.CompiledFunction, constants []vm.Value, globals []vm.Value) ([]byte, error)

Generate generates code for a function, handling recursion

type RecursiveJITCompiler

type RecursiveJITCompiler struct {
	// contains filtered or unexported fields
}

RecursiveJITCompiler handles JIT compilation of recursive functions by converting recursion to iteration where possible

func NewRecursiveJITCompiler

func NewRecursiveJITCompiler(config JITConfig) *RecursiveJITCompiler

NewRecursiveJITCompiler creates a new recursive JIT compiler

func (*RecursiveJITCompiler) AnalyzeRecursiveFunction

func (r *RecursiveJITCompiler) AnalyzeRecursiveFunction(fn *compiler.CompiledFunction, constants []vm.Value) bool

AnalyzeRecursiveFunction analyzes if a function is self-recursive

type SimpleCodeGenerator

type SimpleCodeGenerator struct {
	// contains filtered or unexported fields
}

SimpleCodeGenerator generates x86-64 code with careful attention to correctness

func NewSimpleCodeGenerator

func NewSimpleCodeGenerator() *SimpleCodeGenerator

NewSimpleCodeGenerator creates a new simple code generator

func (*SimpleCodeGenerator) Generate

func (cg *SimpleCodeGenerator) Generate(fn *compiler.CompiledFunction, constants []vm.Value, globals []vm.Value) ([]byte, error)

Generate generates machine code

func (*SimpleCodeGenerator) SetTrampolineAddress

func (cg *SimpleCodeGenerator) SetTrampolineAddress(code []byte, offset int, addr uintptr)

SetTrampolineAddress patches the trampoline address in generated code This should be called after code generation to set up the actual call target

type TrueRecursiveJITCompiler

type TrueRecursiveJITCompiler struct {
	// contains filtered or unexported fields
}

TrueRecursiveJITCompiler compiles functions with TRUE recursive call support It generates native x86-64 code that uses the call instruction for recursion, maintaining O(2^n) complexity but with native execution speed

func NewTrueRecursiveJITCompiler

func NewTrueRecursiveJITCompiler(config JITConfig) *TrueRecursiveJITCompiler

NewTrueRecursiveJITCompiler creates a compiler that supports true recursion

func (*TrueRecursiveJITCompiler) Compile

func (c *TrueRecursiveJITCompiler) Compile(fn *compiler.CompiledFunction, constants []vm.Value) ([]byte, error)

Compile compiles a recursive function to native code that performs TRUE recursion

func (*TrueRecursiveJITCompiler) GetEntryPoint

func (c *TrueRecursiveJITCompiler) GetEntryPoint() int

GetEntryPoint returns the offset of the function entry point

Directories

Path Synopsis
Package bridge provides assembly bridges for calling JIT-compiled code from Go.
Package bridge provides assembly bridges for calling JIT-compiled code from Go.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL