ir

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2026 License: GPL-3.0 Imports: 6 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultStageResultShift = 32

Variables

This section is empty.

Functions

func BuildStandaloneProgramForArch

func BuildStandaloneProgramForArch(arch hv.CpuArchitecture, prog *Program) (asm.Program, error)

BuildStandaloneProgramForArch lowers the requested Program using the backend registered for arch.

func RegisterBackend

func RegisterBackend(arch hv.CpuArchitecture, backend Backend)

RegisterBackend wires an architecture-specific backend into the shared IR helpers. It panics when attempting to register the same architecture more than once so mistakes are caught during init.

Types

type AssignFragment

type AssignFragment struct {
	Dst Fragment
	Src Fragment
}

type Backend

type Backend interface {
	BuildStandaloneProgram(p *Program) (asm.Program, error)
}

Backend exposes the architecture-specific pieces required by the top-level IR helpers (for example BuildStandaloneProgramForArch).

type Block

type Block []Fragment

type CacheFlushFragment added in v0.0.2

type CacheFlushFragment struct {
	// Base is the starting address of the region to flush
	Base Fragment
	// Size is the size of the region in bytes
	Size Fragment
}

CacheFlushFragment represents a cache flush operation for self-modifying code. On ARM64, this performs the full cache maintenance sequence: 1. Clean data cache lines (DC CVAU) for the entire region 2. DSB ISH (data synchronization barrier) 3. Invalidate instruction cache lines (IC IVAU) for the entire region 4. DSB ISH 5. ISB (instruction synchronization barrier) On x86-64, this is a no-op since x86 has coherent instruction caches.

type CallFragment

type CallFragment struct {
	Target Fragment
	Args   []Fragment // Arguments to pass to the function
	Result Var
}

type CompareCondition

type CompareCondition struct {
	Kind  CompareKind
	Left  Fragment
	Right Fragment
}

type CompareKind

type CompareKind int
const (
	CompareEqual CompareKind = iota
	CompareNotEqual
	CompareLess
	CompareLessOrEqual
	CompareGreater
	CompareGreaterOrEqual
)

type Condition

type Condition interface {
	Fragment
}

func IsEqual

func IsEqual(left, right any) Condition

func IsGreaterOrEqual

func IsGreaterOrEqual(left, right any) Condition

func IsGreaterThan

func IsGreaterThan(left, right any) Condition

func IsLessOrEqual

func IsLessOrEqual(left, right any) Condition

func IsLessThan

func IsLessThan(left, right any) Condition

func IsNegative

func IsNegative(value Fragment) Condition

func IsNotEqual

func IsNotEqual(left, right any) Condition

func IsZero

func IsZero(value Fragment) Condition

type ConstantBytesConfig

type ConstantBytesConfig struct {
	// Target selects the asm variable that will reference the constant. Required.
	Target asm.Variable
	// Data provides the literal contents to bind.
	Data []byte
	// ZeroTerminate appends a trailing zero byte when true (unless already
	// present) so the constant can be treated as a C string.
	ZeroTerminate bool
	// Length receives the length of Data before any zero terminator is appended
	// when set. Useful for methods that need the literal size separately.
	Length Var
	// TotalLength receives the full length after optional zero termination when
	// set. Callers can differentiate between the raw length and the encoded size.
	TotalLength Var
	// Pointer optionally receives the address of the constant block. This allows
	// callers to reuse the data without re-encoding string literals.
	Pointer Var
}

ConstantBytesConfig describes how a constant byte slice should be bound to an assembler variable and optionally expose metadata to the IR method.

type ConstantBytesFragment

type ConstantBytesFragment struct {
	Target asm.Variable
	Data   []byte
}

type ConstantPointerFragment

type ConstantPointerFragment struct {
	Target asm.Variable
}

type DeclareParam

type DeclareParam string

type Fragment

type Fragment interface{}

func Assign

func Assign(dst Fragment, src Fragment) Fragment

func AssignGlobal

func AssignGlobal(g GlobalVar, value any) Fragment

AssignGlobal stores value into the provided global variable. It behaves like Assign(g.AsMem(), value) but documents the intent at the call site.

func CacheFlush added in v0.0.2

func CacheFlush(base, size Fragment) Fragment

CacheFlush returns a cache flush fragment for the given memory region. This must be called after writing code to memory and before executing it.

func Call

func Call(target any, result ...Var) Fragment

Call emits an indirect call to the provided target value. When result is specified the callee's return value (RAX) is stored into that variable.

func CallMethod

func CallMethod(name string, result ...Var) Fragment

CallMethod emits an indirect call to another IR method.

func CallWithArgs added in v0.0.2

func CallWithArgs(target any, args []Fragment, result ...Var) Fragment

CallWithArgs emits a call with arguments. Arguments are passed via registers according to the calling convention (System V AMD64 ABI for x86-64, AAPCS64 for ARM64). When result is specified the callee's return value is stored into that variable.

func ConstantPointer

func ConstantPointer(variable asm.Variable) Fragment

ConstantPointer loads the address of a constant declared via LoadConstantBytes.

func DeclareLabel

func DeclareLabel(label Label, block Block) Fragment

func Goto

func Goto(label Fragment) Fragment

func ISB

func ISB() Fragment

ISB returns an instruction synchronization barrier fragment.

func If

func If(cond Condition, then Fragment, otherwise ...Fragment) Fragment

func LoadConstantBytes

func LoadConstantBytes(target asm.Variable, data []byte) Fragment

LoadConstantBytes mirrors asm.LoadConstantBytes by binding the provided byte slice to the supplied constant variable within the emitted program.

func LoadConstantBytesConfig

func LoadConstantBytesConfig(cfg ConstantBytesConfig) Fragment

LoadConstantBytesConfig binds a byte slice to an asm variable and exposes optional metadata such as zero termination and length tracking.

func MethodPointer

func MethodPointer(name string) Fragment

MethodPointer returns a placeholder for the entry address of the named IR method. The actual pointer is patched once the standalone program is linked, so the name must correspond to a method included in the Program.

func Op

func Op(kind OpKind, left, right Fragment) Fragment

func Printf

func Printf(format string, args ...any) Fragment

func Return

func Return(value any) Fragment

func Syscall

func Syscall(num defs.Syscall, args ...any) Fragment

func SyscallChecked

func SyscallChecked(cfg SyscallCheckedConfig) Fragment

SyscallChecked emits the canonical syscall + errno handling pattern used by the init runtime. It expands to:

result = syscall(number, args...)
if result < 0 {
  onError
}

The helper panics if required fields are missing so mistakes surface early during method construction.

func WithStackSlot

func WithStackSlot(cfg StackSlotConfig) Fragment

WithStackSlot creates a temporary stack allocation for the duration of Body. Callers should avoid returning from inside Body so the cleanup sequence runs.

func WriteStageResult

func WriteStageResult(cfg StageResultStoreConfig) Fragment

WriteStageResult emits the canonical pattern used by init to store a stage-encoded result: copy the low 32 bits to Base+Offset and the stage to Base+Offset+4. The function panics if required fields are missing so mistakes appear during method construction.

type GlobalConfig

type GlobalConfig struct {
	// Size controls how many bytes are reserved for the variable. Defaults to 8.
	Size int
	// Align controls the byte alignment for the variable. Defaults to 8 and must
	// be a power of two.
	Align int
}

type GlobalMem

type GlobalMem struct {
	Name  string
	Disp  Fragment
	Width ValueWidth
}

func (GlobalMem) As8

func (m GlobalMem) As8() GlobalMem

func (GlobalMem) As16

func (m GlobalMem) As16() GlobalMem

func (GlobalMem) As32

func (m GlobalMem) As32() GlobalMem

func (GlobalMem) WithDisp

func (m GlobalMem) WithDisp(disp any) Fragment

type GlobalPointerFragment

type GlobalPointerFragment struct {
	Name string
}

type GlobalVar

type GlobalVar string

func Global

func Global(name string) GlobalVar

Global declares a reference to a program-level variable. The returned handle can be used with AssignGlobal or treated as a memory reference via AsMem.

func (GlobalVar) AsMem

func (g GlobalVar) AsMem() MemoryFragment

func (GlobalVar) Mem

func (g GlobalVar) Mem() GlobalMem

Mem exposes a typed global memory reference so width helpers may be chained.

func (GlobalVar) MemWithDisp

func (g GlobalVar) MemWithDisp(disp any) GlobalMem

MemWithDisp is equivalent to Mem().WithDisp(disp) while retaining the concrete type for chaining width helpers.

func (GlobalVar) Name

func (g GlobalVar) Name() string

Name returns the string identifier backing the global. Useful when wiring globals into Program.Globals.

func (GlobalVar) Pointer

func (g GlobalVar) Pointer() Fragment

Pointer returns a placeholder pointing at the base address of the global variable. The linker resolves the final address once the standalone program layout is finalized.

type GotoFragment

type GotoFragment struct {
	Label Fragment
}

type I8Var

type I8Var struct {
	Name Var
}

type I32Var

type I32Var struct {
	Name Var
}

type ISBFragment

type ISBFragment struct{}

ISBFragment represents an Instruction Synchronization Barrier. On ARM64, this is required after modifying code in memory before executing it. On x86-64, this is a no-op since x86 has coherent instruction caches.

type IfFragment

type IfFragment struct {
	Cond      Condition
	Then      Fragment
	Otherwise Fragment
}

type Int8

type Int8 int8

type Int16

type Int16 int16

type Int32

type Int32 int32

type Int64

type Int64 int64

type IsNegativeCondition

type IsNegativeCondition struct {
	Value Fragment
}

type IsZeroCondition

type IsZeroCondition struct {
	Value Fragment
}

type Label

type Label string

type LabelFragment

type LabelFragment struct {
	Label Label
	Block Block
}

type MemVar

type MemVar struct {
	Base  Var
	Disp  Fragment
	Width ValueWidth
}

func (MemVar) As8

func (m MemVar) As8() MemVar

func (MemVar) As16

func (m MemVar) As16() MemVar

func (MemVar) As32

func (m MemVar) As32() MemVar

func (MemVar) WithDisp

func (m MemVar) WithDisp(disp any) Fragment

type MemoryFragment

type MemoryFragment interface {
	Fragment
	WithDisp(disp any) Fragment
}

type Method

type Method []Fragment

type MethodPointerFragment

type MethodPointerFragment struct {
	Name string
}

type NativeBackend added in v0.0.2

type NativeBackend interface {
	Backend
	// PrepareNativeExecution prepares a compiled program for native execution.
	// Returns a callable function, a cleanup function, and an error.
	// The cleanup function must be called when the function is no longer needed.
	PrepareNativeExecution(prog asm.Program) (asm.NativeFunc, func(), error)
}

NativeBackend extends Backend with native execution support. Implementations are only available on platforms that support native code execution.

func LookupNativeBackend added in v0.0.2

func LookupNativeBackend(arch hv.CpuArchitecture) (NativeBackend, error)

LookupNativeBackend returns the NativeBackend for the specified architecture. Returns an error if no backend is registered or if the backend does not support native execution.

type OpFragment

type OpFragment struct {
	Kind  OpKind
	Left  Fragment
	Right Fragment
}

type OpKind

type OpKind int
const (
	OpInvalid OpKind = iota
	OpAdd
	OpSub
	OpMul
	OpDiv
	OpShr
	OpShl
	OpAnd
	OpOr
	OpXor
)

type PrintfFragment

type PrintfFragment struct {
	Format string
	Args   []Fragment
}

type Program

type Program struct {
	Entrypoint string
	Methods    map[string]Method
	Globals    map[string]GlobalConfig
}

type ReturnFragment

type ReturnFragment struct {
	Value Fragment
}

type StackSlot

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

StackSlot allows callers to address the reserved memory without having to juggle raw stack pointer arithmetic.

func (StackSlot) At

func (s StackSlot) At(disp any) MemoryFragment

At returns a MemoryFragment located at the provided displacement from the slot base.

func (StackSlot) Base

func (s StackSlot) Base() MemoryFragment

Base returns a MemoryFragment covering the start of the slot.

func (StackSlot) Pointer

func (s StackSlot) Pointer() Fragment

Pointer returns the address of the slot base.

func (StackSlot) PointerWithDisp

func (s StackSlot) PointerWithDisp(disp any) Fragment

PointerWithDisp returns the address of the slot plus the provided displacement.

func (StackSlot) Size

func (s StackSlot) Size() int64

Size reports the total number of bytes reserved for the slot.

type StackSlotConfig

type StackSlotConfig struct {
	// Size is the number of bytes required by the caller. Must be > 0.
	Size int64
	// Body builds the fragment that will run while the stack slot is active.
	Body func(StackSlot) Fragment
}

StackSlotConfig describes a temporary stack reservation that should outlive a loop body. The helper subtracts Size bytes (rounded up to the requested alignment and the ABI stack alignment), exposes the slot via the provided StackSlot helper, compiles Body, and restores the stack pointer once the fragment completes.

type StackSlotContext

type StackSlotContext struct {
	Id   uint64
	Base int32
	Size int64
}

type StackSlotFragment

type StackSlotFragment struct {
	Id     uint64
	Size   int64
	Body   Fragment
	Chunks []string
}

type StackSlotMemFragment

type StackSlotMemFragment struct {
	SlotID uint64
	Disp   Fragment
	Width  ValueWidth // Width of memory access (0 means 64-bit/default)
}

func (StackSlotMemFragment) As8

As8 returns a copy with 8-bit width.

func (StackSlotMemFragment) As16

As16 returns a copy with 16-bit width.

func (StackSlotMemFragment) As32

As32 returns a copy with 32-bit width.

func (StackSlotMemFragment) WithDisp

func (m StackSlotMemFragment) WithDisp(disp any) Fragment

type StackSlotPtrFragment

type StackSlotPtrFragment struct {
	SlotID uint64
	Disp   Fragment
}

type StageResultStoreConfig

type StageResultStoreConfig struct {
	// Base points at the destination region (for example Var("page").AsMem()).
	Base MemoryFragment
	// Offset is the byte displacement for the detail (low 32-bit) field.
	Offset int64
	// Value is the encoded result (detail | stage<<shift) to store.
	Value Var
	// Scratch optionally provides a variable to receive the shifted stage. When
	// omitted the helper allocates an internal temporary.
	Scratch Var
	// Shift controls how many bits to shift Value right to obtain the stage. If
	// zero the helper uses defaultStageResultShift.
	Shift int64
}

StageResultStoreConfig describes how to split a stage-encoded uint64 into the low detail portion and the high stage tag and store them in memory.

type SyscallCheckedConfig

type SyscallCheckedConfig struct {
	// Result stores the syscall return value for later use. It must be a Var so
	// the helper can emit the common negative-result check.
	Result Var
	// Number is the syscall number (for example linux.SYS_OPENAT).
	Number defs.Syscall
	// Args provides the syscall arguments. Each element must be compatible with
	// Syscall (Var, string, or int-convertible value).
	Args []any
	// OnError runs when the syscall result is negative. Use a Block to sequence
	// multiple fragments or Goto to jump to an error label.
	OnError Fragment
}

SyscallCheckedConfig describes a syscall invocation that assigns the result to a variable and branches to an error handler when the result is negative.

type SyscallFragment

type SyscallFragment struct {
	Num  defs.Syscall
	Args []Fragment
}

type ValueWidth

type ValueWidth uint8
const (
	Width8  ValueWidth = 8
	Width16 ValueWidth = 16
	Width32 ValueWidth = 32
	Width64 ValueWidth = 64
)

type Var

type Var string

func (Var) As8

func (v Var) As8() Fragment

func (Var) As32

func (v Var) As32() Fragment

func (Var) AsMem

func (v Var) AsMem() MemoryFragment

func (Var) Mem

func (v Var) Mem() MemVar

Mem exposes a typed memory reference so width helpers (As8/As16/As32) may be chained without losing the underlying memVar type.

func (Var) MemWithDisp

func (v Var) MemWithDisp(disp any) MemVar

MemWithDisp is equivalent to Mem().WithDisp(disp) but preserves the memVar type so callers can chain width conversions.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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